diff --git "a/3651.jsonl" "b/3651.jsonl"
new file mode 100644--- /dev/null
+++ "b/3651.jsonl"
@@ -0,0 +1,1259 @@
+{"seq_id":"9108871972","text":"#\nimport itertools\n\ndef dif(li1=[], li2=[]):\n _my = [elem for elem in li1 if not elem in li2]\n return _my\n\ndef interception(li1=[], li2=[]):\n _my = [elem for elem in li1 if elem in li2]\n return _my\n\n\nclass Results:\n def __init__(self):\n self.numTable = self.build_table()\n self.statistics = []\n self.results = self.build_table()\n\n def build_table(self):\n _all = []\n def has_extra(num):\n num = str (num)\n for char in num:\n if num.count (char) > 1:\n return True\n\n for number in range(1000, 10000):\n if not has_extra(number):\n _all.append(str(number))\n\n return _all\n\n def addStatistics(self, number, bulls, cows):\n self.statistics.append((number, bulls, cows))\n\n def remove(self, arg):\n _al = []\n for i in self.results:\n if arg not in i:\n _al.append(i)\n else:\n pass\n\n self.results = _al.copy()\n\n return None\n\n def remove_with(self, args=None):\n for char in args:\n self.remove(char)\n\n def resolve(self):\n if self.statistics:\n for num, b, c in self.statistics:\n _temp = []\n num=str(num)\n for _number in self.results:\n\n if b and c:\n if self.hasCows(_number, num) == c and \\\n self.hasBulls(_number, num) == b:\n _temp.append(_number)\n elif b:\n self.KillxBull(num, b)\n elif c:\n self.results = dif(self.results, self.bulls0(num))\n if c == 4:\n self.results = interception(self.cows4(num), self.results)\n else:\n self.KillxCow(num, c)\n\n else:\n self.allIs0(num)\n if _temp:\n self.results = interception (self.results, _temp)\n return self.results\n else:\n return False\n\n def variants(self, num: str):\n _li = []\n for item in itertools.permutations (num):\n _li.append (''.join (x for x in item))\n return _li\n\n def killValue(self, value):\n try:\n self.results.remove (value)\n except ValueError:\n pass\n\n def same_pos(self, n, m):\n for _int in range(len(n)):\n if n[_int] == m[_int]:\n return True\n\n def cows4(self, num: str):\n # Also does the trick for 0 bulls\n _li = []\n for var in self.variants(num):\n if self.same_pos(num, var):\n pass\n else:\n _li.append(var)\n\n return _li\n\n def allIs0(self, num):\n self.remove_with(num)\n\n def hasCows(self, num1, num2):\n # Obtain number of cows that has num2 on num1\n # num1: num to determine cows\n # num2: num with data\n _cows = 0\n for it in range(len(num2)):\n if num2[it] in num1:\n if num2[it] != num1[it]:\n _cows += 1\n\n return _cows\n\n def hasBulls(self, num1, num2):\n # num1: num to determine bulls\n # num2: num with data\n _bulls = 0\n for it in range(len(num2)):\n if num1[it] == num2[it]:\n _bulls += 1\n\n return _bulls\n\n def bulls0(self, num):\n _li = []\n for elem in self.results:\n if self.same_pos(num, elem):\n _li.append(elem)\n return _li\n\n def KillxCow(self, num, cows):\n for elem in self.results:\n if self.hasCows(elem, num) != cows:\n self.killValue (elem)\n\n def KillxBull(self, num, bull):\n for elem in self.results:\n if self.hasBulls(elem, num) != bull:\n self.killValue(elem)\n\nif __name__ == '__main__':\n a = Results()\n\n a.addStatistics('1234', 0, 2)\n print(a.resolve())","repo_name":"luisiacc/numguess","sub_path":"logic.py","file_name":"logic.py","file_ext":"py","file_size_in_byte":4088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"75024201529","text":"import io\nimport contextlib\nimport textwrap\nfrom traceback import format_exception\nimport datetime\n\nimport discord\nfrom discord.ext import commands\nfrom tabulate import tabulate\n\nfrom bot.main import NewCommand, StringPaginator, Emoji\n\nclass SQL(commands.Cog):\n def __init__(self, client):\n self.client = client\n\n def clean_query(self, query:str) -> str:\n if query.startswith(\"```\") and query.endswith(\"```\"):\n return \" \".join(query.split(\"\\n\")[1:])[:-3]\n \n return query\n\n def chunk_result(self, ctx, result):\n entries = []\n _temp_entries = [f\"```\\n{result[i:i+1950]}\\n```\" for i in range(0, len(result), 1950)]\n for index, entry in enumerate(_temp_entries, start=1):\n entries.append(f\"{entry} Page No: `{index}/{len(_temp_entries)}`\")\n return entries\n\n @commands.command(\n name='sql',\n cls=NewCommand,\n aliases=['psotgres'],\n brief=\"Execute an SQL Statement!\",\n description=\"To Execute SQL Statement in the Bot's Database\",\n help=\"\"\"This command can execute a SQL statement (PostreSQL) into the Bot to get Bot Data and do several Operations for Bot and Data Management.\nThis is a **Developer Only** Command. Means, only the Bot owner can use this Command.\"\"\",\n usage=\" \",\n explained_usage=[\"**Query Type:** Type of Query to Execute (`fetch`/`execute`)\", \"**Query:** The SQL Query to execute. Code blocks are also Accepted.\"],\n permissions=['Developer Only'],\n bot_permissions=['Manage Messages'],\n examples=[\n \"sql execute INSERT INTO mytable VALUES (1, 'test');\",\n 'sql fetch ```sql\\nSELECT * from table;```'\n ]\n )\n @commands.is_owner()\n async def _sql(self, ctx, query_type:str, *, query:str):\n query = self.clean_query(query)\n\n async with self.client.pool.acquire() as conn:\n async with conn.transaction() as trans:\n if query_type == \"fetch\":\n temp_list = []\n try:\n data = await conn.fetch(query)\n if not data:\n return await ctx.reply(f\"Output: []\")\n for row in data:\n temp_list.append(list(row.values()))\n table = tabulate(temp_list, headers=list(data[0].keys()), showindex=\"always\", tablefmt=\"psql\")\n chunk_list = self.chunk_result(ctx, table)\n pager = StringPaginator(\n pages=chunk_list, timeout=180\n )\n await pager.start(ctx)\n except Exception as e:\n return await ctx.reply(f\"{Emoji.redcross} **Oops! Some Error Occured...**\\n> Error: `{e}`\")\n # raise e\n elif query_type == \"execute\":\n try:\n resp = await conn.execute(query)\n return await ctx.reply(f\"> Output: `{resp}`\")\n except Exception as e:\n return await ctx.reply(f\"{Emoji.redcross} **Oops! Some Error Occured...**\\n> Error: `{e}`\")\n else:\n return await ctx.reply(f\"{Emoji.redcross} Invalid Query Type! Valid Types: `fetch`/`execute`\")\n\n\ndef setup(client):\n client.add_cog(SQL(client))","repo_name":"AkshuAgarwal/Aperture-1.7","sub_path":"cogs/dev_only/sql.py","file_name":"sql.py","file_ext":"py","file_size_in_byte":3467,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"19411851658","text":"import numpy as np\nimport pandas as pd\nimport scipy.stats as stats\n\ndef hello():\n print(\"Hello\")\n\ndef getDataList(data, ivar, dvar, conditions_list):\n ''' Creates a list of arrays, each array corresponding to a different group's values for a particular\n dependent variable. The order of arrays will correspond to the order of conditions for ivar in conditions_list.\n\n Args:\n data: a pandas dataframe of the data\n ivar: a string, the column name independent variable\n dvar: a string, the column name of the dependent variable\n conditions_list: a list of the group names/identifiers found in ivar \n\n Returns:\n datalist: the list of tuples of the data in (group, data) pairs, group \n being a string and data being a numpy array.\n '''\n\n datalist = []\n for grp in conditions_list:\n df_grp = data.loc[data[ivar] == grp][dvar].to_numpy()\n datalist.append((grp,df_grp))\n return datalist\n\ndef getLongTable(datalist):\n ''' Create a long table of values and their corresponding condition group.\n\n Args:\n datalist: the list of tuples of the data in (group, data) pairs. See getDataList().\n\n Returns:\n table_df: a dataframe of the data consisting of two columns: \"Condition\" and \"Data\", \n where \"Condition\" is the group/condition name and \"Data\" is the value. \n '''\n\n series = [sr[1].tolist() for sr in datalist] \n grps = [sr[0] for sr in datalist]\n\n alldata = []\n allgrps = []\n\n for grp, data in datalist: \n allgrps.extend([grp] * len(data))\n alldata.extend(data)\n\n table_df = pd.DataFrame(list(zip(allgrps, alldata)), \n columns = ['Condition', 'Data'])\n \n return table_df\n\ndef isMinSampleSize(data, group, column_to_count, MIN_SAMPLE_SIZE = 25, debug=True):\n ''' Converts JSON files of grid node layout and grid line layout to CSV files\n\n Args:\n JSON: grid nodes\n JSON: grid lines\n\n Returns:\n Saving grid nodes as CSV\n Saving grid lines as CSV\n '''\n \n flag = True\n\n # get all counts\n grp = data.groupby(group).count().reset_index()\n grp.rename(columns={ column_to_count:'SAMPLE_SIZE'}, inplace=True)\n #return(grp)\n\n for index, value in grp['SAMPLE_SIZE'].items():\n if value < MIN_SAMPLE_SIZE: #if any are smaller, it will return false\n flag = False\n\n if debug:\n print(grp)\n print(f\"Meets Min Sample Size of {MIN_SAMPLE_SIZE}?: {flag}\")\n\n return flag \n\ndef isMinSampleSize_grps(data, ivar, MIN_SAMPLE_SIZE = 25):\n ''' Checks if each experimental group has a number of samples above a specified minimum.\n\n Args:\n data: a pandas dataframe of the data\n ivar: the independent variable to define each sample group\n MIN_SAMPLE_SIZE: the minimum sample size\n\n Returns:\n flag: True if all samples have more values than the minimum, False otherwise \n '''\n flag = True\n\n cts = data[ivar].value_counts()\n\n for ct in cts:\n if ct < MIN_SAMPLE_SIZE: #if any are smaller, it will return false\n flag = False\n\n return flag \n\ndef checkSamplesEqual(data, ivar, TOL = 0.15):\n ''' Checks if each experimental group has a roughly equal number of samples.\n\n Args:\n data: a pandas dataframe of the data\n ivar: the independent variable to define each sample group\n TOL: the percentage tolderance of differences \n\n Returns:\n flag: True if all samples are roughly equal, False otherwise \n '''\n flag = True\n\n cts = data[ivar].value_counts()\n\n tolVal = np.mean(cts) * TOL \n\n for ct in cts:\n for ct2 in cts: \n if abs(ct - ct2) > tolVal: #if difference is greater than tolerance, return false\n flag = False\n\n return flag \n\ndef addProcessedCol(df, col_og, newname, name_dict):\n ''' Adds a new column based on an existing column with a new name and renamed values. Edits the existing dataframe.\n\n Args:\n df: a pandas dataframe of the data\n col_og: the original column name\n newname: the new column name\n name_dict: a dictionary of names in old:new pairs\n\n '''\n df[newname] = np.nan \n for j in df.index:\n val_og = df.loc[j, col_og]\n for item in name_dict:\n if (val_og == item):\n df.loc[j, newname] = name_dict[item]\n\n\ndef plotStats(data, ivar, dvar, conditions_list, phoc, pal, ylims=None, test=\"tukey\", lbl=\"\"):\n '''\n Ref: https://blog.4dcu.be/programming/2021/12/30/Posthoc-Statannotations.html \n\n Args: \n data: pandas dataframe of the data\n ivar: string, column name of the independent variable\n dvar: string, column name of the dependent variable\n conditions_list: list of strings, names of groups for independent variable\n phoc: returned results from tukey or dunn\n pal: dictionary, palettes for conditions\n ylims: tuple of y-axis limits, if any\n test: string, must be tukey or dunn\n\n '''\n from statannotations.Annotator import Annotator\n import matplotlib.pyplot as plt\n import seaborn as sns\n\n # format post-hoc tests into a non-reduntant list of comparisons with p value\n if test == \"tukey\":\n stat_df = pd.DataFrame(data=phoc._results_table.data[1:], columns=phoc._results_table.data[0])\n elif test == \"dunn\":\n dunn = phoc.set_axis(conditions_list, axis=1)\n dunn.set_axis(conditions_list, axis=0, inplace=True)\n \n remove = np.tril(np.ones(dunn.shape), k=0).astype(\"bool\")\n dunn[remove] = np.nan\n\n stat_df = dunn.melt(ignore_index=False).reset_index().dropna()\n stat_df.set_axis([\"group1\", \"group2\", \"p-adj\"], axis=1, inplace=True)\n elif test == \"none\": # no significant results, so no post-hoc test\n # generate dummy list for annotations\n import itertools\n cmbs = itertools.combinations(conditions_list, 2)\n g1 = []\n g2 = []\n pv = []\n for comb in cmbs:\n g1.append(comb[0])\n g2.append(comb[1])\n pv.append(1)\n d = {\"group1\":g1, \"group2\":g2, \"p-adj\":pv}\n stat_df = pd.DataFrame(data=d)\n \n else: \n print(\"Error: test must be tukey, dunn, or none\")\n return\n \n plt.figure(figsize = (3,4))\n\n pairs = [(i[1][\"group1\"], i[1][\"group2\"]) for i in stat_df.iterrows()]\n p_values = [i[1][\"p-adj\"] for i in stat_df.iterrows()]\n\n plt.tight_layout()\n\n sns.set(style=\"whitegrid\")\n\n ax = sns.barplot(data=data, x=ivar, y=dvar, order=conditions_list, palette=pal, capsize=.1, alpha=0.6)\n #sns.stripplot(data=data, x=ivar, y=dvar, order=conditions_list, palette=pal, dodge=True, alpha=0.35, ax=ax, jitter=0.15)\n sns.swarmplot(data=data, x=ivar, y=dvar, order=conditions_list, color=\"black\", dodge=True, size=2.5, alpha=0.2, ax=ax)\n ax.grid(False)\n ax.text(x=0.5, y=-0.3, s=lbl, fontsize=20, ha='center', va='bottom', transform=ax.transAxes)\n if ylims is not None:\n plt.ylim(ylims[0], ylims[1])\n annot = Annotator(\n ax, pairs, data=data, x=ivar, y=dvar, order=conditions_list, fontsize=20\n )\n annot.configure(text_format=\"star\", loc=\"outside\")\n annot.set_pvalues_and_annotate(p_values)\n\ndef isNormal(datalist, debug = True, type = \"Shapiro\"):\n ''' Normality Tests. \n \n ref: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.normaltest.html\n\n null hypothesis: sample come from a normal distribution ~ i.e. Normal\n rejecting the null hypothesis means it is NOT normal\n\n Logic \n Null hypothesis: Data follows a normal distribution\n alternatie hypothesis: Data do not follow a normal distribution \n\n If p<0.05, NOT normal, reject null hypothesis \n If p>0.05, ARE normal distributions, fail to reject null hypothesis\n\n Args:\n datalist: the list of tuples of the data in (group, data) pairs. See getDataList().\n\n Returns:\n flag: True if all groups are normal, False otherwise \n '''\n\n if type == \"Shapiro\":\n print(\"Performing Shapiro-Wilk normality test...\")\n alpha = 0.05\n print(f\"alpha_value: {alpha}\")\n\n flag = True\n for dt in datalist:\n grp = dt[0]\n series = dt[1]\n shapiro_test = stats.shapiro(series)\n print(shapiro_test)\n p = shapiro_test[1]\n w = shapiro_test[0]\n if p < alpha:\n if debug:\n print(f\"Series {grp}: is NOT normal. W:{w}, Pvalue: {p}\")\n flag = False\n else:\n if debug:\n print(f\"Series {grp}: IS normal. W:{w}, Pvalue: {p}\")\n if debug:\n print(f\"Normality Assumption Met? : {flag}\")\n return flag\n\n else: # D’Agostino and Pearson’s Normality Test\n print(\"Performing D'Agostino-Pearson's normality test...\")\n flag = True\n # alpha = 1e-3 #0.001\n alpha = 0.05\n print(f\"alpha_value: {alpha}\")\n\n for dt in datalist:\n grp = dt[0]\n series = dt[1]\n k2, p = stats.normaltest(series)\n if p < alpha:\n if debug:\n print(f\"Series {grp}: is NOT normal. Pvalue: {p}\")\n flag = False\n else:\n if debug:\n print(f\"Series {grp}: IS normal. Pvalue: {p}\")\n if debug:\n print(f\"Normality Assumption Met? : {flag}\")\n return flag\n\n\ndef isEqualVariances(datalist, isVeryNotNormal=True):\n \"\"\" Check Unequal Sample Sizes\n Check the equality of variances for a variable\n Ref: https://stats.stackexchange.com/questions/135232/bartletts-test-vs-levenes-test\n Ref: https://www.itl.nist.gov/div898/handbook/eda/section3/eda357.\n Bartlett's test is sensitive to departures from normality. That is, if your samples come from non-normal distributions, then Bartlett's test may simply be testing for non-normality.\n The Levene test is an alternative to the Bartlett test that is less sensitive to departures from normality.\n\n Logic\n Null hypothesis : all samples are from populations with equal variances\n\n Args:\n datalist: the list of tuples of the data in (group, data) pairs. See getDataList().\n isVeryNotNormal: Boolean, use True if the samples come from non-normal distributions.\n\n Returns:\n True if all populations have equal variance, False otherwise \n \"\"\"\n\n print(\"Performing Equal Variances Test...\")\n if isVeryNotNormal:\n return LeveneTest(datalist)\n else:\n return BartlettTest(datalist)\n\n\ndef LeveneTest(datalist):\n ''' Helper function for isEqualVariances(). Perform Levene test. \n\n Args:\n datalist: the list of tuples of the data in (group, data) pairs. See getDataList().\n\n Returns:\n True if all populations have equal variance, False otherwise \n '''\n print(\"Performing Levene Test...\")\n args = [sr[1]\n for sr in datalist] # this returns a list of series\n\n levene_result = stats.levene(*args) # [0] statistic, [1] pvalue\n print(\"homogeneity test:\", levene_result)\n if levene_result[1] < 0.05:\n print(f\"The populations do NOT have equal variances.\")\n return False\n else:\n print(f\"The populations have equal variances.\")\n return True\n\ndef BartlettTest(datalist):\n ''' Helper function for isEqualVariances(). Perform Bartlett test. \n\n There are significant deviations from normality, use\n Null hypothesis is that each group has the same variance\n Ref: https://www.statology.org/welchs-anova-in-python/\n\n Args:\n datalist: the list of tuples of the data in (group, data) pairs. See getDataList().\n\n Returns:\n True if all populations have equal variance, False otherwise \n '''\n\n print(\"Performing Bartlett Test of Homogeneity of Variances...\")\n args = [sr[1]\n for sr in datalist] # this returns a list of series\n bartlett_result = stats.bartlett(*args)\n print(\"Result:\", bartlett_result)\n if bartlett_result[1] < 0.05:\n print(f\"The populations do NOT have equal variances.\")\n return False\n else:\n print(f\"The populations have equal variances.\")\n return True\n\n\ndef passesBasicAnova(datalist):\n ''' Perform basic one-way ANOVA. \n\n Args:\n datalist: the list of tuples of the data in (group, data) pairs. See getDataList().\n\n Returns:\n True if at least one of the means of the groups is significantly different, False otherwise \n '''\n print(\"Performing ANOVA\")\n args = [sr[1]\n for sr in datalist] # this returns a list of series\n anova = stats.f_oneway(*args) # [0] statistic, [1] pvalue\n print(anova)\n if anova[1] < 0.05:\n print(\n \"ANOVA found signifance. At least one of the means of the groups is different.\")\n return True\n else:\n print(\"oneway ANOVA: no significance. No significant difference between means of the groups.\")\n return False\n # return anova\n\ndef anovaP(datalist):\n ''' Perform basic one-way ANOVA and return p value. \n\n Args:\n datalist: the list of tuples of the data in (group, data) pairs. See getDataList().\n\n Returns:\n p: the p-value. \n '''\n args = [sr[1]\n for sr in datalist] # this returns a list of series\n anova = stats.f_oneway(*args) # [0] statistic, [1] pvalue\n return anova[1]\n\ndef passesAnovaWelch(datalist, var_equal=False):\n ''' Perform ANOVA with Welch Statistic. \n\n Args:\n datalist: the list of tuples of the data in (group, data) pairs. See getDataList().\n\n Returns:\n True if at least one of the means of the groups is significantly different, False otherwise \n '''\n \n import scipy\n from collections import namedtuple\n # https://svn.r-project.org/R/trunk/src/library/stats/R/oneway.test.R\n # translated from R Welch ANOVA (not assuming equal variance)\n\n args = [sr[1] for sr in datalist] # this returns a list of series\n\n F_onewayResult = namedtuple('F_onewayResult', ('statistic', 'pvalue'))\n\n args = [np.asarray(arg, dtype=float) for arg in args]\n k = len(args)\n ni = np.array([len(arg) for arg in args])\n mi = np.array([np.mean(arg) for arg in args])\n vi = np.array([np.var(arg, ddof=1) for arg in args])\n wi = ni/vi\n\n tmp = sum((1-wi/sum(wi))**2 / (ni-1))\n tmp /= (k**2 - 1)\n\n dfbn = k - 1\n dfwn = 1 / (3 * tmp)\n\n m = sum(mi*wi) / sum(wi)\n f = sum(wi * (mi - m)**2) / ((dfbn) * (1 + 2 * (dfbn - 1) * tmp))\n prob = scipy.special.fdtrc(dfbn, dfwn, f) # equivalent to stats.f.sf\n\n print(F_onewayResult(f, prob))\n if prob < 0.05:\n print(\"ANOVA with Welch Statistic: SIGNIFICANCE. At least one of the means of the groups is different.\")\n return True\n else:\n print(\"ANOVA with Welch Statistic: NO significance. No significant difference between means of the groups.\")\n return False\n\n # return F_onewayResult(f, prob)\n\ndef anovaWelchP(datalist, var_equal=False):\n ''' Perform ANOVA with Welch Statistic and return the p-value.\n\n Args:\n datalist: the list of tuples of the data in (group, data) pairs. See getDataList().\n\n Returns:\n prob: the p-value. \n '''\n \n import scipy\n from collections import namedtuple\n # https://svn.r-project.org/R/trunk/src/library/stats/R/oneway.test.R\n # translated from R Welch ANOVA (not assuming equal variance)\n\n args = [sr[1] for sr in datalist] # this returns a list of series\n\n F_onewayResult = namedtuple('F_onewayResult', ('statistic', 'pvalue'))\n\n args = [np.asarray(arg, dtype=float) for arg in args]\n k = len(args)\n ni = np.array([len(arg) for arg in args])\n mi = np.array([np.mean(arg) for arg in args])\n vi = np.array([np.var(arg, ddof=1) for arg in args])\n wi = ni/vi\n\n tmp = sum((1-wi/sum(wi))**2 / (ni-1))\n tmp /= (k**2 - 1)\n\n dfbn = k - 1\n dfwn = 1 / (3 * tmp)\n\n m = sum(mi*wi) / sum(wi)\n f = sum(wi * (mi - m)**2) / ((dfbn) * (1 + 2 * (dfbn - 1) * tmp))\n prob = scipy.special.fdtrc(dfbn, dfwn, f) # equivalent to stats.f.sf\n return prob\n\n# Krukal Wallis Test by Condition\n# Reference (KW): https://data.library.virginia.edu/getting-started-with-the-kruskal-wallis-test/#:~:text=If%20we%20have%20a%20small,different%20distribution%20than%20the%20others.\n# Reference(KW): https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kruskal.html\n# Reference (Dunn): https://scikit-posthocs.readthedocs.io/en/latest/generated/scikit_posthocs.posthoc_dunn/\n# Reference (Dunn) Interpretation: https://www.statology.org/dunns-test-python/\n\n# Logic\n# If p>0.05, we cannot reject the null hypothesis. The samples come from the same distirbution, therefore there is no significant difference between the groups.\n# If p<0.05, we can reject the null hypothesis. There is a significant difference between the groups.\n\ndef Kruskal_Wallis_Test(datalist, alpha=0.05, debug=True):\n ''' Krukal Wallis Test by Condition\n Reference (KW): https://data.library.virginia.edu/getting-started-with-the-kruskal-wallis-test/#:~:text=If%20we%20have%20a%20small,different%20distribution%20than%20the%20others.\n Reference(KW): https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kruskal.html\n Reference (Dunn): https://scikit-posthocs.readthedocs.io/en/latest/generated/scikit_posthocs.posthoc_dunn/\n Reference (Dunn) Interpretation: https://www.statology.org/dunns-test-python/\n\n Logic\n If p>0.05, we cannot reject the null hypothesis. The samples come from the same distirbution, therefore there is no significant difference between the groups.\n If p<0.05, we can reject the null hypothesis. There is a significant difference between the groups. \n\n Args:\n datalist: the list of tuples of the data in (group, data) pairs. See getDataList().\n\n Returns:\n first value: the results of the dunn post-hoc tests if a significant result was found\n second value: string, which post-hoc test was used (dunn in this case)\n third value: string, label of which tests were performed\n\n '''\n\n import scikit_posthocs as sp\n import itertools\n\n phoc = None \n\n flag = True\n # alpha = 5e-2 #0.05\n print(f\"alpha: {alpha}\")\n\n args = [sr[1] for sr in datalist] # this returns a list of series\n grps = [sr[0] for sr in datalist] # list of experimental groups\n\n # for key in data_dict:\n # print(key)\n\n # RUN KW Test\n # Inputs are *individual series, one for each category\n kw_result = stats.kruskal(*args)\n statistic = kw_result[0]\n pvalue = kw_result[1]\n if debug:\n print(kw_result)\n\n flag = False\n if pvalue < alpha: # KW returns significant result\n print(\"Significant Result for Kruskal Wallis.\")\n else:\n print(\"No significant result for Kruskal Wallis.\")\n\n print(\"Compute the DUNN post-hoc test.\")\n dunn = sp.posthoc_dunn(args, p_adjust='bonferroni')\n phoc = dunn\n\n if debug:\n print(f\"{dunn}\")\n # print(dunn[1])\n # print(dunn[1][4])\n # print(len(dunn))\n\n # Print Significance Results for Dunn\n print(\"Pairwise Dunn P-Values:\")\n conds = np.arange(1, len(dunn)+1, 1)\n combs = list(itertools.combinations(conds, 2))\n\n for i in combs:\n if dunn[i[0]][i[1]] <= 0.001:\n print(\n f\"{i}: {grps[i[0]-1]}-{grps[i[1]-1]} : pvalue = {dunn[i[0]][i[1]]} : SIGNIFICANT (***)\")\n flag = True\n elif dunn[i[0]][i[1]] <= 0.01:\n print(\n f\"{i}: {grps[i[0]-1]}-{grps[i[1]-1]} : pvalue = {dunn[i[0]][i[1]]} : SIGNIFICANT (**)\")\n flag = True\n elif dunn[i[0]][i[1]] <= alpha:\n print(\n f\"{i}: {grps[i[0]-1]}-{grps[i[1]-1]} : pvalue = {dunn[i[0]][i[1]]} : SIGNIFICANT (*)\")\n flag = True\n else:\n # print(f\"{i}: {grps[i[0]]}-{grps[i[1]]} : pvalue = {dunn[i[0]][i[1]]} : not significant\")\n pass\n \n\n \n\n if flag:\n return phoc, \"dunn\", \"Kruskal-Wallis, Dunn posthoc\"\n else:\n return None, \"none\", \"Kruskal-Wallis\"\n\ndef kruskalWallisP(datalist, alpha=0.05, debug=True):\n ''' Krukal Wallis Test by Condition, return p value.\n Reference (KW): https://data.library.virginia.edu/getting-started-with-the-kruskal-wallis-test/#:~:text=If%20we%20have%20a%20small,different%20distribution%20than%20the%20others.\n Reference(KW): https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kruskal.html\n Reference (Dunn): https://scikit-posthocs.readthedocs.io/en/latest/generated/scikit_posthocs.posthoc_dunn/\n Reference (Dunn) Interpretation: https://www.statology.org/dunns-test-python/\n\n Logic\n If p>0.05, we cannot reject the null hypothesis. The samples come from the same distirbution, therefore there is no significant difference between the groups.\n If p<0.05, we can reject the null hypothesis. There is a significant difference between the groups. \n\n Args:\n datalist: the list of tuples of the data in (group, data) pairs. See getDataList().\n\n Returns:\n pvalue: the p-value.\n\n '''\n\n import scikit_posthocs as sp\n import itertools\n\n phoc = None \n\n flag = True\n # alpha = 5e-2 #0.05\n\n args = [sr[1] for sr in datalist] # this returns a list of series\n grps = [sr[0] for sr in datalist] # list of experimental groups\n\n # for key in data_dict:\n # print(key)\n\n # RUN KW Test\n # Inputs are *individual series, one for each category\n kw_result = stats.kruskal(*args)\n statistic = kw_result[0]\n pvalue = kw_result[1]\n return pvalue\n\ndef TukeyTest(datalist):\n ''' Perform Tukey Test to find which groups have a significant difference. Prints results. \n\n Args:\n datalist: the list of tuples of the data in (group, data) pairs. See getDataList().\n\n Returns:\n tukey: tukey results\n\n '''\n print(\"Performing Tukey Post-Hoc Test...\")\n from statsmodels.stats.multicomp import pairwise_tukeyhsd\n\n long_table = getLongTable(datalist)\n \n tukey = pairwise_tukeyhsd(endog=long_table['Data'].to_numpy(), groups=long_table['Condition'], alpha=0.05)\n print(tukey)\n return tukey\n \n\ndef StatTest_checkSamples(datalist):\n ''' Helper function for StatTest. \n\n Args:\n datalist: the list of tuples of the data in (group, data) pairs. See getDataList().\n\n Returns:\n first value: the results of the post-hoc tests if a significant result was found\n second value: string, which post-hoc test was used\n third value: string, label of which tests were performed\n\n '''\n if isEqualVariances(datalist):\n print('[StatTest] Assumption of Equal Variances was met. Run basic ANOVA.')\n print ('---------------------------------------------')\n if passesBasicAnova(datalist):\n print('[StatTest] Basic ANOVA found significance. Run Tukey post-hoc test.')\n print ('---------------------------------------------')\n phoc = TukeyTest(datalist)\n return phoc, \"tukey\", \"basic ANOVA, Tukey posthoc\"\n else:\n print(\"[StatTest] Tukey found NO statistically significance found between groups.\")\n print ('---------------------------------------------')\n phoc = TukeyTest(datalist)\n return None, \"none\", \"basic ANOVA\"\n else: \n print('[StatTest] Assumption of Equal Variances was violated. Run ANOVA with Welch Statistic.')\n if passesAnovaWelch(datalist):\n print('[StatTest] ANOVA with Welch Statistic found significance. Run Tukey post-hoc test.')\n print ('---------------------------------------------')\n phoc = TukeyTest(datalist)\n return phoc, \"tukey\", \"ANOVA with Welch, Tukey posthoc\"\n else:\n print(\"[StatTest] Tukey found NO statistically significance found between groups.\")\n print ('---------------------------------------------')\n phoc = TukeyTest(datalist)\n return None, \"none\", \"ANOVA with Welch\"\n\n\ndef StatTest(data, ivar, dvar, conditions_list, viz=False, pal=None, ylims=None):\n ''' Main function for running statistical tests. Only works for one question/column of data at a time. \n Will print results. \n\n Args:\n data: a pandas dataframe of the data\n ivar: a string, the column name independent variable\n dvar: a string, the column name of the dependent variable\n conditions_list: a list of the group names/identifiers found in ivar\n viz: boolean. True if plotting the results is desired\n pal: dictionary, palettes for conditions\n\n Returns: \n p: the p-value\n tst: a string indicating which statistical test was used\n\n '''\n datalist = getDataList(data, ivar, dvar, conditions_list)\n\n results = None\n \n if isMinSampleSize_grps(data, ivar):\n # check sample sizes roughly equal\n print('[StatTest] Minimal Sample Size was met. Check if sample sizes are roughly equal.') \n print ('---------------------------------------------')\n results = StatTest_checkSamples(datalist)\n\n else: \n print ('[StatTest] Minimal Sample Size was not met. Proceed to check Normality Assumption.')\n print ('---------------------------------------------')\n if isNormal(datalist):\n print('[StatTest] Normality Assumption was met. Check if sample sizes are roughly equal.')\n print ('---------------------------------------------')\n results = StatTest_checkSamples(datalist)\n else:\n print ('[StatTest] Normality Assumption was not met. Proceed with Kruskal-Wallis Test')\n print ('---------------------------------------------')\n results = Kruskal_Wallis_Test(datalist)\n\n # plot results\n if viz:\n plotStats(data, ivar, dvar, conditions_list, results[0], pal, ylims=ylims, test=results[1], lbl=results[2])\n\n # get p-value\n tst = results[2]\n p = 1\n if \"ANOVA with Welch\" in tst:\n p = anovaWelchP(datalist)\n elif \"basic ANOVA\" in tst:\n p = anovaP(datalist)\n elif \"Kruskal-Wallis\" in tst:\n p = kruskalWallisP(datalist)\n\n return p, tst\n","repo_name":"mitmedialab/nmi-ai-2023","sub_path":"Include/stat_process.py","file_name":"stat_process.py","file_ext":"py","file_size_in_byte":26237,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"77"}
+{"seq_id":"9585655689","text":"from family_tree import FamilyTree\n\n\nclass Shell:\n start_sign = '> '\n exit_command = 'exit'\n query_command = '?-'\n cmd_pattern = ' [objects] | -> | table | back | exit'\n\n def __init__(self, database: str = None, program: str = None):\n self.family_tree = FamilyTree()\n\n if program is not None:\n self.execute_file(program)\n status = None\n if database is not None:\n status = self.parse_file(database)\n if status != 'exit':\n self.main_loop()\n\n def parse_command(self, command: str):\n command = command.strip('\\n')\n if not len(command):\n return\n if command == 'table':\n self.family_tree.print_as_table()\n return\n if command == 'back':\n self.family_tree.remove_last_predicate()\n return\n\n args = command.split()\n if len(args) < 2:\n raise ValueError(f'Incorrect format. Use follow pattern: {self.cmd_pattern}')\n\n if args[0] == self.query_command:\n self.family_tree.query(' '.join(args[1:]))\n else:\n self.family_tree.apply(args)\n\n def parse_file(self, file):\n with open(file) as f:\n lines = f.readlines()\n for command in lines:\n if command == self.exit_command:\n break\n try:\n self.parse_command(command)\n except Exception as e:\n print(f'[Error] {e}')\n return command # return last executed command\n\n def execute_file(self, file):\n self.family_tree.consult(file)\n\n def main_loop(self):\n command = input(self.start_sign)\n while command != self.exit_command:\n try:\n self.parse_command(command)\n except Exception as e:\n print(f'[Error] {e}')\n command = input(self.start_sign)\n print('Bye!')\n\n","repo_name":"azavodov/family-tree","sub_path":"shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"13840643839","text":"# natnael abay\r\n#se.natnael.abay@gmail.com\r\ndef insertionSort(lst):\r\n for i in range(1,len(lst)):\r\n current = lst[i]\r\n while lst[i-1]>current and i>0:\r\n lst[i] = lst[i-1]\r\n i = i-1\r\n lst[i] = current\r\n return lst\r\n\r\nprint(insertionSort([5,2,1,9,0,4,6]))\r\n","repo_name":"natnaelabay/comptetive-programming","sub_path":"CP/D4/Inesrtion Sort.py","file_name":"Inesrtion Sort.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"559933546","text":"import xml.etree.ElementTree as ET\nimport glob\ndef parse():\n xlist = glob.glob(\"../../DDL/*.xml\")\n ret=[]\n for xml in xlist:\n tree = ET.parse(xml)\n root = tree.getroot()\n for a in root.findall('Sensor'):\n for b in a.findall('Interation'):\n for c in b.findall('Topic'):\n for d in b.findall('Dashboard'):\n if d.attrib['show'] == '1':\n ret.append(c.text)\n for a in root.findall('Actuator'):\n for b in a.findall('Interation'):\n for c in b.findall('Topic'):\n for d in b.findall('Dashboard'):\n if d.attrib['show'] == '1':\n ret.append(c.text)\n return ret\n","repo_name":"cjnbill/IOT","sub_path":"Source/CloudServer/dashboard/dashboard/xmlparser.py","file_name":"xmlparser.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"69857809528","text":"# -*- coding: utf-8 -*-\nimport hashlib\nfrom binascii import b2a_hex, a2b_hex\nfrom Crypto.Cipher import AES\nfrom Crypto import Random\n\nclass MyCrypt():\n def __init__(self, key):\n self.key = hashlib.md5(key).hexdigest()\n self.iv = b'0000000000000000'\n self.mode = AES.MODE_CBC\n\n def encrypt(self, text):\n cryptor = AES.new(self.key, self.mode, self.iv)\n length = 16\n count = len(text)\n add = length - (count % length)\n text = text + ('\\0' * add)\n self.ciphertext = cryptor.encrypt(text)\n return b2a_hex(self.ciphertext)\n\n def decrypt(self, text):\n cryptor = AES.new(self.key, self.mode, self.iv)\n plain_text = cryptor.decrypt(a2b_hex(text))\n return plain_text.rstrip('\\0')\n","repo_name":"keelii/snote","sub_path":"app/crypt.py","file_name":"crypt.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":71,"dataset":"github-code","pt":"77"}
+{"seq_id":"4487056585","text":"import pandas as pd\nimport scipy.stats\nimport numpy as np\nfrom sklearn.metrics import auc, roc_curve\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\n\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LogisticRegression\n\n\ndef roc_calc(labels, score):\n fpr, tpr, thresholds = roc_curve(labels, score)\n roc = auc(fpr, tpr)\n return roc\n\n\ndef geom_p_calc(total, outlier, tumor, common):\n return scipy.stats.hypergeom.sf(common - 1, total, outlier, tumor)\n\n\ncancer = pd.DataFrame(pd.read_csv('../demo/input.txt', sep='\\t'))\ncancer = cancer.set_index('Symbol').transpose()\nscaler = MinMaxScaler()\nscaled_values = scaler.fit_transform(cancer)\ncancer.loc[:, :] = scaled_values\n\ncancer_type = 1\nmask = (cancer.TYPE == 0) | (cancer.TYPE == cancer_type)\ncancer = cancer[mask]\nmask = (cancer.TYPE != 0)\ncancer.loc[mask, 'TYPE'] = 1\ncancer_type = 1\n\nmask = (cancer.TYPE != 0)\ncancer.loc[mask, 'TYPE'] = 2\n\nmask = (cancer.TYPE == 0)\ncancer.loc[mask, 'TYPE'] = 1\n\nmask = (cancer.TYPE == 2)\ncancer.loc[mask, 'TYPE'] = 0\n\ncancer_type = 1\nX_train, X_test, y_train, y_test = train_test_split(cancer,\n cancer.TYPE,\n test_size=0.3)\n\nX_train, X_train_test, y_train, y_train_test = train_test_split(X_train,\n y_train,\n test_size=0.3)\n\nnormal = X_train[X_train.TYPE == 0]\n\nresult = pd.DataFrame()\nresult = result.append(normal.quantile(.25))\nresult = result.append(normal.quantile(.75))\niqr = result.iloc[1] - result.iloc[0]\niqr.name = 'iqr'\nresult = result.append(iqr)\nfence_low = result.iloc[0] - 1.5 * result.iloc[2]\nfence_low.name = 'fence_low'\nresult = result.append(fence_low)\nfence_high = result.iloc[1] + 1.5 * result.iloc[2]\nfence_high.name = 'fence_high'\nresult = result.append(fence_high)\n\n#Reference Range\ntotal = len(normal.columns)\ntumor = X_train[X_train.TYPE == cancer_type]\nct = (tumor > result.iloc[4]).sum(axis=0)\noutliers = ct[ct > max(ct) * 0.2].index.to_list()[:-1]\n\n#Prediction\ntrain_tumor = (X_train_test > result.iloc[4]).sum(axis=1)\ntrain_test = X_train_test[outliers]\ncommons = (train_test > result.iloc[4]).sum(axis=1)\nscore = []\nfor exp in commons.index.to_list():\n common = commons[exp]\n total = 10709\n outlier = len(outliers)\n n = train_tumor[exp]\n print(n)\n pval = geom_p_calc(total, outlier, n, common)\n if pval == 0:\n pval = 1e-100\n score.append(-np.log10(pval))\nroc_val = roc_calc(y_train_test, score)\n#Output\nprint(\"roc:\", roc_val)\nwith open('../demo/output.txt', 'w') as f:\n f.write('Pre\\tReal\\n')\n for pre, real in zip(y_train_test, score):\n f.write(str(pre) + '\\t' + str(real) + '\\n')\n","repo_name":"FirmianaPlatform/ccRCC","sub_path":"code/prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":2850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"7078115586","text":"from bigdl.optim.optimizer import Adam\nfrom tensorflow.python.keras.datasets import imdb\nfrom tensorflow.python.keras.preprocessing import sequence\nfrom zoo.pipeline.api.keras.models import Model\nfrom zoo.pipeline.api.keras.layers import *\nfrom zoo.common.nncontext import init_spark_conf\nfrom zoo.common.nncontext import init_nncontext\n\n\nconf = init_spark_conf()\nconf.set(\"spark.executor.extraJavaOptions\", \"-Xss512m\")\nconf.set(\"spark.driver.extraJavaOptions\", \"-Xss512m\")\nsc = init_nncontext(conf)\nmax_features = 20000\nmax_len = 200\n\nprint('Loading data...')\n(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)\nprint(len(x_train), 'train sequences')\nprint(len(x_test), 'test sequences')\n\nprint('Pad sequences (samples x time)')\nx_train = sequence.pad_sequences(x_train, maxlen=max_len)\nx_test = sequence.pad_sequences(x_test, maxlen=max_len)\nprint('x_train shape:', x_train.shape)\nprint('x_test shape:', x_test.shape)\n\n\ntrain_pos = np.zeros((len(x_train), max_len), dtype=np.int32)\nval_pos = np.zeros((len(x_test), max_len), dtype=np.int32)\nfor i in range(0, len(x_train)):\n train_pos[i, :] = np.arange(max_len)\n val_pos[i, :] = np.arange(max_len)\n\n\ndef build_sample(token_id, position_id, label):\n samples = []\n for i in range(label.shape[0]):\n sample = Sample.from_ndarray([token_id[i], position_id[i]], np.array(label[i]))\n samples.append(sample)\n return samples\n\n\ntrain_samples = build_sample(x_train, train_pos, y_train)\ntrain_rdd = sc.parallelize(train_samples)\nval_samples = build_sample(x_test, val_pos, y_test)\nval_rdd = sc.parallelize(val_samples)\n\ntoken_shape = (max_len,)\nposition_shape = (max_len,)\ntoken_input = Input(shape=token_shape)\nposition_input = Input(shape=position_shape)\nO_seq = TransformerLayer.init(\n vocab=max_features, hidden_size=128, n_head=8, seq_len=max_len)([token_input, position_input])\n# Select the first output of the Transformer. The second is the pooled output.\nO_seq = SelectTable(0)(O_seq)\nO_seq = GlobalAveragePooling1D()(O_seq)\nO_seq = Dropout(0.2)(O_seq)\noutputs = Dense(2, activation='softmax')(O_seq)\n\nmodel = Model([token_input, position_input], outputs)\nmodel.summary()\n\nmodel.compile(optimizer=Adam(),\n loss=\"sparse_categorical_crossentropy\",\n metrics=['accuracy'])\n\nbatch_size = 128\nprint('Train...')\nmodel.fit(train_rdd,\n batch_size=batch_size,\n nb_epoch=1)\nprint(\"Train finished.\")\n\nprint('Evaluating...')\nscore = model.evaluate(val_rdd, batch_size=128)[0]\nprint(score)\n\nprint(\"finished...\")\nsc.stop()\n","repo_name":"pinggao187/zoo-readthedocs","sub_path":"pyzoo/zoo/examples/attention/transformer.py","file_name":"transformer.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"23343781684","text":"\"\"\"\r\nAuthor: Team Alpha Squad\r\nDate : Sat 01 August 2020\r\nInput : List of reviews called as corpus\r\n\r\nAttribute object has filtered_attributes that containt the dynamically found attribute list\r\n\"\"\"\r\n\r\n \r\nfrom nltk.corpus import wordnet\r\nimport sys\r\nsys.path.append(\"../\")\r\nfrom nltk.tokenize import word_tokenize\r\nfrom preprocessings.basic import file_to_list\r\n\r\ndef return_all_synonyms(word_list):\r\n dict_word = {key: set() for key in word_list}\r\n\r\n for word in word_list:\r\n for syn in wordnet.synsets(word):\r\n \t\tfor l in syn.lemmas():\r\n \t\t\tdict_word[word].add(l.name())\r\n \r\n word_list = []\r\n for key in dict_word:\r\n word_list.append(list(dict_word[key]))\r\n \r\n return word_list\r\n\r\n\r\nclass Attributes:\r\n \r\n def __init__(self,corpus):\r\n self.attributes_ = file_to_list(\"main/resources/attribute_list.txt\") \r\n all_attributes = return_all_synonyms(self.attributes_)\r\n self.filtered_attributes = self.select_attributes(corpus, all_attributes)\r\n \r\n def select_attributes(self, corpus, all_attributes):\r\n dict_att = {key: 0 for key in self.attributes_}\r\n for review in corpus:\r\n words = word_tokenize(str(review))\r\n \r\n for word in words:\r\n for i in range(len(self.attributes_)):\r\n if word in all_attributes[i]:\r\n dict_att[self.attributes_[i]]+=1\r\n dict_att1 = sorted(dict_att.items(), key=lambda x: x[1], reverse = True)\r\n dict_att1 = dict_att1[:5]\r\n return [tuple_[0] for tuple_ in dict_att1]\r\n","repo_name":"kr-praveen/NM396_Alpha_Squad","sub_path":"brain/aspect_based/filter_aspects.py","file_name":"filter_aspects.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"43775049922","text":"'''\nGiven a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.\nA mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.\n'''\n\nfrom collections import deque\nclass Solution(object):\n def letterCombinations(self, digits):\n \"\"\"\n :type digits: str\n :rtype: List[str]\n \"\"\"\n \n if digits == \"\":\n return [] \n \n phone_keys = {2:\"abc\",3:\"def\",4:\"ghi\",5:\"jkl\",6:\"mno\",7:\"pqrs\",8:\"tuv\",9:\"wxyz\"}\n \n q = deque(phone_keys[int(digits[0])])\n \n for i in range(1,len(digits)):\n s = len(q)\n while s:\n out = q.popleft()\n for j in phone_keys[int(digits[i])]:\n q.append(out+j)\n s -=1\n return q \n\ns = Solution()\ndigits = \"23\"\nprint(s.letterCombinations(digits)) \n","repo_name":"shilpavijay/Algorithms-Problems-Techniques","sub_path":"Puzzles/Phone_letter_comb.py","file_name":"Phone_letter_comb.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"73561956409","text":"import urllib.request\r\nimport urllib.parse\r\nimport os\r\n\r\n# 目标:输入指定吧名,并输入要爬取的起始页和结束页,创建一个名为吧名的文件夹,并将爬取的html文件以吧名_page.html为文件名放入文件夹\r\n\r\nurl = 'http://tieba.baidu.com/f?ie=utf-8'\r\nname = input('请输入吧名:')\r\npage_start = int(input('请输入起始页码:'))\r\npage_end = int(input('请输入结束页码:'))\r\n\r\nif not os.path.isdir(name):\r\n os.mkdir(name) # 如果目录下没有这个名字命名的文件夹,生成名为吧名的文件夹\r\n\r\nfor page in range(page_start, page_end + 1):\r\n # page是当前页\r\n data = {\r\n 'kw': name,\r\n 'pn': (page-1)*50,\r\n }\r\n\r\n query_string = urllib.parse.urlencode(data)\r\n new_url = url + query_string\r\n print('正在下载第%s页……' % page)\r\n response = urllib.request.urlopen(new_url)\r\n\r\n file_name = name + '_' + str(page) + '.html' # 生成文件名\r\n file_path = name + '/' + file_name # 生成文件路径\r\n\r\n with open(file_path, 'wb') as fp:\r\n fp.write(response.read())\r\n\r\n print('已完成下载第%s页……' % page)\r\n","repo_name":"kevinhkr/Cra","sub_path":"baidutieba.py","file_name":"baidutieba.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"35506412246","text":"import requests\r\nimport re\r\nimport json\r\nfrom requests.exceptions import RequestException\r\nimport multiprocessing\r\n\r\ndef get_one_page(url):\r\n try:\r\n r= requests.get(url)\r\n if r.status_code==200:\r\n return r.text\r\n return None\r\n except RequestsException:\r\n print(\"获取页面失败\",url)\r\n return \"Faile to get page\"\r\n\r\ndef parse_one_page(html):\r\n pattern = re.compile('.*?board-index.*?>(\\d+).*?data-src=\"(.*?)@160w_220h_1e_1c\".*?name\">(.*?) .*?star\">(.*?)
.*?releasetime\">(.*?).*?in'\r\n 'teger\">(.*?).*?fraction\">(.*?)', re.S)\r\n items = re.findall(pattern, html)\r\n for item in items:\r\n yield {\r\n 'index':item[0],\r\n 'image':item[1],\r\n 'title':item[2],\r\n 'actors':item[3].strip()[3:],\r\n 'date':item[4].strip()[5:],\r\n 'score':item[5]+item[6]\r\n }\r\n \r\ndef write2file(content):\r\n with open(\"result.txt\", 'a', encoding='utf-8') as f:\r\n f.write(json.dumps(content, ensure_ascii=False) + '\\n')\r\n f.close()\r\n\r\n\r\ndef main(offset):\r\n url = \"http://maoyan.com/board/4?offset=\" + str(offset)\r\n html = get_one_page(url)\r\n for item in parse_one_page(html):\r\n print(item)\r\n write2file(item)\r\n\r\nif __name__ == '__main__':\r\n pool_size = multiprocessing.cpu_count()\r\n pool = multiprocessing.Pool(processes=pool_size)\r\n pool.map(main, [i for i in range(0,100,10)])\r\n print('Done')\r\n\r\n","repo_name":"echo-ray/Crawler-demo","sub_path":"get_manyan_top_100.py","file_name":"get_manyan_top_100.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"38399278643","text":"\"\"\"\n글자수_1.py에서 sort 쓰는 거 피하기 위해 딕셔너리 사용\n\"\"\"\n\nT = int(input())\n\nfor tc in range(1, T + 1):\n str1 = input()\n str2 = list(input())\n cnt = {}\n for target in str1:\n cnt[target] = 0\n\n ans = 0\n\n for char in str2:\n # try:\n # cnt[char] += 1\n # except:\n # continue\n if char in cnt:\n cnt[char] += 1\n\n print(cnt)\n ans = 0\n # ans = max(cnt.values())\n for val in cnt.values():\n if ans < val:\n ans = val\n\n print(\"#{} {}\".format(tc, ans))\n","repo_name":"LeeSungRyul/TIL","sub_path":"Algorithm/SWEA/D2/4865_d2_글자수_2.py","file_name":"4865_d2_글자수_2.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"805649013","text":"import numpy as np\r\nimport pandas as pd\r\nfrom sklearn.tree import DecisionTreeClassifier\r\n\r\n\r\nclass Ada_Boost:\r\n def __init__(self):\r\n self.classifiers = []\r\n self.classifiers_weights = []\r\n self.object_weights = []\r\n self.errors = []\r\n \r\n \r\n def fit(self, X, Y, classifiers):\r\n n = X.shape[0]\r\n\r\n self.object_weights = np.zeros(shape=(classifiers, n))\r\n self.classifiers = np.zeros(shape=classifiers, dtype=object)\r\n self.classifiers_weights = np.zeros(shape=classifiers)\r\n self.errors = np.zeros(shape=classifiers)\r\n\r\n self.object_weights[0] = np.ones(shape=n) / n\r\n\r\n for i in range(classifiers):\r\n \r\n #Обучем пня\r\n curr_object_weights = self.object_weights[i]\r\n classifier = DecisionTreeClassifier(max_depth=1, max_leaf_nodes=2)\r\n classifier = classifier.fit(X, Y, sample_weight=curr_object_weights)\r\n\r\n #Спрогнозируем класс, посчитаем ошибку пня и альфа тэтый\r\n classifier_pred = classifier.predict(X)\r\n err = curr_object_weights[(classifier_pred != Y)].sum()# / n\r\n aplha_t = np.log((1 - err) / err) / 2\r\n\r\n #Обновим веса объектов и отнормируем их\r\n new_object_weights = (curr_object_weights * np.exp(-aplha_t * Y * classifier_pred))\r\n new_object_weights = new_object_weights / new_object_weights.sum()\r\n\r\n #Для следующего пня используем уже новые веса объектов\r\n if i+1 < classifiers:\r\n self.object_weights[i+1] = new_object_weights\r\n\r\n self.classifiers[i] = classifier\r\n self.classifiers_weights[i] = aplha_t\r\n self.errors[i] = err\r\n return self\r\n\r\n def predict(self, X):\r\n #Находит предсказания каждого из пней и скалярно умножает их на полученные веса пней\r\n \r\n classifier_preds = np.array([classifier.predict(X) for classifier in self.classifiers])\r\n return np.sign(np.dot(self.classifiers_weights, classifier_preds))\r\n","repo_name":"Faraonchika/ML-Algorithms-from-scratch","sub_path":"adaboost.py","file_name":"adaboost.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"28470389114","text":"while True:\n check1 = False # 조건1\n check2 = True # 조건2\n check3 = True # 조건3\n VowelsCount = 0\n ConsonantsCount = 0\n inputLine = input()\n if inputLine == 'end':\n break\n length = len(inputLine)\n\n for i in range(length): # 수정: range 함수의 범위 지정 방식 변경\n\n # 조건1\n if inputLine[i] in ['a', 'e', 'i', 'o', 'u']:\n check1 = True\n\n # 조건2\n if inputLine[i] in ['a', 'e', 'i', 'o', 'u']:\n VowelsCount += 1\n ConsonantsCount = 0\n else:\n ConsonantsCount += 1\n VowelsCount = 0\n\n if VowelsCount == 3 or ConsonantsCount == 3:\n check2 = False\n break\n\n # 조건3\n if i > 0 and inputLine[i] == inputLine[i - 1]:\n if inputLine[i] not in ['e', 'o']:\n check3 = False\n break\n\n print(\"<\", end=\"\")\n print(inputLine + \"> is \", end=\"\") # 수정: 출력 형식 수정\n if check1 and check2 and check3: # 수정: 논리 연산자 사용 방식 변경\n print(\"acceptable.\")\n else:\n print(\"not acceptable.\")\n","repo_name":"909ma/Repository-for-Study","sub_path":"백준/Python4659.py","file_name":"Python4659.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"898365132","text":"\nimport pytest\n#import pdb\n\nfrom graphinet.diagramming import AxisType, LinearAxis, QuantizedAxis, \\\n\tValueOutOfRange, BaseLayout, OuterRim, Pt\n\nclass TestClass:\n\n\tdef test_linearaxis(self):\n\t\tla = LinearAxis(1000, minspace=100)\n\t\tla.setValuesDomainSize(40, 120)\n\t\twith pytest.raises(ValueOutOfRange):\n\t\t\tx = la.getPosition(12, doraise=True)\n\t\tassert la.getPosition(12) is None\n\t\t#pdb.set_trace()\n\t\tassert la.getPosition(60) == 250\n\n\t\tla.setValuesDomain(40, 120)\n\t\tassert la.getPosition(60) == 325\n\n\tdef test_quantaxis(self):\n\t\tqa = QuantizedAxis(1000, 2, minspace=100)\n\t\tqa.setValuesDomainSize(40, 120)\n\t\tassert qa.getPosition(50, doraise=True) == 325\n\t\tassert qa.getPositionFromQuantile(1) == 775\n\t\twith pytest.raises(ValueOutOfRange):\n\t\t\tx = qa.getPositionFromQuantile(2)\n\n\tdef test_quantaxis2(self): #, capsys):\n\t\tqa = QuantizedAxis(1000, 2, minspace=100, inverted=True)\n\t\tqa.setValuesDomainSize(40, 120)\n\t\t#with capsys.disabled():\n\t\tassert qa.getPosition(50, doraise=True) == 775\n\t\tassert qa.getPositionFromQuantile(0) == 775\n\n\t#def test_blayout(self, capsys):\n\tdef test_blayout1(self):\n\t\tbl = BaseLayout(1000, 800, origin = Pt(10,10))\n\t\tbl.setOuterRim(OuterRim(all=10))\n\t\txa = bl.addLinearXAxis(doraise=True)\n\t\txa.setValuesDomain(40, 160)\n\t\tassert xa.getPosition(80, doraise=True) == 347\n\t\tya = bl.addLinearYAxis(doraise=True)\n\t\tya.setValuesDomain(80, 200)\n\t\tassert ya.getPosition(100, doraise=True) == 150\n\t\t# with capsys.disabled():\n\t\t# \tprint(ya.getPosition(100, doraise=True))\n\n\tdef test_blayout2(self, capsys):\n\t\tbl = BaseLayout(1000, 800, origin = Pt(10,10))\n\t\tbl.setOuterRim(OuterRim(all=10))\n\t\txa = bl.addQuantizedXAxis(2, doraise=True)\n\t\txa.setIdentValuesDomain()\n\t\tassert xa.getValuesDomain() == (20, 1000)\n\t\tassert xa.getPosition(100, doraise=True) == 265\n\t\tya = bl.addQuantizedYAxis(3, doraise=True)\n\t\tya.setIdentValuesDomain()\n\t\tassert ya.getValuesDomain() == (20, 800)\n\t\tassert ya.getPosition(620, doraise=True) == 670\n\t\tassert ya.getPosition(740, doraise=True) == 670\n\t\t#with capsys.disabled():\n\t\t#\tprint(ya.getPosition(620, doraise=True))\n\t\twith pytest.raises(ValueOutOfRange):\n\t\t\tx = ya.getPosition(19, doraise=True)\n\t\twith pytest.raises(ValueOutOfRange):\n\t\t\tx = ya.getPosition(801, doraise=True)\n\n\tdef test_blayout3(self): #, capsys):\n\t\tbl = BaseLayout(1200, 700)\n\t\t#with capsys.disabled():\n\t\tbl.basicLinearIdentInit(doraise=True)\n\t\tassert bl.getPosition(Pt(20, 400), doraise=True) == (20, 400)\n\n\tdef test_blayout4(self): #, capsys):\n\t\tbl = BaseLayout(1200, 700)\n\t\tbl.setOuterRim(OuterRim(top=5, bottom=4))\n\t\tya = bl.addLinearYAxis(invert=True, doraise=True)\n\t\tya.setValuesDomain(80, 240)\n\t\t#with capsys.disabled():\n\t\tassert ya.getPosition(120, doraise=True) == 522\n\n","repo_name":"rpcavaco/graphinet","sub_path":"test/test_diagrams.py","file_name":"test_diagrams.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"3242135228","text":"\"\"\"\r\nGiven two binary arrays arr1[] and arr2[] of same size n,which has 1s denotes black rocks and 0s denotes white rocks. Find length of the longest common span (i, j) where j >= i such that arr1[i] + arr1[i+1] + …. + arr1[j] = arr2[i] + arr2[i+1] + …. + arr2[j],find the length of equal counts of black and white rocks in both arrays.\r\n\r\nIn des\r\nFirst line contain integers N,size of two arr.\r\nSecond line contain N space separated integrs,denotes arr1 elements.\r\nSecond line contain N space separated integrs,denotes arr2 elements.\r\n\r\nOt des\r\nPrint the length of span\r\n\r\nH-5\r\nT-1000\r\n\r\nsample\r\n6 6\r\n0 1 0 0 0 0\r\n1 0 1 0 0 1\r\n\r\n4\r\n\r\nexp\r\nFrom sample\r\nThe longest span with same sum is from index 1 to 4.\r\n\r\nHint\r\nOne by one by consider same subarrays of both arrays. For all subarrays, compute sums and if sums are same and current length is more than max length, then update max length.\r\n\r\n4\r\n0 0 1 0\r\n1 1 1 1\r\n1\r\n\r\n3\r\n0 0 0\r\n1 1 1\r\n0\r\n\r\n7\r\n0 1 0 1 1 1 1\r\n1 1 1 1 1 0 1\r\n6\r\n\r\n1\r\n1\r\n1\r\n1\r\n\r\nArray\r\n\r\n\"\"\"\r\n\r\ndef longestCommonSum(arr1, arr2, n): \r\n \r\n\tmaxLen = 0\r\n\r\n\tfor i in range(0,n): \r\n\t\tsum1 = 0\r\n\t\tsum2 = 0\r\n\r\n\t\tfor j in range(i,n): \r\n\t\t\tsum1 += arr1[j] \r\n\t\t\tsum2 += arr2[j] \r\n\t\t\tif (sum1 == sum2): \r\n\t\t\t\tlen = j-i+1\r\n\t\t\t\tif (len > maxLen): \r\n\t\t\t\t\tmaxLen = len\r\n\t\r\n\treturn maxLen \r\nN=int(input()) \r\narr1 = list(map(int,input().split())) \r\narr2 = list(map(int,input().split())) \r\nn = len(arr1) \r\nprint(longestCommonSum(arr1, arr2, n)) \r\n\r\n\r\n","repo_name":"govardhananprabhu/DS-task-","sub_path":"long span.py","file_name":"long span.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"29364394479","text":"#Descomponer un número\nnum=int(input(\"ingrese numero \"))\nmil=(num//1000)\ncen=(num-(mil*1000))//100\nres1=(num//100)\nres2=(num-(res1*100))\ndec=(res2//10)\nuni=(res2-(dec*10))\nif(num<=999):\n print(cen,\"C+\",dec,\"D+\",uni,\"U\")\nelif(num<=9999):\n print(mil,\"M+\",cen,\"C+\",dec,\"D+\",uni,\"U\")\nelse:\n print(\"ingreso un numero con mas de 4 digitos\")","repo_name":"pabloschwarzenberg/grader","sub_path":"hito1_ej8/hito1_ej8_061e116de9ce21769fa0777a5a483775.py","file_name":"hito1_ej8_061e116de9ce21769fa0777a5a483775.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"10793088968","text":"# Append parent directory for imports\nimport os, sys, subprocess\ncurrentdir = os.path.dirname(os.path.realpath(__file__))\nparentdir = os.path.dirname(currentdir)\nsys.path.append(parentdir)\n\n\n# General Imports\nimport lib\nfrom trainer import Trainer\nfrom logger import Logger\nfrom datetime import datetime\n\n# Check for proper meta file\nif len(sys.argv) != 2:\n print('Incorrect arguemnts. Please use \"training.py meta.txt\" with your desired meta file.') \n exit()\nmeta = lib.load_meta(sys.argv[1])\n\n# Ensure that the correct folders exist\nif not os.path.isdir('results'):\n subprocess.run(['mkdir', 'results'])\nif not os.path.isdir(os.path.join('results', meta['run_name'])):\n subprocess.run(['mkdir', os.path.join('results', meta['run_name'])])\n\n# Initialize the logger\nl = Logger(file = os.path.join('results', meta['run_name'], meta['log_file_name'] + datetime.now().strftime(\"%m-%d_%H:%M:%S\") + '.txt'), \n include = meta['include'].split('/'),\n stdout = bool(int(meta['log_out'])))\nl.open()\nl.log('LOG', f'Meta loaded using file: {sys.argv[1]}')\n\n\n# Get Cuda Device\ndevice = lib.get_cuda()\nl.log('LOG', f'CUDA {\"Loaded\" if device != \"cpu\" else \"not loaded\"}. Using device {device}')\n\n# Set up the generic trainer\ntrainer = Trainer(\n steps = int(meta['steps']),\n model = lib.get_model(meta['model'], l, device),\n logger = l,\n epochs = int(meta['epochs']),\n save_path = meta['save_path'],\n save_name = meta['save_name'],\n load_name = meta['load_name'],\n cuda = bool(int(meta['cuda']))\n)\n\n# Apply all relavent modes\nmodes = meta['modes'].split('/')\n\nif 'train_model' in modes:\n trainer.train()\nif 'visualize' in modes:\n print('got here')\n lib.visualize_losses(os.path.join('results', meta['run_name']), trainer.get_losses())\n","repo_name":"willsanford/qgan","sub_path":"src/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"26951768334","text":"#!/usr/bin/env python3\n'''\nMakes installing inkscape_silhouette easier on OSX\n\nThis installer adds the extension to the user's local Inkscape extensions rather\nthan inside the Inkscape.app bundle. This should, in theory, allow it to survive\nbetween inscape upgrades.\n\n@author: Brian Bustin\n@contact: brian at bustin.us\n'''\nimport os, sys, shutil, logging, subprocess\n\nlogger = logging.getLogger(__name__)\n\nprerequisites = [\"cssselect\", \"xmltodict\", \"lxml\", \"pyusb\", \"libusb1\", \"numpy\"]\nextensions_dir = os.path.join(os.path.expanduser(\"~\"), \"Library\",\"Application Support\",\"org.inkscape.Inkscape\",\"config\",\"inkscape\",\"extensions\")\nextension_files = [\"sendto_silhouette.inx\", \"sendto_silhouette.py\",\n \"silhouette_multi.inx\", \"silhouette_multi.py\",\n \"silhouette\"]\n\n\ndef install_inkscape_silhouette():\n try:\n logger.info(\"inkscape_silhouette install starting\")\n\n # make sure this is os x\n logger.debug(\"making sure running on Mac OS\")\n sys_platform = sys.platform.lower()\n logger.debug(\"platform: %s\", sys_platform)\n if not sys_platform.startswith('darwin'):\n logger.error(\"Installer only works with Mac OS\")\n return\n\n if not os.path.isdir(extensions_dir):\n logger.info(\"creating extensions dir %s\", extensions_dir)\n os.makedirs(extensions_dir)\n\n install_prerequisites()\n install_extension()\n check_libusb()\n logger.info(\"inkscape_silhouette extension install ended\")\n logger.info(\"Don't forget to add 'python-interpreter=\\\"%s\\\"' to your extension preference file.\", subprocess.check_output([\"which\", \"python3\"]).decode(\"utf-8\").replace(\"\\n\", \"\"))\n except Exception as ex:\n logger.warning(\"inkscape_silhouette install was unsuccessful. Please check previous messages for the cause. Details: %s\", ex)\n\n\ndef install_prerequisites():\n logger.info(\"installing inkscape_silhouette prerequisites\")\n for prerequisite in prerequisites:\n logger.debug(\"installing %s\", prerequisite)\n try:\n return_code = subprocess.call(\"pip3 install {}\".format(prerequisite), shell=True)\n if return_code > 0:\n raise OSError(\"command returned code {}, try running again using sudo\".format(return_code))\n except OSError:\n logger.error(\"unable to install module. Try running 'pip3 install %s' manually\", prerequisite)\n raise\n\n\ndef check_libusb():\n logger.info(\"making sure libusb is installed\")\n try:\n import usb.core\n except ImportError:\n logger.error(\"pyusb is not installed. Install script usually fails here on first attempt. Running it again should allow installation to complete.\")\n raise\n\n try:\n usb.core.find()\n except usb.core.NoBackendError:\n logger.error(\"libusb is probably not installed. Refer to the instructions in README.md to install it.\")\n raise\n except Exception as ex:\n logger.error(\"something is not right with either pyusb or libusb. Details: %s\", ex)\n raise\n\n\ndef install_extension():\n logger.info(\"installing extension\")\n for file in extension_files:\n path = os.path.join(os.getcwd(), file)\n if os.path.isfile(path):\n logger.debug(\"copying %s => %s\", path, extensions_dir)\n shutil.copy(path, extensions_dir)\n else:\n destination_dir = os.path.join(extensions_dir, file)\n if os.path.isdir(destination_dir):\n logger.info(\"directory already exists '%s'. Removing it and recreating it.\", destination_dir)\n shutil.rmtree(destination_dir)\n logger.debug(\"copying %s => %s\", path, destination_dir)\n shutil.copytree(path, destination_dir)\n\n\ndef uninstall_extension():\n logger.info(\"uninstalling extension\")\n for file in extension_files:\n file_path = os.path.join(extensions_dir, file)\n logger.debug(\"deleting %s\", file_path)\n try:\n os.remove(file_path)\n except OSError:\n logger.info(\"unable to delete %s. It may have been previously removed or was never installed\", file_path)\n\n\nif __name__ == \"__main__\":\n import logging.handlers\n\n log_level = logging.INFO\n\n # set up logging\n logger.setLevel(log_level)\n log_console = logging.StreamHandler()\n log_console.setLevel(log_level)\n log_formatter = logging.Formatter('%(levelname)s: %(message)s')\n log_console.setFormatter(log_formatter)\n logger.addHandler(log_console)\n\n # run installer\n install_inkscape_silhouette()\n","repo_name":"fablabnbg/inkscape-silhouette","sub_path":"install_osx.py","file_name":"install_osx.py","file_ext":"py","file_size_in_byte":4596,"program_lang":"python","lang":"en","doc_type":"code","stars":415,"dataset":"github-code","pt":"77"}
+{"seq_id":"24651460630","text":"from django import forms\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.forms import ModelForm\n\nfrom petstagram.accounts.models import Profile\nfrom petstagram.common.helps import BootstrapFormMixin\nfrom petstagram.main.models import PetPhoto\n\n\nclass CreateProfileForm(BootstrapFormMixin, UserCreationForm):\n first_name = forms.CharField(\n max_length=Profile.FIRST_NAME_MAX_LENGTH,\n )\n last_name = forms.CharField(\n max_length=Profile.LAST_NAME_MAX_LENGTH,\n )\n picture = forms.URLField()\n data_of_birth = forms.DateField()\n description = forms.CharField(\n widget=forms.Textarea\n )\n email = forms.EmailField()\n gender = forms.ChoiceField(\n choices=Profile.GENDERS,\n )\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._init_bootstrap_form_controls()\n\n def save(self, commit=True):\n user = super().save(commit=commit)\n profile = Profile(\n first_name=self.cleaned_data['first_name'],\n last_name=self.cleaned_data['last_name'],\n picture=self.cleaned_data['picture'],\n data_of_birth=self.cleaned_data['data_of_birth'],\n description=self.cleaned_data['description'],\n email=self.cleaned_data['email'],\n gender=self.cleaned_data['gender'],\n user=user,\n )\n if commit:\n profile.save()\n return user\n\n class Meta:\n model = get_user_model()\n fields = ('username', 'password1', 'password2', 'first_name', 'last_name', 'picture', 'description')\n widgets = {\n 'first_name': forms.TextInput(\n attrs={\n 'placeholder': 'Enter first name',\n }\n ),\n 'last_name': forms.TextInput(\n attrs={\n 'placeholder': 'Enter last name',\n }\n ),\n 'picture': forms.TextInput(\n attrs={\n 'placeholder': 'ENTER URL',\n }\n )\n }\n\n\nclass DateInput(forms.DateInput):\n input_type = 'date'\n\n\nclass EditProfileForm(BootstrapFormMixin, ModelForm):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._init_bootstrap_form_controls()\n self.initial['gender'] = Profile.DO_NOT_SHOW\n\n class Meta:\n model = get_user_model()\n fields = '__all__'\n widgets = {\n 'first_name': forms.TextInput(\n attrs={\n 'placeholder': 'ENTER name'\n }\n ),\n 'last_name': forms.TextInput(\n attrs={\n 'placeholder': 'ENTER second name'\n }\n ),\n 'picture': forms.TextInput(\n attrs={\n 'placeholder': 'ENTER URL'\n }\n ),\n 'email': forms.EmailInput(\n attrs={\n 'placeholder': 'ENTER @mail.bg'\n }\n ),\n 'description': forms.Textarea(\n attrs={\n 'placeholder': 'ENTER description',\n 'rows': 3,\n }\n ),\n 'gender': forms.Select(\n choices=Profile.GENDERS,\n ),\n 'data_of_birth': DateInput(\n attrs={\n 'min': '1920-01-01',\n }\n ),\n }\n\n\nclass DeleteProfileForm(forms.ModelForm):\n def save(self, commit=True):\n # taka ne e dobre trqbwa da e s signali za da trie snimkite na potrebitelq\n pets = list(self.instance.pet_set.all())\n PetPhoto.objects.filter(tagged_pets__in=pets).delete()\n self.instance.delete()\n\n return self.instance\n\n class Meta:\n model = Profile\n fields = ()\n\n","repo_name":"Didomitko/python-web-frameworks-demo-repo-","sub_path":"petstagram/petstagram/accounts/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"38696321782","text":"import posixpath\nimport logging\nimport os\n\nfrom ccdb.errors import ObjectIsNotFoundInDbError\nfrom ccdb.model import Directory, TypeTable\nfrom ccdb.provider import AlchemyProvider\nfrom ccdb.cmd import CliCommandBase, UtilityArgumentParser\nfrom ccdb import BraceMessage as LogFmt\n\nlog = logging.getLogger(\"ccdb.cmd.commands.ls\")\n\n\n# ********************************************************************\n# Class List - List objects in a given directory *\n# ********************************************************************\nclass List(CliCommandBase):\n \"\"\" List objects in a given directory \"\"\"\n\n # ccdb utility class descr part \n #------------------------------\n command = \"ls\"\n name = \"List\"\n short_descr = \"List objects in a given directory\"\n uses_db = True\n\n def __init__(self, context):\n CliCommandBase.__init__(self, context)\n self.raw_entry = \"/\" # object path with possible pattern, like /mole/*\n self.parent_path = \"/\" # parent path\n self.parent_dir = None # @type parent_dir DDirectory\n self.pattern = \"\" # pattern on the end of parent path like file?*\n self.is_extended = False\n\n def reset(self):\n \"\"\"Resets variables for each 'process'\"\"\"\n self.raw_entry = \"/\" # object path with possible pattern, like /mole/*\n self.parent_path = \"/\" # parent path\n self.parent_dir = None # @type parent_dir DDirectory\n self.pattern = \"\" # pattern on the end of parent path like file?*\n self.is_extended = False\n\n def execute(self, args):\n if log.isEnabledFor(logging.DEBUG):\n log.debug(LogFmt(\"{0}List is in charge{0}\\\\\".format(os.linesep)))\n log.debug(LogFmt(\" |- arguments : '\" + \"' '\".join(args) + \"'\"))\n\n # This command might be used as an alias\n self.is_alias = False\n\n assert self.context is not None\n provider = self.context.provider\n assert isinstance(provider, AlchemyProvider)\n self.reset()\n\n # PARSE ARGUMENTS\n # -------------------------------\n raw_path, task, is_extended = self._process_arguments(args)\n\n # dump as tree\n if task == ListTasks.directory_tree:\n self.parent_dir = provider.get_root_directory()\n self.print_directory_tree(self.parent_dir, False, 0)\n return\n\n # dump as directories\n if task == ListTasks.directories:\n self.parent_dir = provider.get_root_directory()\n self.print_directory_tree(self.parent_dir, True, 0)\n return\n\n # dump variations\n if task == ListTasks.variations:\n self.print_variations()\n return\n\n # dump type_tables\n if task == ListTasks.type_tables:\n self.print_tables()\n return\n\n if len(args) > 0:\n self.raw_entry = raw_path\n else:\n self.raw_entry = self.context.current_path\n\n dirs, tables = self.get_name_pathes(self.raw_entry)\n\n if (not dirs) and (not tables):\n log.info(\"Can't find the directory or tables\")\n\n # it is not a wild card search, and\n if (\"*\" not in self.raw_entry) and\\\n (\"?\" not in self.raw_entry) and\\\n (not dirs) and\\\n (len(tables) == 1):\n table = tables[0]\n\n self.table_info(table, is_extended)\n\n # we will use this command as alias\n # (return string is called by cli_manager)\n self.is_alias = True\n if is_extended:\n return \"info \" + table.path\n return \"vers \" + table.path\n\n for directory in dirs:\n log.info(self.theme.Directories + directory.name + self.theme.Reset)\n\n for table in tables:\n log.info(table.name)\n\n @staticmethod\n def _process_arguments(args):\n # solo arguments\n\n # utility argument parser is argparse which raises errors instead of exiting app\n parser = UtilityArgumentParser()\n parser.add_argument(\"raw_path\", nargs='?', default=\"\")\n parser.add_argument(\"-x\", \"--dtree\", action=\"store_true\")\n parser.add_argument(\"-d\", \"--directories\", action=\"store_true\")\n parser.add_argument(\"-t\", \"--tables\", action=\"store_true\")\n parser.add_argument(\"-v\", \"--variations\", action=\"store_true\")\n parser.add_argument(\"-l\", \"--extended\", action=\"store_true\")\n\n result = parser.parse_args(args)\n\n if result.variations:\n task = ListTasks.variations\n elif result.directories:\n task = ListTasks.directories\n elif result.dtree:\n task = ListTasks.directory_tree\n elif result.tables:\n task = ListTasks.type_tables\n else:\n task = ListTasks.default\n\n log.debug(LogFmt(\" |- parsed as (obj: '{0}', type: '{1}')\", result.raw_path, task))\n\n return result.raw_path, task, result.extended\n\n def get_name_pathes(self, path):\n assert self.context is not None\n provider = self.context.provider\n assert isinstance(provider, AlchemyProvider)\n self.reset()\n\n #prepare path\n log.debug(\" | |- ls.get_name_pathes\")\n log.debug(\" | | \\\\\")\n log.debug(\" | | |- before prepare_path: \" + path)\n\n self.raw_entry = self.prepare_path(path)\n log.debug(\" | | |- after prepare_path: \" + self.raw_entry)\n\n #SEARCH LOGIC\n #---------------------------\n\n #brute assumption that user has entered a simple dir path\n try:\n self.parent_dir = provider.get_directory(self.raw_entry)\n self.parent_path = self.raw_entry\n self.pattern = \"\"\n except ObjectIsNotFoundInDbError:\n self.parent_dir = None\n log.debug(\" | | |- directory {0} not found.\".format(self.raw_entry))\n\n if not self.parent_dir:\n # we have not find the directory by brute rawentry.\n # but maybe it is just /path/plus*some*pattern\n (head, tail) = posixpath.split(self.raw_entry)\n self.parent_path = head\n self.pattern = tail\n log.debug(\" | | |- searching parent directory as:\")\n log.debug(\" | | |- new path: \" + self.parent_path)\n if self.pattern:\n log.debug(\" | | |- pattern: \" + self.pattern)\n\n # try to find such dir once more\n self.parent_dir = provider.get_directory(self.parent_path)\n\n # found a directory\n assert isinstance(self.parent_dir, Directory)\n log.debug(\" | | |- searching sub directories \")\n log.debug(\" | | |- full path: \" + self.parent_dir.path)\n if self.pattern:\n log.debug(\" | | |- pattern: \" + self.pattern)\n\n # part 1 directories for this path\n if self.pattern == \"\":\n sub_dirs = self.parent_dir.sub_dirs\n log.debug(\" | | |- simply taking sub directories \")\n else:\n sub_dirs = provider.search_directories(self.pattern, self.parent_path)\n log.debug(\" | | |- use database search for directories \")\n\n # fill list of directory names\n dir_list = [subdir.name for subdir in sub_dirs]\n\n log.debug(\" | | |- found dirs:\" + \" \".join([d for d in dir_list]))\n\n log.debug(\" | | |- searching tables \")\n # part 2 is tables for this path\n if self.pattern == \"\":\n tables = self.context.provider.get_type_tables(self.parent_dir)\n else:\n tables = self.context.provider.search_type_tables(self.pattern, self.parent_path)\n\n return sub_dirs, tables\n\n def prepare_path(self, path):\n \"\"\"\n prepares path:\n makes path absolute if it is relative\n removes path artifacts like / in the end, /../ in the middle etc.\n\n :param path: raw uncoocked path\n :type path: str\n :return: Well done path\n :rtype: str\n \"\"\"\n # correct ending /\n\n if path.endswith(\"/\"):\n path = path[:-1]\n\n # local or absolute path?\n if not path.startswith(\"/\"):\n path = posixpath.join(self.context.current_path, path)\n\n # normalize\n path = posixpath.normpath(path)\n\n return path\n\n def print_directory_tree(self, directory, printFullPath, level):\n \"\"\" prints a full tree of directories This is recursive function\"\"\"\n\n # print this directory\n if not printFullPath:\n print((\"\".join([\" \" for i in range(0, level)]) + directory.name))\n else:\n print((directory.path))\n\n # print subdirectories recursively\n sub_dirs = directory.sub_dirs\n if len(sub_dirs) > 0:\n for subDir in sub_dirs:\n self.print_directory_tree(subDir, printFullPath, level + 1)\n\n def print_variations(self):\n default_variation = self.context.provider.get_variation(\"default\")\n print(( self._get_variation_tree_str(default_variation) ))\n\n def _get_variation_tree_str(self, variation, level=0):\n ret = \" \"*level + str(variation.name)+\"\\n\"\n for child in variation.children:\n ret += self._get_variation_tree_str(child, level+1)\n return ret\n\n def print_tables(self):\n tables = self.context.provider.search_type_tables(\"*\")\n for table in tables:\n assert (isinstance(table, TypeTable))\n print(table.path)\n\n def table_info(self, table, is_extended):\n log.info(table.path)\n\n def print_help(self):\n \"\"\"Prints help of the command\"\"\"\n\n print(\"\"\"\nLists directories and tables for current directory\n\n- Accepts wildcards symbols '*', and '?'\n\n- When used on single table name, gives table data version as 'vers ' command\n note(!): vers command allows you to filter data by variation or run, ls - not\n\nkeys:\n -v or --variations - prints all variations\n -t or --tables - prints full path for all tables\n -d or --directories - prints all directories\n -x or --dtree - draws directory tree\n\n -l or --extended - shows extended info when is used on table\n\"\"\")\n\n\nclass ListTasks(object):\n default = \"default\"\n variations = \"variations\"\n type_tables = \"type_tables\"\n directories = \"directories\"\n directory_tree = \"directory_tree\"\n\n\n\n\n\n","repo_name":"JeffersonLab/ccdb","sub_path":"python/ccdb/cmd/commands/ls.py","file_name":"ls.py","file_ext":"py","file_size_in_byte":10371,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"77"}
+{"seq_id":"39990292480","text":"import math\nfrom collections import defaultdict\nfrom typing import TextIO, Tuple\n\nimport numpy # type: ignore\n\n\ndef read_asteroids(data: TextIO) -> Tuple[numpy.array, numpy.array]:\n xs = []\n ys = []\n for y, line in enumerate(data):\n for x, c in enumerate(line):\n if c == '#':\n xs.append(x)\n ys.append(y)\n\n return numpy.array(xs), -numpy.array(ys)\n\n\ndef asteroids_visible(x: int, y: int, xs: numpy.array, ys: numpy.array) -> int:\n dx = xs - x\n dy = ys - y\n\n div = numpy.abs(numpy.gcd(dx, dy))\n\n mask = div != 0\n\n dx[mask] //= div[mask]\n dy[mask] //= div[mask]\n\n unique = set(zip(dx, dy))\n\n return len(unique) - 1 # need to ignore the point itself\n\n\ndef part1(data: TextIO) -> int:\n xs, ys = read_asteroids(data)\n\n return max(asteroids_visible(x, y, xs, ys) for x, y in zip(xs, ys))\n\n\ndef part2(data: TextIO) -> int:\n xs, ys = read_asteroids(data)\n\n cx, cy = max(zip(xs, ys), key=lambda c: asteroids_visible(c[0], c[1], xs, ys))\n\n dx = xs - cx\n dy = ys - cy\n\n angles = numpy.arctan2(dy, dx)\n distances = numpy.abs(dx) + numpy.abs(dy)\n\n to_shoot = defaultdict(list)\n\n for angle, distance, dx, dy in zip(angles, distances, dx, dy):\n if distance == 0:\n # The point itself\n continue\n\n to_shoot[angle].append((distance, dx, dy))\n\n for distances in to_shoot.values():\n distances.sort(reverse=True)\n\n unique_angles = sorted(set(angles), reverse=True)\n\n shot = 0\n\n # First shoot from up clockwise\n for angle in unique_angles:\n if angle > math.pi / 2:\n continue\n\n shot += 1\n\n _, dx, dy = to_shoot[angle].pop()\n\n # Repeatedly shoot until you reach #200\n while True:\n for angle in unique_angles:\n if not to_shoot[angle]:\n # Nothing left to shoot\n continue\n\n shot += 1\n\n _, dx, dy = to_shoot[angle].pop()\n\n if shot == 200:\n x = cx + dx\n y = -(cy + dy)\n return 100 * x + y\n\n","repo_name":"bertptrs/adventofcode","sub_path":"2019/aoc2019/day10.py","file_name":"day10.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"77"}
+{"seq_id":"32221338454","text":"from PyQt5.QtWidgets import (QApplication, QComboBox, QDialog,\r\n QDialogButtonBox, QFormLayout, QGridLayout, QGroupBox, QHBoxLayout,\r\n QLabel, QLineEdit, QMenu, QMenuBar, QPushButton, QSpinBox, QTextEdit,\r\n QVBoxLayout, QMainWindow, QAction, QWidget, QFileDialog, QMdiSubWindow,\r\n QDesktopWidget, QMessageBox)\r\n \r\nfrom PyQt5.QtGui import QIcon\r\nfrom PyQt5.QtCore import pyqtSlot\r\nimport sys\r\nfrom netCDF4 import Dataset\r\n\r\nclass App(QWidget):\r\n \r\n def __init__(self):\r\n super().__init__()\r\n\r\n self.initUI()\r\n \r\n def initUI(self):\r\n self.setWindowTitle('Model WRF')\r\n self.setGeometry(10, 10, 450, 300)\r\n self.setWindowIcon(QIcon('wrf.jpeg'))\r\n self.center()\r\n \r\n \r\n self.openFileNameDialog()\r\n\r\n mainLayout = QVBoxLayout()\r\n \r\n but1 = QPushButton('Показать список переменных')\r\n but2 = QPushButton('Показать информацию о переменной')\r\n but3 = QPushButton('Показать значения переменной')\r\n but4 = QPushButton('Сохранить значения переменной')\r\n but5 = QPushButton('Рассчитать параметры переменной')\r\n but6 = QPushButton('Загрузить второй файл')\r\n\r\n mainLayout.addWidget(but1)\r\n mainLayout.addWidget(but2)\r\n mainLayout.addWidget(but3)\r\n mainLayout.addWidget(but4)\r\n mainLayout.addWidget(but5)\r\n mainLayout.addWidget(but6)\r\n \r\n but1.clicked.connect(self.event_show_lists)\r\n\r\n self.setLayout(mainLayout)\r\n self.show()\r\n \r\n\r\n def openFileNameDialog(self): \r\n options = QFileDialog.Options()\r\n options |= QFileDialog.DontUseNativeDialog\r\n fileName, _ = QFileDialog.getOpenFileName(self,\"Input file\", \"\",\"All Files (*);;Python Files (*.py)\", options=options)\r\n \r\n self.data = Dataset(fileName, \"r\", format=\"NETCDF4\")\r\n \r\n #self.data._isopen()\r\n #self.data.close()\r\n #with Dataset(fileName, \"r\", format=\"NETCDF4\") as f:\r\n # self.data = f\r\n\r\n\r\n def event_show_lists(self):\r\n self.data_keys_for_buts = []\r\n keys = []\r\n \r\n text = QTextEdit()\r\n #textEdit = self.window.setWindowModality(self, QTextEdit())\r\n \r\n #window.addWidget(text)\r\n \r\n with self.data:\r\n data_keys = self.data.variables.keys()\r\n for k in data_keys:\r\n self.lbl = k\r\n self.data_keys_for_buts.append(k)\r\n str_param = '\\n'.join(self.data_keys_for_buts)\r\n \r\n text.setText(str_param)\r\n return text.show()\r\n\r\n \r\n def event_show_information(self):\r\n\r\n self.textEdit = QTextEdit()\r\n \r\n with self.data:\r\n data_keys = self.data.variables.values()\r\n\r\n\r\n\r\n def closeEvent(self, event):\r\n #переопределяем обработчик события закрытия окна\r\n #название окна, вопрос в окне, кнопка | кнопка, кнопка на которой курсор по умолчанию\r\n reply = QMessageBox.question(self, 'Exit message',\r\n \"Are you sure to quit?\", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\r\n \r\n if reply == QMessageBox.Yes:\r\n event.accept()\r\n else:\r\n event.ignore()\r\n \r\n \r\n #центрирование окна на рабочем столе\r\n def center(self):\r\n \r\n #получаем прямоугольник, определяющий геометрию главного окна\r\n qr = self.frameGeometry()\r\n #получаем разрешение экрана нашего монитора и центральную точку\r\n cp = QDesktopWidget().availableGeometry().center()\r\n #устанавливаем центр прямоугольника в центр экрана\r\n qr.moveCenter(cp)\r\n #двигаем верхний левый угол окна приложения в верхний левый угол прямоугольника qr, \r\n #таким образом, центрируя окно на нашем экране\r\n self.move(qr.topLeft())\r\n\r\n\r\n\r\n\r\nclass Description(QDialog):\r\n def __init__(self):\r\n super().__init__()\r\n\r\n self.initUI()\r\n \r\n \r\n def initUI(self):\r\n pass\r\n \r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n app = QApplication(sys.argv)\r\n ex = App()\r\n sys.exit(app.exec_())\r\n\r\n\r\n","repo_name":"lelik9416/courseWork","sub_path":"smth.py","file_name":"smth.py","file_ext":"py","file_size_in_byte":4706,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"25335799366","text":"#######################################\n#######################################\n# NETWORK ADJUSTMENT LIBRARY FOR PLOTS\n# Sébastien Guillaume (HEIG-VD)\n# Daniel Willi (swisstopo)\n# 2019\n#######################################\n#######################################\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass Point:\n \n def __init__(self,id):\n self.id = id\n self.ipl_id = -1\n self.east = 0\n self.north = 0\n self.height = 0\n self.planiFix = 0\n self.heightFix = 0\n self.displ_east = 0\n self.displ_north = 0\n self.displ_height = 0\n self.ellipse_a = 0\n self.ellipse_b = 0\n self.ellipse_azi = 0\n self.fiab_NA = 0\n self.fiab_NB = 0\n self.fiab_azi = 0\n \n def printId(self):\n print('id = {}'.format(self.id))\n\n def printCoord(self):\n print('id = {} East = {:0.4f} North = {:0.4f} Height = {:0.4f}'.format(self.id,self.east,self.north,self.height))\n\n\nclass Observation:\n \n def __init__(self,id1,id2,type_obs):\n self.id1 = id1\n self.id2 = id2\n self.type_obs = type_obs\n \n def printObservation(self):\n print('{}->{} : {}'.format(self.id1,self.id2,self.type_obs))\n\n\ndef findIdFromIplID(points,ipl_id):\n for key,value in points.items():\n if value.ipl_id == ipl_id:\n return value.id\n\ndef plotPoints(points,options):\n \n #PLOT POINTS\n for key, value in points.items():\n pts_no = key\n y = value.east\n x = value.north\n if value.planiFix == '0':\n plt.plot(y,x,'s',color='black',markersize=7)\n if value.planiFix == '1':\n plt.plot(y,x,'o',color='blue',markersize=5)\n\n textOffset = options['textOffset'][0]\n fontSize = options['fontSize'][0]\n plt.text(y+textOffset,x+textOffset,pts_no,fontSize=fontSize) \n \n plt.axis('equal')\n plt.xticks(fontsize=14)\n plt.yticks(fontsize=14)\n plt.grid(True)\n plt.xlabel(r'$E_{MN95}$ [m]',fontsize=14)\n plt.ylabel(r'$N_{MN95}$ [m]',fontsize=14)\n\n\ndef plotObservations(points,observations,options):\n \n #PLOT OBSERVATIONS\n for obs in observations:\n type = obs.type_obs\n sta = obs.id1\n vis = obs.id2\n sta_y = points[sta].east\n sta_x = points[sta].north\n vis_y = points[vis].east\n vis_x = points[vis].north\n D_y = vis_y-sta_y\n D_x = vis_x-sta_x \n \n if type == 'RI':\n plt.plot([sta_y,sta_y+D_y*0.7],[sta_x,sta_x+D_x*0.7],'black',lineWidth=1)\n plt.plot([sta_y+D_y*0.7,sta_y+D_y*1.0],[sta_x+D_x*0.7,sta_x+D_x*1.0],'black',lineStyle='--',lineWidth=1)\n \n if type == 'DP':\n plt.plot([sta_y,sta_y+D_y*1],[sta_x,sta_x+D_x*1],'black',lineStyle='--',lineWidth=0.5)\n plt.plot([sta_y+D_y*0.2,sta_y+D_y*0.4],[sta_x+D_x*0.2,sta_x+D_x*0.4],'black',lineWidth=2.5)\n \n \n plt.axis('equal')\n plt.xticks(fontsize=14)\n plt.yticks(fontsize=14)\n plt.grid(True)\n plt.xlabel(r'$E_{MN95}$ [m]',fontsize=14)\n plt.ylabel(r'$N_{MN95}$ [m]',fontsize=14)\n \n \ndef plotPrecision(points,options):\n \n for key, value in points.items():\n pts_no = key\n pt_y = value.east\n pt_x = value.north\n \n f = options['scalePrecision'][0]\n theta = np.linspace(0,2*np.pi,50)\n R=[[np.cos(value.ellipse_azi*np.pi/200),np.sin(value.ellipse_azi*np.pi/200)],\n [-np.sin(value.ellipse_azi*np.pi/200),np.cos(value.ellipse_azi*np.pi/200)]]\n \n y0 = f*value.ellipse_b*np.cos(theta)\n x0 = f*value.ellipse_a*np.sin(theta)\n \n vec_yx = np.vstack((y0,x0))\n rot_yx = np.matmul(R,vec_yx)\n \n y = rot_yx[0,:] + pt_y\n x = rot_yx[1,:] + pt_x\n plt.plot(y,x,color='b')\n\n ax1_y_1 = 0.8*f*value.ellipse_a*np.sin(value.ellipse_azi*np.pi/200) + pt_y\n ax1_x_1 = 0.8*f*value.ellipse_a*np.cos(value.ellipse_azi*np.pi/200) + pt_x\n ax1_y_2 = 1.2*f*value.ellipse_a*np.sin(value.ellipse_azi*np.pi/200) + pt_y\n ax1_x_2 = 1.2*f*value.ellipse_a*np.cos(value.ellipse_azi*np.pi/200) + pt_x\n ax2_y_1 = 0.8*f*value.ellipse_b*np.sin((100+value.ellipse_azi)*np.pi/200) + pt_y\n ax2_x_1 = 0.8*f*value.ellipse_b*np.cos((100+value.ellipse_azi)*np.pi/200) + pt_x\n ax2_y_2 = 1.2*f*value.ellipse_b*np.sin((100+value.ellipse_azi)*np.pi/200) + pt_y\n ax2_x_2 = 1.2*f*value.ellipse_b*np.cos((100+value.ellipse_azi)*np.pi/200) + pt_x\n plt.plot([ax1_y_1,ax1_y_2],[ax1_x_1,ax1_x_2],color='b')\n plt.plot([ax2_y_1,ax2_y_2],[ax2_x_1,ax2_x_2],color='b')\n \n plt.axis('equal')\n plt.xticks(fontsize=14)\n plt.yticks(fontsize=14)\n plt.grid(True)\n plt.xlabel(r'$E_{MN95}$ [m]',fontsize=14)\n plt.ylabel(r'$N_{MN95}$ [m]',fontsize=14)\n \n\n\ndef plotReliability(points,options):\n \n for key, value in points.items():\n pts_no = key\n pt_y = value.east\n pt_x = value.north\n \n f = options['scaleReliability'][0]\n R=[[np.cos(value.fiab_azi*np.pi/200),np.sin(value.fiab_azi*np.pi/200)],\n [-np.sin(value.fiab_azi*np.pi/200),np.cos(value.fiab_azi*np.pi/200)]]\n \n y0 = [f*value.fiab_NB,f*value.fiab_NB,-f*value.fiab_NB,-f*value.fiab_NB,f*value.fiab_NB]\n x0 = [f*value.fiab_NA,-f*value.fiab_NA,-f*value.fiab_NA,f*value.fiab_NA,f*value.fiab_NA]\n \n vec_yx = np.vstack((y0,x0))\n rot_yx = np.matmul(R,vec_yx)\n \n y = rot_yx[0,:] + pt_y\n x = rot_yx[1,:] + pt_x\n plt.plot(y,x,color='g')\n\n# ax1_y_1 = 0.8*f*value.fiab_NA*np.sin(value.fiab_azi*np.pi/200) + pt_y\n# ax1_x_1 = 0.8*f*value.fiab_NA*np.cos(value.fiab_azi*np.pi/200) + pt_x\n# ax1_y_2 = 1.2*f*value.fiab_NA*np.sin(value.fiab_azi*np.pi/200) + pt_y\n# ax1_x_2 = 1.2*f*value.fiab_NA*np.cos(value.fiab_azi*np.pi/200) + pt_x\n# ax2_y_1 = 0.8*f*value.fiab_NB*np.sin((100+value.fiab_azi)*np.pi/200) + pt_y\n# ax2_x_1 = 0.8*f*value.fiab_NB*np.cos((100+value.fiab_azi)*np.pi/200) + pt_x\n# ax2_y_2 = 1.2*f*value.fiab_NB*np.sin((100+value.fiab_azi)*np.pi/200) + pt_y\n# ax2_x_2 = 1.2*f*value.fiab_NB*np.cos((100+value.fiab_azi)*np.pi/200) + pt_x\n# plt.plot([ax1_y_1,ax1_y_2],[ax1_x_1,ax1_x_2],color='g')\n# plt.plot([ax2_y_1,ax2_y_2],[ax2_x_1,ax2_x_2],color='g')\n \n plt.axis('equal')\n plt.xticks(fontsize=14)\n plt.yticks(fontsize=14)\n plt.grid(True)\n plt.xlabel(r'$E_{MN95}$ [m]',fontsize=14)\n plt.ylabel(r'$N_{MN95}$ [m]',fontsize=14)\n \n \n \ndef plotDisplacements(points,options):\n \n for key, value in points.items():\n pts_no = key\n pt_y = value.east\n pt_x = value.north\n \n f = options['scaleDisplacement'][0]\n \n dy = value.displ_east\n dx = value.displ_north\n #plt.quiver(pt_y,pt_x,dy,dx,color='red', scale_units='xy',units='xy', angles='xy',scale=1/f)\n plt.plot([pt_y,pt_y+dy*f],[pt_x,pt_x+dx*f],color='red',linewidth=2)\n \n if np.sqrt(dy**2+dx**2)>0.000001:\n angle = np.arctan2(dy,dx)*180/np.pi\n plt.plot(pt_y+dy*f,pt_x+dx*f,marker=(3,0,-angle),color='red',markersize=10)\n \n plt.axis('equal')\n plt.xticks(fontsize=14)\n plt.yticks(fontsize=14)\n plt.grid(True)\n plt.xlabel(r'$E_{MN95}$ [m]',fontsize=14)\n plt.ylabel(r'$N_{MN95}$ [m]',fontsize=14)\n \n \n######################\n###### READ IPL ######\n######################\n \n# my_int equals int but returns 0 in case of an empty string\n# or an string with only blanks\ndef my_int(my_string):\n my_string.replace(' ','')\n if len(my_string) == 0:\n return 0\n if len(my_string) == 1:\n if ord(my_string) == 32:\n return 0\n nb_spaces = 0\n for car in my_string:\n if ord(car) == 32:\n nb_spaces = nb_spaces + 1\n if nb_spaces == len(my_string):\n return 0\n return int(float(my_string))\n\n\n#####################################\n###### HIER ANPASSEN\n#####################################\n\ndef readIpl(path):\n fname = path\n \n \n # fname root\n fname_root = fname.split(\".\")\n \n \n lines = [line.rstrip('\\n') for line in open(fname)]\n ##with open(fname) as f:\n ## lines = f.readlines()\n \n title1 = lines[0]\n title2 = lines[1]\n net_type = lines[2][0:8]\n \n if net_type != \"LAGENETZ\" and net_type != \"RESEAU P\":\n print(\"Program does only work with LAGENETZ\")\n temp = input(\"Press ENTER to end...\")\n sys.exit()\n \n i = 7\n \n point_name_per_index = {}\n point_index_per_number = {}\n point_coordinates = []\n \n points = {}\n \n ## PUNKTE\n nb_pt = 0\n while True:\n # end of the point section\n if lines[i].strip() == \"MESSUNGEN\":\n break\n \n # read point type\n point_fix = lines[i][0]\n point_name = lines[i][1:17]\n point_name = point_name.strip()\n point_numb = int(lines[i][19:27])\n point_east = float(lines[i][27:41])\n point_north = float(lines[i][41:55])\n \n i = i + 1\n \n if point_name == \"PLOT\":\n continue\n \n cur_point = Point(point_name)\n cur_point.planiFix = point_fix\n cur_point.ipl_id = point_numb\n cur_point.east = point_east\n cur_point.north = point_north\n points.update({cur_point.id:cur_point})\n \n i = i + 1\n observations = []\n ## MESSUNGEN\n while True:\n # end of the point section\n if lines[i].strip() == \"VERSCHIEBUNGEN\":\n break\n \n pt1 = my_int(lines[i][2:10])\n pt2 = my_int(lines[i][10:18])\n gnss = my_int(lines[i][33:34])\n dist = my_int(lines[i][39:40])\n hz = my_int(lines[i][46:48])\n v = my_int(lines[i][78:80])\n \n id1 = findIdFromIplID(points,pt1)\n id2 = findIdFromIplID(points,pt2)\n if dist>0:\n type_obs = 'DP'\n elif hz > 0:\n type_obs = 'RI'\n \n cur_obs = Observation(id1,id2,type_obs)\n observations.append(cur_obs)\n \n i = i+1\n \n i = i + 1\n ## VERSCHIEBUNGEN\n while True:\n # end of the point section\n if lines[i].strip() == \"ELLIPSEN\":\n break\n \n pt1 = my_int(lines[i][2:10])\n dx = float(lines[i][10:20])/1000\n dy = float(lines[i][20:30])/1000\n \n id1 = findIdFromIplID(points,pt1)\n points[id1].displ_east = dx\n points[id1].displ_north = dy\n \n i = i+1\n \n i = i + 1\n ## ELLIPSEN\n while True:\n # end of the point section\n if lines[i].strip() == \"ZUVERLAESSIGKEIT\":\n break\n \n pt1 = my_int(lines[i][2:10])\n a = float(lines[i][10:20])/1000\n b = float(lines[i][20:30])/1000\n azi = float(lines[i][30:40])\n \n id1 = findIdFromIplID(points,pt1)\n points[id1].ellipse_a = a\n points[id1].ellipse_b = b\n points[id1].ellipse_azi = azi\n \n i = i+1\n \n i = i + 1\n ## ZUVERLAESSIGKEIT\n while True:\n # end of the point section\n if lines[i].strip() == \"ENDE\":\n break\n \n pt1 = my_int(lines[i][2:10])\n NA = float(lines[i][10:20])/1000\n NB = float(lines[i][20:30])/1000\n azi = float(lines[i][30:40])\n \n id1 = findIdFromIplID(points,pt1)\n points[id1].fiab_NA = NA\n points[id1].fiab_NB = NB\n points[id1].fiab_azi = azi\n \n i = i+1 \n \n return points,observations","repo_name":"bpshop/ipl2plot","sub_path":"adjustmentNetwork.py","file_name":"adjustmentNetwork.py","file_ext":"py","file_size_in_byte":11892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"35738682920","text":"# for\n\nrestaurants = [\n {\"name\": \"Restaurante A\", \"nota\": 4.5},\n {\"name\": \"Restaurante B\", \"nota\": 3.0},\n {\"name\": \"Restaurante C\", \"nota\": 4.2},\n {\"name\": \"Restaurante D\", \"nota\": 2.3},\n]\n\n# maneira normal de resolução do problema (restaurantes com nota > 3.0)\nfiltered_restaurants = []\nmin_rating = 3.0\nfor restaurant in restaurants:\n if restaurant[\"nota\"] > min_rating:\n filtered_restaurants.append(restaurant)\nprint(filtered_restaurants) # imprime a lista de restaurantes, sem o B e D\n\n# MANEIRA PYTÔNICA DE RESOLUÇÃO (restaurantes com nota > 3.0)\nmin_rating = 3.0\nfiltered_restaurants = [restaurant for restaurant in restaurants\n if restaurant[\"nota\"] > min_rating]\nprint(filtered_restaurants) # imprime a lista de restaurantes, sem o B e D\n\n# Chamando os restaurantes apenas pelo 'name'\n# prática equivalente ao MAP ou FILTER do JavaScript!!!\nmin_rating = 3.0\nfiltered_restaurants = [restaurant[\"name\"] for restaurant in restaurants\n if restaurant[\"nota\"] > min_rating]\nprint(filtered_restaurants)\n\n# percorrendo sequência numérica\nfor index in range(5):\n print(index)\n\n\n# while\n\n# sequência de Fibonacci:\n# começa por 0 e 1 e cada elemento subsequente é à soma dos\n# dois termos anteriores\n\nn = 10\nlast, next = 0, 1\nwhile last < n:\n print(last)\n last, next = next, last + next\n","repo_name":"SavioMoraes/trybe-exercises","sub_path":"Modulo 4/Bloco_32-Introdução_à_Python/Dia_01/estruturas_de_repeticao/estruturas_de_repeticao.py","file_name":"estruturas_de_repeticao.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"10955115856","text":"\"\"\"Самописный класс для удобной работы с матрицами\"\"\"\n\nfrom copy import deepcopy\nfrom random import randint\n\n\nclass MatrixClass:\n \"\"\"Класс матрицы\"\"\"\n\n def __init__(self, generation_way=None, matrix_list=None, n=None, m=None):\n \"\"\"\n generation_way - флаг ввода данных. 1 - автоматический ввод, 2 - ручной ввод\n matrix_list - создание объекта MatrixClass из существующей матрицы в list\n \"\"\"\n\n self.generation_way = generation_way\n self.n, self.m = n, m\n # Генерируем новую матрицу\n if matrix_list == None:\n self._matrix = []\n self._matrix_range_input()\n self._matrix_values_input()\n # Выставляем текущую матрицу\n else:\n self._matrix = matrix_list\n if self.n == None and self.m == None:\n self.n = len(matrix_list)\n self.m = len(matrix_list[0])\n\n def _matrix_range_input(self):\n \"\"\"Ввод данных матрицы в зависимости от флага\"\"\"\n if self.n != None and self.m != None:\n return\n boolean_flag = True\n # Размерность матрицы\n while boolean_flag:\n n = input(\"Введите кол-во строк в матрице -> \")\n m = input(\"Введите кол-во столбцов в матрице -> \")\n if self._digital_checker(n) and self._digital_checker(m):\n boolean_flag = False\n self.n, self.m = int(n), int(m)\n else:\n print(\"Некорректный ввод данных!\")\n\n def _matrix_values_input(self):\n \"\"\"Ввод матрицы\"\"\"\n allowed_ways = [\"1\", \"2\"]\n n = self.n\n m = self.m\n matrix = self._matrix\n\n if self.generation_way == None:\n boolean_flag = True\n while boolean_flag:\n generation_way = input(\n \"Каким способом вы хотите задать значения матрицы?\\n1. Автоматический ввод\\n2. Ручной ввод\\n-> \"\n )\n if generation_way in allowed_ways:\n boolean_flag = False\n generation_way = int(generation_way)\n else:\n print(\"Некорректный ввод данных!\")\n else:\n generation_way = self.generation_way\n\n if generation_way == 1:\n # Генерируем матрицу из диапазона\n for i in range(n):\n buf_matrix = []\n for j in range(m):\n buf_matrix.append(randint(1, 10))\n matrix.append(buf_matrix)\n\n elif generation_way == 2:\n # Ручной ввод матрицы\n for i in range(n):\n buf_matrix = []\n for j in range(m):\n\n boolean_flag = True\n while boolean_flag:\n e = input(\"Введите элемент [{}][{}] -> \".format(i + 1, j + 1))\n if self._digital_checker(e):\n boolean_flag = False\n buf_matrix.append(float(e))\n else:\n print(\n \"Некорректный ввод элемента [{}][{}], повторите попытку.\".format(\n i + 1, j + 1\n )\n )\n\n matrix.append(buf_matrix)\n self._matrix = matrix\n\n def __str__(self):\n \"\"\"Вывод матрицы\"\"\"\n matrix = self._matrix\n return \"\\n\" + \"\\n\".join(\n [\"\\t\".join([str(cell) for cell in row]) for row in matrix]\n )\n\n def __mul__(self, m2):\n \"\"\"Умножение матриц\"\"\"\n\n if self.m != m2.n:\n raise ValueError(\"Кол-во столбцов матрицы != кол-ву строк\")\n\n a = self._matrix\n b = m2.matrix\n c = []\n\n for i in range(self.n):\n c.append([])\n for j in range(m2.m):\n c[i].append(0)\n for k in range(self.m):\n c[i][j] += a[i][k] * b[k][j]\n return MatrixClass(matrix_list=c)\n\n def __add__(self, m2):\n \"\"\"Сложение матриц\"\"\"\n if self.n != m2.n or self.m != m2.m:\n raise ValueError(\"Матрицы разного порядка!\")\n c = [\n list(map(lambda x, y: x + y, self._matrix[i], m2.matrix[i]))\n for i in range(self.n)\n ]\n return MatrixClass(matrix_list=c)\n\n def __sub__(self, m2):\n \"\"\"Вычитание матриц\"\"\"\n if self.n != m2.n or self.m != m2.m:\n raise ValueError(\"Матрицы разного порядка!\")\n c = [\n list(map(lambda x, y: x - y, self._matrix[i], m2.matrix[i]))\n for i in range(self.n)\n ]\n return MatrixClass(matrix_list=c)\n\n def _matrix_transposed(self):\n \"\"\"Вычисление транспонированной матрицы\"\"\"\n matrix = self._matrix\n return MatrixClass(matrix_list=list(zip(*matrix)))\n\n def _matrix_determinant(self, A=None, total=0):\n \"\"\"Вычисление определителя матрицы\"\"\"\n # Если первая итерация\n if A == None:\n A = self._matrix\n\n indices = list(range(len(A)))\n\n # Когда доехали до матрицы 2 на 2\n if len(A) == 2 and len(A[0]) == 2:\n val = A[0][0] * A[1][1] - A[1][0] * A[0][1]\n return val\n\n # Определяем подматрицу\n for fc in indices:\n\n As = deepcopy(A)\n As = As[1:] # Удаляем первую строку\n height = len(As)\n\n for i in range(height):\n As[i] = As[i][0:fc] + As[i][fc + 1 :]\n\n sign = (-1) ** (fc % 2)\n sub_det = self._matrix_determinant(As)\n total += sign * A[0][fc] * sub_det\n\n return total\n\n def _matrix_minor(self, i, j):\n \"\"\"Вычисление минора матрицы\"\"\"\n m = self._matrix\n return [row[:j] + row[j + 1 :] for row in (m[:i] + m[i + 1 :])]\n\n def _matrix_inverse(self):\n \"\"\"Вычисление обратной матрицы (сделать проверку умножением на исходную матрицу)\"\"\"\n m = self._matrix\n # Определитель матрицы\n determinant = self._matrix_determinant()\n\n # Вычисления для матрицы 2x2\n if len(m) == 2:\n return MatrixClass(\n matrix_list=[\n [m[1][1] / determinant, -1 * m[0][1] / determinant],\n [-1 * m[1][0] / determinant, m[0][0] / determinant],\n ]\n )\n\n # Результат\n result_matrix = []\n for r in range(len(m)):\n cofactorRow = []\n for c in range(len(m)):\n minor = self._matrix_minor(r, c)\n cofactorRow.append(((-1) ** (r + c)) * self._matrix_determinant(minor))\n result_matrix.append(cofactorRow)\n\n # Транспонированная матрица\n result_matrix = list(map(list, zip(*result_matrix)))\n\n for r in range(len(result_matrix)):\n for c in range(len(result_matrix)):\n result_matrix[r][c] = result_matrix[r][c] / determinant\n return MatrixClass(matrix_list=result_matrix)\n\n def _digital_checker(self, number):\n \"\"\"Метод для проверки элемента на число\"\"\"\n try:\n float(number)\n return True\n except ValueError:\n return False\n\n @property\n def matrix(self):\n return self._matrix\n\n @property\n def matrix_transposed(self):\n \"\"\"Свойство для транспонированной матрицы\"\"\"\n return self._matrix_transposed()\n\n @property\n def matrix_determinant(self):\n \"\"\"Свойство для определителя матрицы\"\"\"\n return self._matrix_determinant()\n\n @property\n def matrix_inverse(self):\n \"\"\"Свойство для обратной матрицы\"\"\"\n return self._matrix_inverse()\n","repo_name":"GeorgiyDemo/FA","sub_path":"Course_I/Практика Python/Part2/pract3/DEMKAMatrixClass.py","file_name":"DEMKAMatrixClass.py","file_ext":"py","file_size_in_byte":8755,"program_lang":"python","lang":"ru","doc_type":"code","stars":36,"dataset":"github-code","pt":"77"}
+{"seq_id":"26999222619","text":"from flask import request\nfrom flask_restx import Namespace, Resource\n\nfrom decorators import auth_required\nfrom project.container import favorite_movie_dao\n\napi = Namespace('favorites')\n\n\n@api.route('/movies/')\nclass UsersView(Resource):\n @auth_required\n def post(self, movie_id, user_id):\n user = favorite_movie_dao.create(movie_id, user_id)\n return f\"Запись создана: {user.id}\", 200\n\n @auth_required\n def delete(self, user_id, movie_id):\n user = favorite_movie_dao.delete(movie_id, user_id)\n return f\"Запись удалена\", 200\n","repo_name":"BityutskiyNA/SkyPRO_coursework_3","sub_path":"project/views/main/favorite_movie.py","file_name":"favorite_movie.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"15568729357","text":"from __future__ import print_function\n\nimport fcntl\nimport hashlib\nimport subprocess\nimport re\nimport sys\n\nfrom io import StringIO\nfrom os import stat\nfrom re import search\nfrom time import time, sleep\n\n## Functions\n\ndef flatten(orig, flat):\n \"\"\"\n Flattens nested iterables in orig to single depth list appended to flat.\n \"\"\"\n if '__iter__' not in dir(orig):\n flat += [orig]\n else:\n for memb in orig:\n flatten(memb, flat)\n\n\ndef get_ge_ver():\n \"\"\"\n Runs GE's whatRev and returns the major and minor version numbers as a\n tuple of ints: (major, minor).\n \"\"\"\n rev = subprocess.Popen([\"/usr/g/bin/whatRev\", \"-format_small\"],\n stdout=subprocess.PIPE)\n rev.wait()\n rev = rev.stdout.readline()\n rev = [int(z) for z in search(r'([0-9]+)\\.([0-9]*)', rev).group(1, 2)]\n return rev\n\n\ndef pretty_bytes(num):\n \"\"\"\n Pretty string of bytes size\n \"\"\"\n ext = {0: '', 10: 'K', 20: 'M', 30: 'G', 40: 'T', 50: 'E'}\n for pwr in sorted(ext.keys()):\n if num / 2.0**pwr < 512:\n return \"{0:.3g} {1}B\".format(num / 2.0**pwr, ext[pwr])\n return \"{0:g} B\".format(num)\n\n\ndef print_out(output, label=('Output', 'Error messages')):\n \"\"\"\n Prints output[:], described by label[:], sequentially to stdout.\n \"\"\"\n printed = False\n for (buf, lbl) in zip(output, label):\n if buf is None or buf.find('\\n') == -1:\n continue\n printed = True\n print(\" +--- %s:\" % lbl)\n if sys.version_info[0] >= 3:\n buf = StringIO(buf)\n else:\n buf = StringIO(unicode(buf))\n for line in buf:\n print(\" | \" + line.rstrip())\n print(\" +--- End of %s.\" % lbl)\n if not printed:\n print(\" -- No output --\")\n\n\ndef run_cmd(cmd):\n \"\"\"\n Runs the external command cmd in a shell and prints the result.\n Raises an IOError exception if a non-zero exit code is detected.\n \"\"\"\n print(\"Executing command [{0}]\".format(cmd))\n sub_cmd = subprocess.Popen(cmd,\n bufsize=4096,\n close_fds=True,\n shell=True,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n universal_newlines=True)\n output = sub_cmd.communicate()\n print_out(output)\n if sub_cmd.returncode: # Had a non-zero return code\n raise IOError(\"Subprocess returned non-zero exit code (%d)\" %\n sub_cmd.returncode)\n\n\ndef settle_file(file_path, age=5.0):\n \"\"\"Wait until file at file_path is at least age seconds old.\"\"\"\n def wait_time():\n \"How much longer to wait for file_path to be age seconds old.\"\n return max(0.0, stat(file_path).st_mtime + age - time())\n start_time = time()\n slept = False\n while wait_time() > 0.0:\n if not slept:\n print(\"Waiting for file [{0}] to stop changing.\".format(file_path))\n print(\" ^-\", end=\"\")\n sys.stdout.flush()\n sleep(min(1, wait_time()))\n print(\"-\", end=\"\")\n sys.stdout.flush()\n slept = True\n if slept:\n print(\" waited {0:.2g}s total.\".format(time() - start_time))\n\n\ndef get_fid(pathname):\n if not re.match('^\\d+$', pathname):\n return None\n fd = int(pathname)\n try:\n fcntl.fcntl(fd, fcntl.F_GETFL)\n return fd\n except OSError as err:\n return None\n## Classes\n\nclass MD5Wrapper(object):\n \"\"\"\"\n Used to wrap a file object which will be checksummed while read().\n \"\"\"\n def __init__(self, fileObject):\n \"\"\"\n Creates a new MD5Wrapper object; initialized checksum.\n\n fileObject: Opened object supporting read([size]) method.\n \"\"\"\n self.handle = fileObject\n # Create checksum object\n try:\n self.md5 = hashlib.md5()\n except ValueError:\n # pylint: disable=E1123\n # RHEL FIPS mode support\n self.md5 = hashlib.md5(usedforsecurity=False)\n\n def read(self, *args):\n \"\"\"\n Read from wrapped file and update checksum.\n \"\"\"\n buf = self.handle.read(*args)\n self.md5.update(buf)\n return buf\n\n def hexdigest(self):\n \"\"\"\n Return hexdigest (string) of read bytes.\n \"\"\"\n return self.md5.hexdigest()\n","repo_name":"eborisch/autorec","sub_path":"ar_lib/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4454,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"18094956848","text":"\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('appliances', '0007_provider_num_simultaneous_configuring'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='appliance',\n name='uuid',\n field=models.CharField(\n help_text=b'UUID of the machine', max_length=36, null=True, blank=True),\n preserve_default=True,\n ),\n ]\n","repo_name":"ManageIQ/integration_tests","sub_path":"sprout/appliances/migrations/0008_appliance_uuid.py","file_name":"0008_appliance_uuid.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":70,"dataset":"github-code","pt":"77"}
+{"seq_id":"22543743452","text":"from __future__ import annotations\nfrom contextlib import contextmanager\nimport pickle\nfrom typing import Generator, Generic, TypeVar\n\nimport sqlite3\n\nfrom .supports_caching import SupportsCaching\n\n\nCT = TypeVar(\"CT\")\n\n\nclass PersistentCache(SupportsCaching, Generic[CT]):\n \"\"\"A cache that persists in between app restarting\"\"\"\n\n def __init__(self, db_name: str = \"items.db\") -> None:\n self.database = db_name\n self._ensure_table_exists()\n\n def add(self, key: str, value: CT) -> None:\n \"\"\"Adds the value to the cache.\"\"\"\n picked_value = pickle.dumps(value)\n cursor = self.connection.cursor()\n cursor.execute(\n \"INSERT INTO items (key, value) VALUES (?, ?)\",\n (key, picked_value),\n )\n self.connection.commit()\n cursor.close()\n\n def head(self, key: str) -> CT:\n \"\"\"\n Returns the most recently added value for the key.\n Raises KeyError if the key is not found.\n \"\"\"\n cursor = self.connection.cursor()\n cursor.execute(\n \"SELECT value FROM items WHERE key = ? ORDER BY added DESC\",\n # \"LIMIT 1\",\n (key,),\n )\n cursor_value = cursor.fetchone()\n if cursor_value is None:\n raise KeyError(key)\n pickled_value = cursor_value[0]\n value: CT = pickle.loads(pickled_value)\n return value\n\n def count(self, key: str) -> int:\n \"\"\"Return the number of values stored for the key.\"\"\"\n cursor = self.connection.cursor()\n cursor.execute(\n \"SELECT COUNT(*) FROM items WHERE key = ?\",\n (key,),\n )\n row_count: int = cursor.fetchone()[0]\n cursor.close()\n return row_count\n\n def list(self) -> Generator[CT, None, None]:\n cursor = self.connection.cursor()\n cursor.execute(\"SELECT value FROM items\")\n for row in cursor.fetchall():\n pickled_value = row[0]\n value: CT = pickle.loads(pickled_value)\n yield value\n\n def _ensure_table_exists(self) -> None:\n with self:\n cursor = self.connection.cursor()\n cursor.execute(\n \"CREATE TABLE IF NOT EXISTS items \"\n \"(key TEXT, value BLOB, added DATETIME DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')))\"\n )\n self.connection.commit()\n cursor.close()\n\n def __enter__(self) -> PersistentCache:\n \"\"\"Open the underlying connection to the database\"\"\"\n self.connection = sqlite3.connect(self.database)\n return self\n\n def __exit__(self, exc_type, exc_value, exc_traceback) -> None:\n \"\"\"Close the underlying connection to the database\"\"\"\n self.connection.close()\n","repo_name":"python-spokane/journey-to-the-pythonic-peak","sub_path":"app/cache/persistent_cache.py","file_name":"persistent_cache.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"14499457121","text":"import sys\nfrom collections import defaultdict\n\nlast_frequency = 0\n\ndef operate(instr, registers):\n global last_frequency\n if len(instr) > 2:\n val = registers[instr[2]] if isinstance(instr[2], str) else instr[2]\n if instr[0] == 'snd':\n last_frequency = registers[instr[1]]\n elif instr[0] == 'set':\n registers[instr[1]] = val\n elif instr[0] == 'add':\n registers[instr[1]] += val\n elif instr[0] == 'mul':\n registers[instr[1]] *= val\n elif instr[0] == 'mod':\n registers[instr[1]] = registers[instr[1]] % val\n elif instr[0] == 'rcv':\n if registers[instr[1]] > 0:\n print('RCV: ', last_frequency)\n sys.exit()\n else: # instr[0] == 'jgz':\n if registers[instr[1]] > 0:\n return val\n return 1\n\ndef play(instructions, registers):\n i = 0\n while True:\n incr = operate(instructions[i], registers)\n i += incr\n\nif __name__ == '__main__':\n instructions = []\n registers={}\n with open('18-input.txt') as f:\n for line in f.readlines():\n cmd = line.strip().split()\n if cmd[1].isalpha():\n registers[cmd[1]] = 0\n else:\n cmd[1] = int(cmd[1])\n if len(cmd) > 2:\n if cmd[2].isalpha():\n registers[cmd[2]] = 0\n else:\n cmd[2] = int(cmd[2])\n instructions.append(cmd)\n print(len(instructions))\n print(registers)\n play(instructions, registers)\n","repo_name":"tjcuddihy/AoC2017","sub_path":"18-1.py","file_name":"18-1.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"23947756679","text":"\"\"\"Some functions from R-base\n\nIf a function uses DataFrame/DataFrameGroupBy as first argument, it may be\nregistered by `register_verb` and should be placed in `./verbs.py`\n\"\"\"\nimport itertools\nfrom typing import Any, Callable, Iterable, List, Union\nimport numpy\n\nimport pandas\nfrom pandas import Categorical, DataFrame\nfrom pipda import register_func\n\nfrom ..core.middlewares import WithDataEnv\nfrom ..core.types import NumericType, is_scalar\nfrom ..core.contexts import Context\nfrom ..core.utils import arg_match\nfrom ..core.names import repair_names\n\n\n@register_func(None, context=Context.EVAL)\ndef cut(\n x: Iterable[NumericType],\n breaks: Any,\n labels: Iterable[Any] = None,\n include_lowest: bool = False,\n right: bool = True,\n precision: int = 2,\n ordered_result: bool = False,\n) -> Categorical:\n \"\"\"Divides the range of x into intervals and codes the values in x\n according to which interval they fall. The leftmost interval corresponds\n to level one, the next leftmost to level two and so on.\n\n Args:\n x: a numeric vector which is to be converted to a factor by cutting.\n breaks: either a numeric vector of two or more unique cut points or\n a single number (greater than or equal to 2) giving the number of\n intervals into which x is to be cut.\n labels: labels for the levels of the resulting category. By default,\n labels are constructed using \"(a,b]\" interval notation.\n If labels = False, simple integer codes are returned instead\n of a factor.\n include_lowest: bool, indicating if an ‘x[i]` equal to the lowest\n (or highest, for right = FALSE) ‘breaks’ value should be included.\n right: bool, indicating if the intervals should be closed on the right\n (and open on the left) or vice versa.\n precision:integer which is used when labels are not given. It determines\n the precision used in formatting the break numbers. Note, this\n argument is different from R's API, which is dig.lab.\n ordered_result: bool, should the result be an ordered categorical?\n\n Returns:\n A categorical object with the cuts\n \"\"\"\n if labels is None:\n ordered_result = True\n\n return pandas.cut(\n x,\n breaks,\n labels=labels,\n include_lowest=include_lowest,\n right=right,\n precision=precision,\n ordered=ordered_result,\n )\n\n\n@register_func(None, context=Context.EVAL)\ndef identity(x: Any) -> Any:\n \"\"\"Return whatever passed in\n\n Expression objects are evaluated using parent context\n \"\"\"\n return x\n\n\n@register_func(None, context=Context.EVAL)\ndef expandgrid(*args: Iterable[Any], **kwargs: Iterable[Any]) -> DataFrame:\n \"\"\"Expand all combinations into a dataframe. R's `expand.grid()`\"\"\"\n iters = {}\n for i, arg in enumerate(args):\n name = getattr(arg, \"name\", getattr(arg, \"__name__\", f\"Var{i}\"))\n iters[name] = arg\n iters.update(kwargs)\n\n return DataFrame(\n list(itertools.product(*iters.values())), columns=iters.keys()\n )\n\n\n@register_func(None, context=Context.EVAL)\ndef outer(x, y, fun: Union[str, Callable] = \"*\") -> DataFrame:\n \"\"\"Compute the outer product of two vectors.\n\n Args:\n x: The first vector\n y: The second vector\n fun: The function to handle how the result of the elements from\n the first and second vectors should be computed.\n The function has to be vectorized at the second argument, and\n return the same shape as y.\n\n Returns:\n The data frame of the outer product of x and y\n \"\"\"\n if fun == \"*\":\n return DataFrame(numpy.outer(x, y))\n\n return DataFrame([fun(xelem, y) for xelem in x])\n\n\n@register_func(None, context=Context.EVAL)\ndef make_names(names: Any, unique: bool = False) -> List[str]:\n \"\"\"Make names available as columns and can be accessed by `df.`\n\n The names will be transformed using `python-slugify` with\n `lowercase=False` and `separator=\"_\"`. When the first character is\n a digit, preface it with \"_\".\n\n If `unique` is True, the results will be fed into\n `datar.core.names.repair_names(names, \"unique\")`\n\n Args:\n names: The names\n if it is scalar, will make it into a list.\n Then all elements will be converted into strings\n unique: Whether to make the names unique\n\n Returns:\n Converted names\n \"\"\"\n from slugify import slugify\n from . import as_character\n\n if is_scalar(names):\n names = [names]\n names = as_character(names)\n names = [slugify(name, separator=\"_\", lowercase=False) for name in names]\n names = [f\"_{name}\" if name[0].isdigit() else name for name in names]\n if unique:\n return repair_names(names, \"unique\")\n return names\n\n\n@register_func(None, context=Context.EVAL)\ndef make_unique(names: Any) -> List[str]:\n \"\"\"Make the names unique.\n\n It's a shortcut for `make_names(names, unique=True)`\n\n Args:\n names: The names\n if it is scalar, will make it into a list.\n Then all elements will be converted into strings\n\n Returns:\n Converted names\n \"\"\"\n return make_names(names, unique=True)\n\n\n@register_func(None, context=Context.EVAL)\ndef rank(\n x: Iterable,\n na_last: bool = True,\n ties_method: str = \"average\",\n) -> Iterable:\n \"\"\"Returns the sample ranks of the values in a vector.\n\n Args:\n x: A numeric vector\n na_last: for controlling the treatment of `NA`s. If `True`, missing\n values in the data are put last; if `False`, they are put\n first; if `\"keep\"` they are kept with rank `NA`.\n ties_method: a character string specifying how ties are treated\n One of `average`, `first`, `dense`, `max`, and `min`\n Note that the ties_method candidates are different than the ones\n from R, because we are using `pandas.Series.rank()`. See\n https://pandas.pydata.org/docs/reference/api/pandas.Series.rank.html\n\n Returns:\n A numeric rank vector of the same length as `x`\n \"\"\"\n ties_method = arg_match(\n ties_method,\n \"ties_method\",\n [\"average\", \"first\", \"dense\", \"max\", \"min\"],\n )\n\n from ..dplyr.rank import _rank\n return _rank(x, na_last, method=ties_method)\n\n# ---------------------------------\n# Plain functions\n# ---------------------------------\n\n\ndef data_context(data: DataFrame) -> Any:\n \"\"\"Evaluate verbs, functions in the\n possibly modifying (a copy of) the original data.\n\n It mimic the `with` function in R, but you have to write it in a python way,\n which is using the `with` statement. And you have to use it with `as`, since\n we need the value returned by `__enter__`.\n\n Args:\n data: The data\n func: A function that is registered by\n `pipda.register_verb` or `pipda.register_func`.\n *args: Arguments for func\n **kwargs: Keyword arguments for func\n\n Returns:\n The original or modified data\n \"\"\"\n return WithDataEnv(data)\n","repo_name":"Gedevan-Aleksizde/datar","sub_path":"datar/base/funs.py","file_name":"funs.py","file_ext":"py","file_size_in_byte":7143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"77"}
+{"seq_id":"71753220408","text":"from setuptools import find_packages, setup\r\n\r\nwith open(\"requirements.txt\") as f:\r\n required = f.read().splitlines()\r\n\r\nsetup(\r\n name=\"abstracts_embeddings_evaluation\",\r\n description=\"Data and code used for evaluating abstracts embeddings on a papers classification task\",\r\n author=[\"Giovanni Zurlo\"],\r\n author_email=\"giovanni.zurlo@studio.unibo.it\",\r\n install_requires=required,\r\n packages=find_packages(),\r\n)","repo_name":"zurlog/abs-embeddings-eval","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"30087778469","text":"gols=list()\r\nlista=list()\r\nJogador=dict()\r\nwhile True:\r\n Jogador['nome']=input(str('Qual é o nome do jogador?'))\r\n partidas=int(input(f'Quantas partidas {Jogador[\"nome\"]} jogou? '))\r\n for c in range (1,partidas+1):\r\n Jogador['gols']=(int(input(f'Quantos gols na partida {c} ')))\r\n gols.append(Jogador['gols'])\r\n tot_gol = sum(gols)\r\n continua=str(input('Deseja continua? [S/N]' )).upper().strip()[0]\r\n if continua == 'N':\r\n lista.append(Jogador)\r\n Jogador.clear()\r\n break\r\nprint('=+'* 30)\r\nprint(gols)\r\nprint(Jogador)\r\nprint(tot_gol)\r\nprint(lista)\r\n\r\n#while True:\r\n# jogador=int(input('Coloque o numero do jogador que você quer ver, para finalizar digite [999] '))\r\n# print(['jogador'])","repo_name":"oGabrielCruz/python-exercices","sub_path":"Exc095.py","file_name":"Exc095.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"29329220039","text":"#Aprobación de créditos\n\ningreso = int(input(\"Ingrese su ingreso en pesos: \"))\nnacimiento = int(input(\"Ingrese su año de nacimiento: \"))\nhijo = int(input(\"Ingrese cuantos hijos tiene: \"))\naños = int(input(\"Ingrese los años que ha pertenecido al banco: \"))\n\nestado = (input(\"'S': soltero, 'C': casado\\nIngrese su estado civil: \"))\n\nvivienda = (input(\"'U': urbano, 'R': rural\\nIngrese donde vive actualmente: \"))\n\nedad = 2021 - nacimiento\n\nif (años > 10) and (hijo >= 2):\n print(\"\\nAPROBADO\")\n \nelif ((estado == \"C\") and (hijo > 3)) and (45 <= edad <= 55):\n print(\"\\nAPROBADO\")\n \nelif (ingreso > 2500000) and (estado == \"S\") and (vivienda == \"U\"):\n print(\"\\nAPROBADO\")\n \nelif (ingreso > 3500000) and (años > 5):\n print(\"\\nAPROBADO\")\n \nelif (vivienda == \"R\") and (estado == \"C\") and (hijo < 2):\n print(\"\\nAPROBADO\")\n \nelse:\n print(\"\\nRECHAZADO\")","repo_name":"pabloschwarzenberg/grader","sub_path":"hito1_ej3/hito1_ej3_84fea8a3756e059c20b64aa7ab3ec866.py","file_name":"hito1_ej3_84fea8a3756e059c20b64aa7ab3ec866.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"1642047913","text":"import logging\nimport os\nfrom pathlib import Path\n\nimport pytorch_lightning as pl\nimport torch\nfrom pytorch_lightning.callbacks import Callback\nfrom pytorch_lightning.loggers import WandbLogger\nfrom torch.utils.mobile_optimizer import optimize_for_mobile\n\nfrom pydx7.dx7tools import load_patch\nfrom pydx7.dx7tools import unpack_packed_patch\n\n# Setup logging\nlogging.basicConfig()\nlog = logging.getLogger(__name__)\nlog.setLevel(level=os.environ.get(\"LOGLEVEL\", \"INFO\"))\n\n\nclass TS_ExportModelCallback(Callback):\n \"\"\"\n Callback to export model to TorchScript when finished.\n\n Traces the model and generates a script.\n Then it wraps this script around a ScriptWrapper that contains training patch,\n and may contain also output amplitude denormalization.\n \"\"\"\n\n @torch.no_grad()\n def on_test_end(self, trainer: pl.Trainer, pl_module: pl.LightningModule):\n log.info(\n f\"Export to TorchScript Callback. Envelope type: {pl_module.envelope_type}\"\n )\n\n pl_module = pl_module.to(\"cpu\")\n example_x = torch.ones([1, 1, 2])\n example_state = torch.zeros(1, 1, pl_module.decoder.rnn.hidden_size)\n # Tuple to feed tracer.\n example = (example_x, example_state)\n\n traced_script_module = optimize_for_mobile(\n torch.jit.trace(pl_module, example, check_trace=True)\n )\n print(traced_script_module.code)\n\n filepath = Path(pl_module.data_dir + pl_module.data_file)\n # Confirm that dataset exists\n if not filepath.exists():\n raise FileNotFoundError(\n f\"Envelope dataset not found for exporting patch. Expected: {filepath}\"\n )\n\n # Load the patch from file and store it in wrapper\n dset_dict = torch.load(filepath)\n\n packed_patch = torch.ByteTensor(dset_dict[\"patch\"])\n patch_name = load_patch(packed_patch.numpy())[\"name\"]\n\n unpacked_patch = unpack_packed_patch(dset_dict[\"patch\"])\n if pl_module.envelope_type == \"linear\":\n script_wrapper = ScriptWrapper_linear(\n traced_script_module,\n torch.ByteTensor(unpacked_patch),\n )\n elif pl_module.envelope_type == \"doubling_log\":\n script_wrapper = ScriptWrapper_doubling_log(\n traced_script_module,\n torch.ByteTensor(unpacked_patch),\n )\n\n if isinstance(trainer.logger, WandbLogger):\n group = trainer.logger._wandb_init.get(\"group\")\n outdir = (\n Path(trainer.logger.save_dir).joinpath(\"export\").joinpath(f\"{group}\")\n )\n outdir.mkdir(parents=True, exist_ok=True)\n # traced_script_module.save(\n # str(outdir.joinpath(f\"{trainer.logger._name}.ts\"))\n # )\n script_wrapper.save(str(outdir.joinpath(f\"{patch_name}.ts\")))\n else:\n outdir = Path(\"./\").joinpath(\"export\")\n outdir.mkdir(parents=True, exist_ok=True)\n script_wrapper.save(f\"{patch_name}.ts\")\n return\n\n\nclass ScriptWrapper_linear(torch.jit.ScriptModule):\n \"\"\"\n We can use this wrapper to multiply the output by the correct values\n And to store the training patch\n \"\"\"\n\n def __init__(self, script, patch):\n super().__init__()\n self.register_buffer(\"patch\", patch)\n self.script = script\n\n @torch.jit.script_method\n def forward(self, input: torch.Tensor, state: torch.Tensor):\n outlevels, next_state = self.script(input, state)\n outlevels_denorm = 2 * outlevels\n return (outlevels_denorm, next_state)\n\n\nclass ScriptWrapper_doubling_log(torch.jit.ScriptModule):\n \"\"\"\n We can use this wrapper to multiply the output by the correct values\n And to store the training patch\n \"\"\"\n\n def __init__(self, script, patch):\n super().__init__()\n self.register_buffer(\"patch\", patch)\n self.script = script\n\n @torch.jit.script_method\n def forward(self, input: torch.Tensor, state: torch.Tensor):\n outlevels, next_state = self.script(input, state)\n outlevels_denorm = 2 ** (outlevels * (1 << 4) - 15)\n return (outlevels_denorm, next_state)\n","repo_name":"fcaspe/fmtransfer","sub_path":"fmtransfer/callbacks/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":4202,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"77"}
+{"seq_id":"35793265822","text":"from RPA.Browser.Selenium import Selenium\r\nimport pandas as pd\r\nimport os\r\n\r\n\r\nclass Scrapper:\r\n def __init__(self) -> None:\r\n self.browser = Selenium()\r\n\r\n def make_dir():\r\n \"\"\"Make output dir if not created already.\r\n \"\"\"\r\n if not os.path.exists('./output'):\r\n os.makedirs('./output')\r\n\r\n def open_browser(self):\r\n \"\"\"Open browser.\r\n \"\"\"\r\n self.browser.open_available_browser('https://www.upcollective.io/company/task-managers')\r\n self.browser.wait_until_element_is_visible('//div[@class=\"collection-list filter-complex w-dyn-items\"]', 10)\r\n\r\n def get_each_page_link(self):\r\n \"\"\"Get each service page link.\r\n \"\"\"\r\n count = self.browser.get_element_count('xpath://div[@class=\"collection-list-item w-dyn-item\"]')\r\n href_list = []\r\n\r\n for i in range(1, count+1):\r\n href = self.browser.get_element_attribute(f'xpath:(//a[@class=\"collection-list-content rounded-xs zoom-in w-inline-block\"])[{i}]', 'href')\r\n href_list.append(href)\r\n\r\n return href_list\r\n \r\n def get_data_from_each_page(self, href_list):\r\n \"\"\"Scrap all necessary data from each service page.\r\n \"\"\"\r\n vertical_list = []\r\n task_list = []\r\n title_list = []\r\n description_list = []\r\n flow_list = []\r\n\r\n for href_link in href_list:\r\n self.browser.go_to(href_link)\r\n\r\n self.browser.wait_until_element_is_visible('//strong[text()=\"Vertical\"]//../following-sibling::div', 20)\r\n vertical = self.browser.get_text('//strong[text()=\"Vertical\"]//../following-sibling::div')\r\n vertical_list.append(vertical)\r\n\r\n task = self.browser.get_text('//strong[text()=\"Task\"]//../following-sibling::div')\r\n task_list.append(task)\r\n\r\n title = self.browser.get_text('//h1[@class=\"title-sm-2\"]')\r\n title_list.append(title)\r\n\r\n description = self.browser.get_text('//div[@class=\"text-xl\"]')\r\n description_list.append(description)\r\n\r\n li_count = self.browser.get_element_count('//*[text()=\"Process Flow\"]/following-sibling::ol/li')\r\n if li_count==0:\r\n print(href_link)\r\n\r\n flow_points= ''\r\n for li in range(1, (li_count//2) +1):\r\n li_text = self.browser.get_text(f'(//*[text()=\"Process Flow\"]/following-sibling::ol/li)[{li}]')\r\n flow_points = flow_points + f'{li}) '+ li_text + '\\n'\r\n flow_list.append(flow_points)\r\n\r\n return title_list, vertical_list, task_list, description_list, flow_list\r\n \r\n def make_excel_file(self, href_list):\r\n \"\"\"Create excel file populated with all necessary data like Title, Vertical, Task, Description, Process Flow\r\n \"\"\"\r\n title_list, vertical_list, task_list, description_list, flow_list = self.get_data_from_each_page(href_list)\r\n print(len(title_list), len(vertical_list), len(task_list), len(description_list), len(flow_list))\r\n\r\n data = {\r\n 'Title' : title_list,\r\n 'Vertical' : vertical_list,\r\n 'Task' : task_list,\r\n 'Description' : description_list,\r\n 'Process Flow' : flow_list\r\n }\r\n\r\n df = pd.DataFrame(data) \r\n df.to_excel('./output/upcollective_scrapping.xlsx', index=False)\r\n","repo_name":"pranjitautomation/Upcollective_Scrapping","sub_path":"scrapper.py","file_name":"scrapper.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"8807137294","text":"\"\"\"empty message\n\nRevision ID: 0cd359646c78\nRevises: 0f251cbbfb53\nCreate Date: 2023-10-11 17:39:45.960218\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '0cd359646c78'\ndown_revision = '0f251cbbfb53'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('event', schema=None) as batch_op:\n batch_op.add_column(sa.Column('impound_lot_operator', sa.Integer(), nullable=True))\n batch_op.add_column(sa.Column('submitted', sa.Boolean(), nullable=True))\n batch_op.create_foreign_key(None, 'impound_lot_operator', ['impound_lot_operator'], ['id'])\n batch_op.drop_column('printed')\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('event', schema=None) as batch_op:\n batch_op.add_column(sa.Column('printed', sa.BOOLEAN(), autoincrement=False, nullable=True))\n batch_op.drop_constraint(None, type_='foreignkey')\n batch_op.drop_column('submitted')\n batch_op.drop_column('impound_lot_operator')\n\n # ### end Alembic commands ###\n","repo_name":"bcgov/rsbc-digital-forms","sub_path":"python/prohibition_web_svc/migrations/versions/0cd359646c78_.py","file_name":"0cd359646c78_.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"31288182898","text":"ListaOriginal = [7, 5, 3, 9, 6, 4, 1]\r\nTarefa1 = [7, 5, 3, 9, 6, 4, 1]\r\nSoma = 0\r\nNovaLista = []\r\n\r\nsubstituir = 5\r\nremover = 4\r\nfor x in range(len(Tarefa1)):\r\n if (Tarefa1[x] == 9):\r\n Tarefa1.insert(x, substituir)\r\n Tarefa1.pop(x+1)\r\n\r\nfor x in range(len(Tarefa1)):\r\n if(x == remover):\r\n Tarefa1.pop(x+1)\r\n\r\nNovaLista = Tarefa1\r\n\r\n\r\nfor x in NovaLista:\r\n Soma += x\r\n\r\nprint('Essa é a lista original:', ListaOriginal)\r\nprint('Essa é a nova lista:', NovaLista)\r\nprint('Essa é a soma dos valores da nova lista:', Soma)\r\n","repo_name":"zecaguiarr/AvaliacaoParadigma","sub_path":"Tarefa1.py","file_name":"Tarefa1.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"32336449042","text":"from PySide.QtGui import QPixmap, QApplication\nfrom PySide.QtCore import QBuffer, QIODevice\nimport StringIO\nimport sys\nimport Image\nimport cv2\nimport numpy as np\n\nfrom BGModel import BGmodel\n\nclass Key():\n\t# area : rectangular area, see class definition bellow\n\t# k : key that should be sent when area is activated\n\tdef __init__(self, x, y, w, h, k, snesKey):\n\t\tself.area = RectArea(x, y, w, h)\n\t\tself.key = k\n\t\tself.snesKey = snesKey\n\t\t\t\n\nclass RectArea():\n\tdef __init__(self, x, y, w, h):\n\t\tself.x = int(x)\n\t\tself.y = int(y)\n\t\tself.w = int(w)\n\t\tself.h = int(h)\n\t\n\tdef isIn(self, x, y):\n\t\treturn (self.x <= x <= self.x+self.w and self.y <= y <= self.y+self.h)\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n#-------------------------------------------------------------------------------\n#\n# PLAYER CLASS\n#\n#-------------------------------------------------------------------------------\n\nclass Player():\n\tdef __init__(self, name, screenArea, keymapFunc, detector, scale=0.8, threshLum=50, SFchar=None):\n\t\tself.name = name\n\t\tself.keymapFunc = keymapFunc\n\t\tself.keys = None\n\t\tself.listKey = [] # list of keyboard keys reserved for this player\n\t\t # look up table to map snes key to keyboard key\n\t\tself.lut = dict([(sk, None) for sk in ['u', 'd', 'l', 'r', 'lk', 'mk', 'hk', 'lp', 'mp', 'hp']])\n\t\tself.SFchar = SFchar\n\t\tself.threshLum = threshLum\n\t\tself.screenArea = screenArea\n\t\tself.detector = detector\n\t\t# morphological structuring element to clean the image\n\t\tself.kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))\n\t\tself.scale = scale\n\t\tself.bgmodel = None\n\t\tself.idFrame = 0\n\t\tself.buffer = QBuffer()\n\t\tself.buffer.open(QIODevice.ReadWrite)\n\n\t\n\t\n\tdef grabImg(self):\n\t\tself.idFrame += 1\t\n\t\twid = QApplication.desktop().winId()\n\t\tQPixmap.grabWindow(wid, self.screenArea.x, self.screenArea.y, self.screenArea.w, self.screenArea.h).save(self.buffer, 'png')\n\t\tstrio = StringIO.StringIO()\n\t\tstrio.write(self.buffer.data())\n\t\tself.buffer.seek(0)\n\t\tstrio.seek(0)\n\t\tpix = np.array(Image.open(strio))\n\t\tpix = cv2.resize(pix, (0,0), fx=self.scale, fy=self.scale)\n\t\treal_color = cv2.cvtColor(pix, cv2.COLOR_BGR2RGB)\n\t\treturn real_color\n\t\n\t\n\tdef process(self, real_color, draw = True):\n\t\tgray = cv2.cvtColor(real_color, cv2.COLOR_RGB2GRAY)\n\t\tif self.keys == None:\n\t\t\tself.keys = self.keymapFunc(gray.shape)\n\t\t\tfor k in self.keys:\n\t\t\t\tif 'combo' in k.key:\n\t\t\t\t\tk.key = str(id(self))+'_combo'\n\t\t\t\telse :\n\t\t\t\t\tself.listKey.append(k.key)\n\t\t\t# build look up table \n\t\t\tfor sk in self.lut:\n\t\t\t\tfor kk in self.keys:\n\t\t\t\t\tif kk.snesKey == sk:\n\t\t\t\t\t\tself.lut[sk] = kk.key\n\t\t\t\t\t\tbreak\n\t\tif self.bgmodel is None:\n\t\t\tself.bgmodel = BGmodel(100, gray.shape)\n\t\t\n\t\tif self.idFrame%10==0 or not self.bgmodel.ready :\n\t\t\t#print self.idFrame, \"adding image\"\n\t\t\tself.bgmodel.add(gray)\n\n\t\tBG = self.bgmodel.getModel()\n\t\tFG = self.bgmodel.apply(gray)\n\t\t\n\t\timg = cv2.medianBlur(FG,5)\n\t\tret, bin = cv2.threshold(img, self.threshLum, 255, cv2.THRESH_BINARY)\n\t\t\n\t\tfgmask = cv2.morphologyEx(FG, cv2.MORPH_OPEN, self.kernel)\n\t\tfgmask = cv2.morphologyEx(FG, cv2.MORPH_CLOSE, self.kernel) \n\t\tfgmask = cv2.morphologyEx(FG, cv2.MORPH_CLOSE, self.kernel)\n\t\t# blob detection only if we gathered enough images for the background model\n\t\tif self.bgmodel.ready or True:\n\t\t\tkeypoints = self.detector.detect(FG)\n\t\telse:\n\t\t\tkeypoints = []\n\t\t\n\t\tif draw :\n\t\t\t# Draw detected blobs as red circles.\n\t\t\treal_color = cv2.drawKeypoints(real_color, keypoints, np.array([]), (0,0,255), 4)\n\t\treturn [k.pt for k in keypoints], real_color, BG, FG, bin\n\t\t\n\t\t\n\t\n\n\tdef getKeys(self, draw=True):\n\t\tkeys = []\n\t\t\n\t\tori = self.grabImg()\n\t\tblobs, ori, BG, FG, bin = self.process(ori)\t\n\t\t\t\n\t\tfor k in self.keys:\n\t\t\tx, y, w, h = k.area.x, k.area.y, k.area.w, k.area.h\n\t\t\tcv2.rectangle(ori, (y, x), (y+h,x+w), (0,255,0), 1)\n\t\t\tcv2.putText(ori, k.key, (y+10,x+20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0),2)\n\t\t\tfor p in blobs:\n\t\t\t\tif k.area.isIn(p[1], p[0]):\n\t\t\t\t\tkeys.append(k.key)\n\t\t\t\t\tif ori is not None :\n\t\t\t\t\t\tcv2.rectangle(ori, (y, x), (y+h,x+w), (0,0,255), 2)\n\t\t\t\t\tbreak\n\t\t\t\t\n\t\tif draw :\n\t\t\tcv2.imshow(self.name+\"_color input\", ori)\n\t\t\tcv2.imshow(self.name+\"_BG model\", BG)\n\t\t\t#cv2.imshow(self.name+\"_FG model\", FG)\n\t\t\t#cv2.imshow(self.name+\"_binary image\", bin)\n\n\t\treturn keys\n\t\t\n\t# release all keys associated to a player, before a combo\n\tdef cancelKeys(self, kb, keys):\n\t\tfor k in self.keys :\n\t\t\tif 'combo' not in k.key:\n\t\t\t\tkb.release_key(k.key)\n\t\t\t\tkeys[k.key] = False\n\n\t\t\n\tdef resetBG(self):\n\t\tself.bgmodel = None\n","repo_name":"guyver2/SFA2YT","sub_path":"Player.py","file_name":"Player.py","file_ext":"py","file_size_in_byte":4469,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"21509252847","text":"import random\n\nrandNo=random.randint(1,3)\n# print(randNo)\nif randNo==1:\n comp=\"s\"\nelif randNo==2:\n comp=\"w\"\nelif randNo==3:\n comp=\"g\"\n\ndef game(comp,user):\n if comp==user:\n print(\"\\nGame Draw\")\n elif comp==\"s\":\n if user==\"w\":\n return False\n elif user==\"g\":\n return True\n elif comp==\"w\":\n if user == \"s\":\n return True\n elif user== \"g\":\n return False\n elif comp==\"g\":\n if user==\"w\":\n return True\n elif user==\"s\":\n return False\n\n\nuser=input(\"Enter:\\ns for snake \\nw for water\\ng for gun\\n=>\")\nprint(f\"You choose : {user}\")\n\nprint(f\"Comp choose : {comp}\")\nwin= game(comp,user)\nif win==True:\n print(\"\\nYou Win\")\nelif win==False:\n print(\"\\nYou Loose\")\n# possiblities\n# s vs w == s win\n# s vs g == g win\n# w vs g == w win\n\n\n\n\n \n\n\n\n\n","repo_name":"snad0/python-project","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"16163028441","text":"TRAIN_RATIO = 0.3\nN_EPOCH = 20\n\n#'bayesian_indep', 'bayesian_dep', 'global_indep'\nMETHODS = ['bayesian_indep']\n\n# options are 'stage1', 'stage2', 'off'\nHIERARCHICAL = 'off'\n\n# class options are 'koibito', 'doryo', 'yujin', 'kazoku', 'kazokuc', 'kazokua'\n# kazokuc stand for kazoku with child (ie one member is younger than 15)\n# kazokua stand for kazoku with all members adult (ie all members over 15)\n# see split_kazoku for details\nCLASSES_RAW = ['koibito', 'doryo', 'yujin', 'kazoku'] # used only in retrieving filenames at hier stage2\n\n# if hierarchical is off, options are 'koibito', 'doryo', 'yujin', 'kazoku', 'kazokuc', 'kazokua'\n# if hierarchical is on, it is either stage 1 or stage2\n# In stage1, options are doryo and others\n# In stage2, options are the ones except doryo\nif HIERARCHICAL is 'off':\n CLASSES = ['koibito', 'doryo', 'yujin', 'kazoku']\nelif HIERARCHICAL is 'stage1':\n CLASSES = ['doryo', 'others']\n OTHERS = [item for item in CLASSES_RAW if item not in CLASSES]\nelif HIERARCHICAL is 'stage2':\n CLASSES = ['koibito', 'yujin', 'kazoku']\n \n\n# 'v_g', 'v_diff', 'd', 'h_diff' \nOBSERVABLES = ['v_g', 'v_diff', 'd', 'h_diff' ]\n\n# to be used in global methods\n# 'KLdiv', 'JSdiv', 'EMD', 'LL'\nGLOBAL_MEASURES = [ 'KLdiv', 'JSdiv', 'EMD', 'LL']\n\n# to be used in updating the probabiilty in bayesian approach\nALPHAS = [0, 0.5, 1]\n\n# to be used in DEP methods\n# filtering options are 'none', 'KDE', 'MA'\n# none: no filtering\n# KDE: Kernel density estimation\n# MA: Moving average\nFILTERING =[ 'none', 'MA', 'KDE' ]\n\n# to be used if filtering is set to 'MA'\nSIZE_MA = 5 # support of moving average filter\n\n# to be used if filtering is set to 'KDE'\n# these parameters relate grid search for optimal kernel bandwidth\nBW0 = 4 # lower bound of kernel bandwidth\nBWF = 12# upper bound of kernel bandwidth\nNBINS_BW = 100# number of bins between lower and upper bounds of kernel bandwidth\nNCV_BW = 5# number of cross-vaidation\n","repo_name":"yucelzeynep/Identification-of-social-relation-within-pedestrian-dyads","sub_path":"preferences.py","file_name":"preferences.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"26180367792","text":"\n# Builds a list of blocks for the green line in\n# the correct order to leave the yard, \n# make one full loop around the track, \n# and return to the yard.\nsec1 = [i for i in range(63, 101)]\nsec2 = [i for i in range(85, 76, -1)]\nsec3 = [i for i in range(101, 151)]\nsec4 = [i for i in range(29, 0, -1)]\nsec5 = [i for i in range(13, 58)]\n\nsections = sec1 + sec2 + sec3 + sec4 + sec5\n\nprint(sections)","repo_name":"vism2889/ECE_1140_TRAINS","sub_path":"TrackModel/testing_and_resources/trackBlockTest.py","file_name":"trackBlockTest.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"77"}
+{"seq_id":"39486111272","text":"import urllib.request\nimport urllib.parse\n\nurl = \"http://update.googleapis.com/service/update2?cup2key=7:1439191684&cup2hreq=503cf164d5bdbfa1cbedf171078b2690d941befc84cb30c9fc5e0df541111c67\"\npostdata = urllib.parse.urlencode({\n \"loginname\": \"18911341910\",\n \"nloginpwd\": \"lh1994114\"\n}).encode('utf-8')\nreq = urllib.request.Request(url, postdata)\nreq.add_header(\"User-Agent\",\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 \\\n (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36\")\ndata = urllib.request.urlopen(req).read()\nfhandle = open(\"D:/DeepinPythonWebClawler/3.html\", 'wb')\nfhandle.write(data)\nfhandle.close()\n\nurl2 = \"https://www.jd.com/\"\nreq2 = urllib.request.Request(url2,postdata)\nreq2.add_header(\"User-Agent\",\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 \\\n (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36\")\ndata2 = urllib.request.urlopen(req2).read()\nfhandle = open(\"D:/DeepinPythonWebClawler/4.html\",'wb')\nfhandle.write(data)\nfhandle.close()\n\n","repo_name":"Harold1994/DeepinPythonWebClawler","sub_path":"RE&Cookie/Cookie.py","file_name":"Cookie.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"25044644407","text":"# coding: utf-8\n\nfrom contextlib import contextmanager\nfrom functools import partial\nimport os\nimport tempfile\n\nfrom six import text_type, binary_type, PY2, reraise, StringIO\nimport pytest\n\nfrom data import Data as I\n\n\n@contextmanager\ndef tmpfn(*args, **kwargs):\n try:\n fd, fn = tempfile.mkstemp()\n os.close(fd)\n yield fn\n finally:\n try:\n os.unlink(fn)\n except OSError as e:\n if e.errno != 2:\n reraise(e)\n\n\n@pytest.fixture(\n params=[u'This is sample data as unicode. äüöå \\\\',\n u'',\n u'\\0',\n u'multi\\nline\\ninput']\n)\ndef val(request):\n return request.param\n\n\n@pytest.fixture(\n params=['utf8', 'latin1']\n)\ndef encoding(request):\n return request.param\n\n\n@pytest.yield_fixture\ndef tmpfile():\n tmpfd, tmpfn = tempfile.mkstemp()\n try:\n yield tmpfn\n finally:\n os.unlink(tmpfn)\n\n\n@pytest.fixture\ndef valfile(val, tmpfile, encoding):\n with open(tmpfile, 'wb') as f:\n f.write(val.encode(encoding))\n return tmpfile\n\n\n@pytest.fixture(\n params=['file', 'filename', 'unicode', 'string', 'smart_file',\n 'smart_unicode', 'smart_string', 'move_constructor', 'mvc_file',\n pytest.mark.skipif(\"PY2\")('file_no_encoding')]\n)\ndef d(val, request, encoding, valfile):\n if request.param == 'file':\n v = I(file=open(valfile, 'rb'), encoding=encoding)\n elif request.param == 'filename':\n v = I(file=valfile, encoding=encoding)\n elif request.param == 'unicode':\n v = I(data=val, encoding=encoding)\n elif request.param == 'string':\n v = I(data=val.encode(encoding), encoding=encoding)\n elif request.param == 'smart_file':\n v = I(open(valfile, 'rb'), encoding=encoding)\n elif request.param == 'smart_unicode':\n v = I(val, encoding=encoding)\n elif request.param == 'smart_string':\n v = I(val.encode(encoding), encoding=encoding)\n elif request.param == 'file_no_encoding':\n v = I(open(valfile, 'r', encoding=encoding))\n elif request.param == 'move_constructor':\n inp = I(val, encoding=encoding)\n v = I(inp)\n elif request.param == 'mvc_file':\n inp = I(file=open(valfile, 'rb'), encoding=encoding)\n v = I(inp)\n else:\n raise RuntimeError\n\n v._test_req = request.param\n\n return v\n\n\ndef test_getting_contents_as_bytes_str(d, val, encoding):\n assert binary_type(d) == val.encode(encoding)\n\n\ndef test_getting_contents_as_unicode(d, val):\n assert text_type(d) == val\n\n\ndef test_getting_contents_via_read(d, val):\n assert d.read() == val\n\n\ndef test_getting_contents_via_binary_read(d, val, encoding):\n assert d.readb() == val.encode(encoding)\n\n\ndef test_write_to_filename(d, val, encoding):\n with tmpfn() as fn:\n d.save_to(fn)\n\n with open(fn, 'rb') as f:\n assert f.read() == val.encode(encoding)\n\n\ndef test_write_to_file_obj(d, val, encoding):\n with tempfile.NamedTemporaryFile() as tmp:\n d.save_to(tmp)\n\n tmp.seek(0)\n\n assert tmp.read() == val.encode(encoding)\n\n\ndef test_with_temp_saved(d, val, encoding):\n with d.temp_saved() as tmp:\n assert tmp.read() == val.encode(encoding)\n\n\ndef test_with_temp_saved_fn(d, val, encoding):\n with d.temp_saved() as tmp:\n tmp.close()\n assert open(tmp.name, 'rb').read() == val.encode(encoding)\n\n\ndef test_unicode_reading_incremental(d, val):\n bufsize = 4\n\n chunks = [c for c in iter(partial(d.read, bufsize), '')]\n\n assert u''.join(chunks) == val\n\n\ndef test_bytestring_reading_incremental(d, val, encoding):\n bufsize = 4\n\n chunks = [c for c in iter(partial(d.readb, bufsize), b'')]\n\n assert b''.join(chunks) == val.encode(encoding)\n\n\ndef test_readline(d, val):\n buf = StringIO(val)\n\n for line in buf.readlines():\n assert line == d.readline()\n\n\ndef test_readlines(d, val):\n buf = StringIO(val)\n\n assert buf.readlines() == d.readlines()\n\n\ndef test_close(d):\n d.close()\n d.close()\n\n\ndef test_context_manager(d):\n with d as e:\n assert d == e\n\n if d.file is not None:\n assert d.file.closed\n\n\ndef test_iteration(d, val):\n chunks = [l for l in iter(d)]\n\n assert ''.join(chunks) == val\n","repo_name":"mbr/data","sub_path":"tests/test_inputdata.py","file_name":"test_inputdata.py","file_ext":"py","file_size_in_byte":4252,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"38651051886","text":"class Solution:\n def canAttendMeetings(self, intervals: List[List[int]]) -> bool:\n inter = []\n for item in intervals:\n inter.append(item[0])\n inter.append(item[1])\n \n inter.sort()\n \n for i in range(0, len(inter),2):\n if [inter[i], inter[i+1]] not in intervals:\n return False\n return True\n ","repo_name":"emilyws27/Leetcode","sub_path":"252-meeting-rooms/252-meeting-rooms.py","file_name":"252-meeting-rooms.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"71810664250","text":"import requests\nfrom django.shortcuts import render\nfrom django.views.generic import FormView\nfrom website.forms import PesquisaForm\nfrom website.sparql_query import SparqlQuery\nfrom website.tco.tco_calculator import CalculadoraTco\n\n\nclass Pesquisa(FormView):\n template_name = 'index.html'\n form_class = PesquisaForm\n\n def form_valid(self, form):\n data = form.data\n sparql_query = SparqlQuery()\n ontology = sparql_query.search()\n\n request_body = {\n \"select\": ontology,\n \"labels\": ['cpu', 'hd', 'pricing', 'ram'],\n \"filters\": [],\n \"limit\": 10# data['limit']\n }\n\n if data['cpu'] is not None and data['cpu'] != '':\n request_body['filters'].append(\n # {\"field\": \"cpu\", \"comparator\": data['cpu_filter'], \"value\": int(data['cpu'])}\n {\"field\": \"cpu\", \"comparator\": '>=', \"value\": int(data['cpu'])}\n )\n\n # if data['hd'] is not None and data['hd'] != '':\n # request_body['filters'].append(\n # {\"field\": \"hd\", \"comparator\": data['hd_filter'], \"value\": int(data['hd'])}\n # )\n\n if data['ram'] is not None and data['ram'] != '':\n request_body['filters'].append(\n # {\"field\": \"ram\", \"comparator\": data['ram_filter'], \"value\": int(data['ram'])}\n {\"field\": \"ram\", \"comparator\": '>=', \"value\": int(data['ram'])}\n )\n\n request = requests.post('http://157.230.128.104:8080/', json=request_body)\n machines = request.json()\n\n ''' Adicionar o item que corresponde a maquina fisica '''\n calculadora_tco = CalculadoraTco()\n machines.append(calculadora_tco.calcular(data['ram'], data['hd'], data['cpu']))\n\n return render(self.request, 'listagem.html', {'machines': machines})\n","repo_name":"GeovRodri/tco-multicloud","sub_path":"website/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"25531039518","text":"from decimal import *\n# from ocpp_datatypes import *\n# from ocpp_datatypes_enum import *\nfrom ocpp_datatype_parser import *\nimport status_notification_pb2\nimport authorize_pb2\nimport transaction_event_pb2\n\ngetcontext().prec = 6\n\ndef getEnumValue(enumTypeObj, protobufEnumType):\n return protobufEnumType.Value(enumTypeObj.name)\n\ndef statusNotificationRequest(\n timestamp: str,\n connectorStatus: ConnectorStatusEnumType,\n evseId: int,\n connectorId: int):\n request = status_notification_pb2.StatusNotificationRequest()\n request.timestamp = timestamp\n if connectorStatus in ConnectorStatusEnumType:\n request.connectorStatus = getEnumValue(connectorStatus,\n status_notification_pb2.StatusNotificationRequest.ConnectorStatusEnumType)\n else:\n return -1\n request.evseId = evseId\n request.connectorId = connectorId\n return request\n\ndef statusNotificationResponse():\n response = status_notification_pb2.StatusNotificationResponse()\n return response\n\ndef transactionEventRequest(\n eventType: TransactionEventEnumType,\n timestamp: str,\n triggerReason: TriggerReasonEnumType,\n seqNo: int,\n offline: bool = None,\n numberOfPhasesUsed: int = None,\n cableMaxCurrent: Decimal = None,\n reservationId: int = None,\n transactionData: TransactionType = None, # is required\n idToken: IdTokenType = None,\n evse: EVSEType = None,\n meterValue: MeterValueType = None\n):\n request = transaction_event_pb2.TransactionEventRequest()\n if eventType in TransactionEventEnumType:\n request.eventType = getEnumValue(eventType,\n transaction_event_pb2.TransactionEventRequest.TransactionEventEnumType)\n else:\n return -1\n request.timestamp = timestamp\n if triggerReason in TriggerReasonEnumType:\n request.triggerReason = getEnumValue(triggerReason,\n transaction_event_pb2.TransactionEventRequest.TriggerReasonEnumType)\n else:\n return -1\n request.seqNo = seqNo\n\n if offline != None:\n request.offline = offline\n if numberOfPhasesUsed != None:\n request.numberOfPhasesUsed = numberOfPhasesUsed\n if cableMaxCurrent != None:\n request.cableMaxCurrent = str(cableMaxCurrent)\n if reservationId != None:\n request.reservationId = reservationId\n\n request.transactionData.id = transactionData.id\n if transactionData.chargingState in ChargingStateEnumType:\n request.transactionData.chargingState = getEnumValue(transactionData.chargingState,\n transaction_event_pb2.TransactionEventRequest.TransactionType.ChargingStateEnumType)\n if transactionData.timeSpentCharging != None:\n request.timeSpentCharging = transactionData.timeSpentCharging\n if transactionData.stoppedReason in ReasonEnumType:\n request.transactionData.stoppedReason = getEnumValue(transactionData.stoppedReason,\n transaction_event_pb2.TransactionEventRequest.TransactionType.ReasonEnumType)\n if transactionData.remoteStartId != None:\n request.transactionData.remoteStartId = transactionData.remoteStartId\n\n if idToken != None:\n request.idToken.idToken = idToken.idToken\n request.idToken.type = getEnumValue(idToken.type,\n transaction_event_pb2.TransactionEventRequest.IdTokenType.IdTokenEnumType)\n if idToken.additionalInfo != None:\n request.idToken.additionalInfo = getEnumValue(idToken.additionalInfo,\n transaction_event_pb2.TransactionEventRequest.IdTokenType.AdditionalInfoType)\n\n if evse != None:\n request.evse.id = evse.id\n if evse.connectorId != None:\n request.evse.connectorId = evse.connectorId\n\n if meterValue != None:\n request.meterValue.timestamp = meterValue.timestamp\n request.meterValue.sampledValue.value = str(meterValue.sampledValue.value)\n if meterValue.sampledValue.context in ReasonEnumType:\n request.meterValue.sampledValue.context = getEnumValue(meterValue.sampledValue.context,\n transaction_event_pb2.TransactionEventRequest.MeterValueType.SampledValueType.ReadingContextEnumType)\n if meterValue.sampledValue.measurand in MeasurandEnumType:\n request.meterValue.sampledValue.measurand = getEnumValue(meterValue.sampledValue.measurand,\n transaction_event_pb2.TransactionEventRequest.MeterValueType.SampledValueType.MeasurandEnumType)\n if meterValue.sampledValue.phase in PhaseEnumType:\n request.meterValue.sampledValue.phase = getEnumValue(meterValue.sampledValue.phase,\n transaction_event_pb2.TransactionEventRequest.MeterValueType.SampledValueType.PhaseEnumType)\n if meterValue.sampledValue.location in LocationEnumType:\n request.meterValue.sampledValue.location = getEnumValue(meterValue.sampledValue.location,\n transaction_event_pb2.TransactionEventRequest.MeterValueType.SampledValueType.LocationEnumType)\n if meterValue.sampledValue.signedMeterValue != None:\n request.meterValue.sampledValue.signedMeterValue.meterValueSignature = meterValue.sampledValue.signedMeterValue.meterValueSignature\n request.meterValue.sampledValue.signedMeterValue.signatureMethod = getEnumValue(meterValue.sampledValue.signedMeterValue.signatureMethod,\n transaction_event_pb2.TransactionEventRequest.MeterValueType.SampledValueType.SignedMeterValueType.SignatureMethodEnumType)\n request.meterValue.sampledValue.signedMeterValue.encodingMethod = getEnumValue(meterValue.sampledValue.signedMeterValue.encodingMethod,\n transaction_event_pb2.TransactionEventRequest.MeterValueType.SampledValueType.SignedMeterValueType.EncodingMethodEnumType)\n request.meterValue.sampledValue.signedMeterValue.encodedMeterValue = meterValue.sampledValue.signedMeterValue.encodedMeterValue\n if meterValue.sampledValue.unitOfMeasure != None:\n if meterValue.sampledValue.unitOfMeasure.unit != None:\n request.meterValue.sampledValue.unitOfMeasure.unit = meterValue.sampledValue.unitOfMeasure.unit\n if meterValue.sampledValue.unitOfMeasure.multiplier != None:\n request.meterValue.sampledValue.unitOfMeasure.multiplier = meterValue.sampledValue.unitOfMeasure.multiplier\n\n return request\n\ndef transactionEventResponse(\n totalCost: Decimal = None,\n chargingPriority: int = None,\n idTokenInfo: IdTokenInfoType = None,\n updatedPersonalMessage: MessageContentType = None\n):\n response = transaction_event_pb2.TransactionEventResponse()\n if totalCost != None:\n response.totalCost = str(totalCost)\n\n if chargingPriority != None:\n response.chargingPriority = chargingPriority\n\n if idTokenInfo != None:\n if idTokenInfo.status in AuthorizationStatusEnumType:\n response.idTokenInfo.status = getEnumValue(idTokenInfo.status,\n transaction_event_pb2.TransactionEventResponse.IdTokenInfoType.AuthorizationStatusEnumType)\n else:\n return -1\n if idTokenInfo.cacheExpiryDateTime != None:\n response.idTokenInfo.cacheExpiryDateTime = idTokenInfo.cacheExpiryDateTime\n if idTokenInfo.chargingPriority != None:\n response.idTokenInfo.chargingPriority = idTokenInfo.chargingPriority\n if idTokenInfo.language1 != None:\n response.idTokenInfo.language1 = idTokenInfo.language1\n if idTokenInfo.language2 != None:\n response.idTokenInfo.language2 = idTokenInfo.language2\n if idTokenInfo.groupIdToken != None:\n response.idTokenInfo.groupIdToken.idToken = idTokenInfo.groupIdToken.idToken\n response.idTokenInfo.groupIdToken.type = getEnumValue(idTokenInfo.groupIdToken.type,\n transaction_event_pb2.TransactionEventResponse.IdTokenInfoType.GroupIdTokenType.IdTokenEnumType)\n if idTokenInfo.personalMessage != None:\n response.idTokenInfo.personalMessage.format = getEnumValue(idTokenInfo.personalMessage.format,\n transaction_event_pb2.TransactionEventResponse.IdTokenInfo.MessageContentType.MessageFormatEnumType)\n if idTokenInfo.personalMessage.language != None:\n response.idTokenInfo.personalMessage.language = idTokenInfo.personalMessage.language\n response.idTokenInfo.personalMessage.content = idTokenInfo.personalMessage.content\n\n if updatedPersonalMessage != None:\n response.updatedPersonalMessage.format = getEnumValue(updatedPersonalMessage.format,\n transaction_event_pb2.TransactionEventResponse.MessageContentType.MessageFormatEnumType)\n if updatedPersonalMessage.language != None:\n response.updatedPersonalMessage.language = updatedPersonalMessage.language\n response.updatedPersonalMessage.content = updatedPersonalMessage.content\n\n return response\n\ndef authorizeRequest(\n evseId: int = None,\n idToken: IdTokenType = None, # idToken is required\n _15118CertificateHashData: OCSPRequestDataType = None\n):\n request = authorize_pb2.AuthorizeRequest()\n\n if evseId != None:\n request.evseId = evseId\n\n request.idToken.idToken = idToken.idToken\n if idToken.type in IdTokenEnumType:\n request.idToken.type = getEnumValue(idToken.type,\n authorize_pb2.AuthorizeRequest.IdTokenType.IdTokenEnumType)\n else:\n return -1\n\n if idToken.additionalInfo != None:\n request.idToken.additionalInfo.additionalIdToken = idToken.additionalInfo.additionalIdToken\n request.idToken.additionalInfo.type = idToken.additionalInfo.type\n\n if _15118CertificateHashData != None:\n if _15118CertificateHashData.hashAlgorithm in HashAlgorithmEnumType:\n request._15118CertificateHashData.hashAlgorithm = getEnumValue(_15118CertificateHashData.hashAlgorithm,\n authorize_pb2.AuthorizeRequest.OCSPRequestDataType.HashAlgorithmEnumType)\n else:\n return -1\n request._15118CertificateHashData.issuerNameHash = _15118CertificateHashData.issuerNameHash\n request._15118CertificateHashData.issuerKeyHash = _15118CertificateHashData.issuerKeyHash\n request._15118CertificateHashData.serialNumber = _15118CertificateHashData.serialNumber\n if _15118CertificateHashData.responderURL != None:\n request._15118CertificateHashData.responderURL = _15118CertificateHashData.responderURL\n\n return request\n\ndef authorizeResponse(\n certificateStatus: CertificateStatusEnumType = None,\n evseId: int = None,\n idTokenInfo: IdTokenInfoType = None # idTokenInfo is required\n):\n response = authorize_pb2.AuthorizeResponse()\n\n if certificateStatus != None:\n response.certificateStatus = getEnumValue(certificateStatus,\n authorize_pb2.AuthorizeResponse.CertificateStatusEnumType)\n\n if evseId != None:\n response.evseId = evseId\n\n if idTokenInfo.status in AuthorizationStatusEnumType:\n response.idTokenInfo.status = getEnumValue(idTokenInfo.status,\n authorize_pb2.AuthorizeResponse.IdTokenInfoType.AuthorizationStatusEnumType)\n else:\n return -1\n if idTokenInfo.cacheExpiryDateTime != None:\n response.idTokenInfo.cacheExpiryDateTime = idTokenInfo.cacheExpiryDateTime\n if idTokenInfo.chargingPriority != None:\n response.idTokenInfo.chargingPriority = idTokenInfo.chargingPriority\n if idTokenInfo.language1 != None:\n response.idTokenInfo.language1 = idTokenInfo.language1\n if idTokenInfo.language2 != None:\n response.idTokenInfo.language2 = idTokenInfo.language2\n if idTokenInfo.groupIdToken != None:\n response.idTokenInfo.groupIdToken.idToken = idTokenInfo.groupIdToken.idToken\n response.idTokenInfo.groupIdToken.type = getEnumValue(idTokenInfo.groupIdToken.type,\n authorize_pb2.AuthorizeResponse.IdTokenInfoType.GroupIdTokenType.IdTokenEnumType)\n if idTokenInfo.personalMessage != None:\n response.idTokenInfo.personalMessage.format = getEnumValue(idTokenInfo.personalMessage.format,\n authorize_pb2.AuthorizeResponse.IdTokenInfo.MessageContentType.MessageFormatEnumType)\n if idTokenInfo.personalMessage.language != None:\n response.idTokenInfo.personalMessage.language = idTokenInfo.personalMessage.language\n response.idTokenInfo.personalMessage.content = idTokenInfo.personalMessage.content\n\n return response","repo_name":"TovarichMFS/EEA_Charging_Station","sub_path":"ocpp_messages.py","file_name":"ocpp_messages.py","file_ext":"py","file_size_in_byte":12872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"24000087893","text":"import pandas as pd\n\nprint(\"-- Start Data Aggregation \")\n\nSTOCKS = [\"ABEA.BE\",\"BMW.DE\",\"BAS.DE\",'AAPL','AIR.DE','TSLA',\"BAYN.DE\",'TSS',\"ALV.DE\",\"VIV\",'005930.KS']\nstock_names = {\"ABEA.BE\":\"Google\",\"TSS\":\"Total\",\"AIR.DE\":\"Airbus\",\"BMW.DE\":\"BMW\",\"BAS.DE\":\"BASF\",\"AAPL\":\"Apple\",\"TSLA\":\"Tesla\",\"BAYN.DE\":\"Bayer\",\"ALV.DE\":\"Allianz\",\"VIV\":\"Telefonica\",\"005930.KS\":\"Samsung\"}\n\n\n\ni = 0\nfor id in STOCKS:\n company = stock_names[id]\n PATH = \"data/\" + company + \".csv\"\n df = pd.read_csv(PATH,sep=\",\",index_col=0)\n print(\"-- Stock Time Range\", company , \"From\", df['Timestamp'].min(), \" to \" , df['Timestamp'].max())\n\n if i==0:\n database = df\n i = 1\n else:\n database = pd.merge(df,database,on=\"Timestamp\")\n\n print(\"-- Database Time Range\",\"From\", database['Timestamp'].min(), \" to \" , database['Timestamp'].max())\n\ndatabase.to_csv(\"data/aggregated_returns.csv\", sep=\",\", header=True)\n\nprint(\"-- End Data Aggregation \")\n","repo_name":"kosnil/kd-seminar","sub_path":"finance_data/finance_data_aggregation.py","file_name":"finance_data_aggregation.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"13230990306","text":"#################\n #\n # This file is part of\n # ToBaCCo - Topologically-Based Crystal Constructor\n #\n # Copyright 2017 Yamil J. Colon \n # Diego Gomez-Gualdron \n # Ben Bucior \n #\n # ToBaCCo is free software: you can redistribute it and/or modify\n # it under the terms of the GNU Lesser 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 # ToBaCCo 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 #################\nimport os\nimport numpy as np\nimport re \nimport fnmatch \nimport itertools \nfrom neighbors import neighbor_edges, neighbor_vertices\nfrom nodes import __node_properties\nfrom transformations import superimposition_matrix\nfrom operator import itemgetter\nimport sys\nimport contextlib\nimport collections\n\n\n#Placing node.\n\n\ndef __place_bb(arg, unit_cell, edge_coord, vertex_coord, edge_neighbor_vertex):\n\tnode = __node_properties(arg)\n\tnp.set_printoptions(threshold=sys.maxint)\n\tconnect_site = node[0]\n\tdistance_connection_site = node[1]\n\tangle_connection_site_pair = node[2]\n\tconnectivity = node[3]\n\telements = node[4]\n\telement_coord = node[5]\n\t\n\t\n\t\n\t\n\t\n\t\n\tbb_elements=[]\n\tbb_frac_coordinates=[]\n\tbb_connectivity=[]\n\tfor j in range(len(vertex_coord)):\n\t\t\n\t\tif len(elements)==1: ### Special case when node building block is a single atom\n\t\t\tbb_elements.append(elements)\n\t\t\tbb_frac_coordinates.append(vertex_coord[j])\n\t\t\tcontinue\n\t\tedge_vector =[]\n\t\t\n\t\t##Get coordinates of neighboring edges to find connection vectors\n\t\tfor i in range(len(edge_neighbor_vertex[j])):\n\t\t\tedge_vector.append(edge_coord[edge_neighbor_vertex[j][i]])\n\t\t\n\t\tedge_vector=np.asarray(edge_vector) # fract. coord. of neigboring edges\n\t\t\n\t\t\n\t\t\n\t\tnode_vector=[]\n\t\tfor i in range(len(edge_vector)):\n\t\t\tdiffa = edge_vector[i][0]-vertex_coord[j][0] \n\t\t\tdiffb = edge_vector[i][1]-vertex_coord[j][1] \n\t\t\tdiffc = edge_vector[i][2]-vertex_coord[j][2] \n\t\t\t\n\t\t\t### PERIODIC BOUNDARY CONDITIONS\n\t\t\tif diffa > 0.5:\n\t\t\t\tedge_vector[i][0] = edge_vector[i][0] - 1\n\t\t\telif diffa < -0.5:\n\t\t\t\tedge_vector[i][0] = edge_vector[i][0] + 1\n\t\t\t\n\t\t\tif diffb > 0.5:\n\t\t\t\tedge_vector[i][1] = edge_vector[i][1] - 1\n\t\t\telif diffb < -0.5:\n\t\t\t\tedge_vector[i][1] = edge_vector[i][1] + 1\n\t\t\t\n\t\t\tif diffc > 0.5:\n\t\t\t\tedge_vector[i][2] = edge_vector[i][2] - 1\n\t\t\telif diffc < -0.5:\n\t\t\t\tedge_vector[i][2] = edge_vector[i][2] + 1\n\t\t\t\n\t\t\t\n\t\t\tnode_vector.append(edge_vector[i] - vertex_coord[j])\n\t\t\n\t\tnode_vector =np.asarray(node_vector) ## fract vectors from node to edge adjusted for PBCs\n\t\t\n\t\tnode_vector_real=[]\n\t\tfor i in range(len(node_vector)):\n\t\t\tvector_real = np.dot(np.transpose(unit_cell), node_vector[i])\n\t\t\tnode_vector_real.append(vector_real)\n\t\t\n\t\t\t\n\t\t\n\t\tnode_vector_real = np.asarray(node_vector_real) # real (not fractional) coord vector of network\n\t\t\n\t\tnode_coord_real = np.dot(np.transpose(unit_cell), vertex_coord[j]) # real coord of network node (centroid of node)\n\t\tnorm_node_vector_real=[]\n\t\tfor i in range(len(node_vector_real)):\n\t\t\tnorm = node_vector_real[i]/np.linalg.norm(node_vector_real[i])\n\t\t\tnorm_node_vector_real.append(norm)\n\t\t\n\t\tnorm_node_vector_real = np.asarray(norm_node_vector_real) # normalized network vectors\n\t\t\n\t\t\n\t\tconnect_node=[]\n\t\tconnection_node=[]\n\t\tfor i in range(len(norm_node_vector_real)):\n\t\t\tconnect = norm_node_vector_real[i]*distance_connection_site[i]\n\t\t\tconnect_node.append(connect)\n\t\t\tconnection_node.append(connect)\n\t\t\n\t\t\n\t\t\n\t\tconnection_node=np.asarray(connection_node) ## coordinates to where node connection sites should be placed\n\t\t\n\t\tconnection_site = []\n\t\tfor i in range(len(connect_site)):\n\t\t\tconnection_site.append(connect_site[i])\n\t\tconnection_site = np.asarray(connection_site)\n\t\t\n\t\t\n\t\t### To deal with nodes with ONLY two connections.\n\t\tif len(connection_site)==2:\n\t\t\tbi_connection_site=[]\n\t\t\tbi_connection_node=[]\n\t\t\t#test_vector=[0, 0, 0]\n\t\t\tfor i in range(len(connection_site)):\n\t\t\t\tbi_connection_site.append(connection_site[i])\n\t\t\t\tbi_connection_node.append(connection_node[i])\n\t\t\t#bi_connection_site.append(-connection_site[0])\n\t\t\t#bi_connection_site.append(-connection_site[1])\n\t\t\t#bi_connection_node.append(-connection_node[0])\n\t\t\t#bi_connection_node.append(-connection_node[1])\n\t\t\tbi_connection_site.append(np.cross(connection_site[0], connection_site[1]))\n\t\t\tbi_connection_site.append(np.cross(connection_site[1], connection_site[0]))\n\t\t\tbi_connection_node.append(np.cross(connection_node[1], connection_node[0]))\n\t\t\tbi_connection_node.append(np.cross(connection_node[0], connection_node[1]))\n\t\t\t#bi_connection_site.append(test_vector)\n\t\t\t#bi_connection_node.append(test_vector)\n\t\t\tconnection_site=np.asarray(bi_connection_site)\n\t\t\tconnection_node=np.asarray(bi_connection_node)\n\t\t\t#print \"again\", connection_site, len(connection_site)\n\t\t\t#print connection_node\n\t\t\n\t\t### To deal with *bct* topologies\n\t\tif len(connection_site)==10:\n\t\t\tangle_site_sum=[]\n\t\t\tangle_node_sum=[]\n\t\t\tdistance_site_sum=[]\n\t\t\tdistance_node_sum=[]\n\t\t\tfor i in range(len(connection_site)):\n\t\t\t\tangle_site=[]\n\t\t\t\tangle_node=[]\n\t\t\t\tdistance_site=[]\n\t\t\t\tdistance_node=[]\n\t\t\t\tfor k in range(len(connection_site)):\n\t\t\t\t\tangle_s=np.arccos(np.dot(connection_site[i], connection_site[k])/(np.linalg.norm(connection_site[i])*np.linalg.norm(connection_site[k])))*180/np.pi\n\t\t\t\t\tangle_n=np.arccos(np.dot(connection_node[i], connection_node[k])/(np.linalg.norm(connection_node[i])*np.linalg.norm(connection_node[k])))*180/np.pi\n\t\t\t\t\tdist_s = np.linalg.norm(connection_site[i] - connection_site[k])\n\t\t\t\t\tdist_n = np.linalg.norm(connection_node[i] - connection_node[k])\n\t\t\t\t\t\n\t\t\t\t\tif np.isnan(angle_s)==True:\n\t\t\t\t\t\tangle_s=np.arccos(round(np.dot(connection_site[i], connection_site[k])/(np.linalg.norm(connection_site[i])*np.linalg.norm(connection_site[k]))))*180/np.pi\n\t\t\t\t\tif np.isnan(angle_n)==True:\n\t\t\t\t\t\tangle_n=np.arccos(round(np.dot(connection_node[i], connection_node[k])/(np.linalg.norm(connection_node[i])*np.linalg.norm(connection_node[k]))))*180/np.pi\n\t\t\t\t\tangle_site.append(angle_s)\n\t\t\t\t\tangle_node.append(angle_n)\n\t\t\t\t\tdistance_site.append(dist_s)\n\t\t\t\t\tdistance_node.append(dist_n)\n\t\t\t\t\tcounter_site = collections.Counter(np.around(distance_site,1))\n\t\t\t\t\tcounter_node = collections.Counter(np.around(distance_node,1))\n\t\t\t\tangle_site_sum.append(sum(angle_site))\n\t\t\t\tangle_node_sum.append(sum(angle_node))\n\t\t\t\tdistance_site_sum.append(sum(distance_site))\n\t\t\t\tdistance_node_sum.append(sum(distance_node))\n\t\t\tlocation_dist_site=[]\n\t\t\tlocation_dist_node=[]\n\t\t\tindex_dist_site = min(enumerate(distance_site_sum), key=itemgetter(1))[0]\n\t\t\tindex_dist_node = min(enumerate(distance_node_sum), key=itemgetter(1))[0]\n\t\t\tlocation_dist_site.append(index_dist_site)\n\t\t\tlocation_dist_node.append(index_dist_node)\n\t\t\tdistance_site_sum[index_dist_site]=1000\n\t\t\tdistance_node_sum[index_dist_node]=1000\n\t\t\tindex_dist_site = min(enumerate(distance_site_sum), key=itemgetter(1))[0]\n\t\t\tindex_dist_node = min(enumerate(distance_node_sum), key=itemgetter(1))[0]\n\t\t\tlocation_dist_site.append(index_dist_site)\n\t\t\tlocation_dist_node.append(index_dist_node)\n\t\t\tlocation_dist_site = np.sort(location_dist_site)\n\t\t\tlocation_dist_node = np.sort(location_dist_node)\n\t\t\t\n\t\t\t\n\t\t\tindex_site = max(enumerate(angle_site_sum), key=itemgetter(1))[0]\n\t\t\tangle_site_sum[index_site]=0\n\t\t\tindex_site_1 = max(enumerate(angle_site_sum), key=itemgetter(1))[0]\n\t\t\tindex_node = max(enumerate(angle_node_sum), key=itemgetter(1))[0]\n\t\t\tangle_node_sum[index_node]=0\n\t\t\tindex_node_1 = max(enumerate(angle_node_sum), key=itemgetter(1))[0]\n\t\t\tdist_site =[]\n\t\t\tdist_node=[]\n\t\t\t\n\t\t\tlocation_add_site=[]\n\t\t\tlocation_add_node=[]\n\t\t\tfor i in range(len(connection_site)):\n\t\t\t\tdist_site.append(np.linalg.norm(connection_site[location_dist_site[0]] - connection_site[i]))\n\t\t\t\tdist_node.append(np.linalg.norm(connection_node[location_dist_node[0]] - connection_node[i]))\n\t\t\tcounter_site = collections.Counter(np.around(dist_site,0))\n\t\t\tcounter_node = collections.Counter(np.around(dist_node,0))\n\t\t\t\n\t\t\t\n\t\t\tsite_criterion = counter_site.most_common(1)[0][0]\n\t\t\t\n\t\t\tif site_criterion == counter_node.most_common(1)[0][0]:\n\t\t\t\tnode_criterion = counter_node.most_common(1)[0][0]\n\t\t\telse:\n\t\t\t\tnode_criterion = counter_node.most_common(2)[1][0]\n\t\t\t\n\t\t\tfor i in range(len(dist_site)):\n\t\t\t\tif np.around(dist_site[i],0) == site_criterion:\n\t\t\t\t\tlocation_add_site.append(i)\n\t\t\t\tif np.around(dist_node[i],0) == node_criterion:\n\t\t\t\t\tlocation_add_node.append(i)\n\n\t\t\tconnection_site = [connection_site[location_dist_site[1]], connection_site[location_dist_site[0]], connection_site[location_add_site[0]], connection_site[location_add_site[1]], connection_site[location_add_site[2]], connection_site[location_add_site[3]]]\n\t\t\tconnection_node = [connection_node[location_dist_node[1]], connection_node[location_dist_node[0]], connection_node[location_add_node[0]], connection_node[location_add_node[1]], connection_node[location_add_node[2]], connection_node[location_add_node[3]]]\n\n\n\t\t\n\t\t\n\t\t\n\t\t## This part of the code orders vectors and then takes the ratio to find opposite vectors and, if they exist, perpendiculars.\n\t\t## This is to deal with topologies with have nodes with more than 8 connection sites.\n\t\tlist_a = []\n\t\tlist_a_1 =[]\n\t\tfor i in range(len(connection_site)):\n\t\t\tlist_a.append(np.dot(connection_site[0], connection_site[i]))\n\t\t\tlist_a_1.append(np.dot(connection_site[1], connection_site[i]))\n\t\t\n\t\tlist_a = np.asarray(list_a)\n\t\tlist_a_1 = np.asarray(list_a_1)\n\t\tlist_b = []\n\t\tlist_b_1 =[]\n\t\tfor i in range(len(connection_node)):\n\t\t\tlist_b.append(np.dot(connection_node[0], connection_node[i]))\n\t\t\tlist_b_1.append(np.dot(connection_node[1], connection_node[i]))\n\t\t\t\n\t\tlist_b = np.asarray(list_b)\n\t\tlist_b_1 = np.asarray(list_b_1)\n\t\t\n\t\t\n\t\tsigma = np.sort(list_a)\n\t\tsigma_1 = np.sort(list_a_1)\n\t\ttau = np.sort(list_b)\n\t\ttau_1 = np.sort(list_b_1)\n\n\t\tsorted_a = np.argsort(list_a)\n\t\tsorted_a_1 = np.argsort(list_a_1)\n\t\tsorted_b = np.argsort(list_b)\n\t\tsorted_b_1 = np.argsort(list_b_1)\n\t\t\n\t\t\n\t\tinner_distance_site = []\n\t\tfor i in range(len(connection_site)):\n\t\t\tinner_distance_site.append(np.linalg.norm(connection_site[i]-connection_site[0]))\n\t\t\t\n\t\t\t\n\t\t\n\t\t\n\t\tsorted_sites = []\n\t\tsorted_sites_1 =[]\n\t\tsorted_nodes_1 =[]\n\t\tfor i in range(len(connection_site)):\n\t\t\tsorted_sites.append(connection_site[i])\n\t\t\tsorted_sites_1.append(connection_site[i])\n\t\t\tsorted_nodes_1.append(connection_node[i])\n\t\t\t\n\t\tsorted_sites = np.asarray(sorted_sites)\n\t\tsorted_sites_1 = np.asarray(sorted_sites_1)\n\t\tsorted_nodes_1 = np.asarray(sorted_nodes_1)\n\t\t\n\t\tfor i in range(len(sorted_sites)):\n\t\t\tsorted_sites[sorted_b[i]]=connection_site[sorted_a[i]]\n\t\t\tsorted_sites_1[sorted_b_1[i]] = connection_site[sorted_a_1[i]]\n\t\t\tsorted_nodes_1[sorted_a_1[i]] = connection_node[sorted_b_1[i]]\n\t\t\n\t\tconnection_site = sorted_sites\n\t\t\n\t\tinner_dot_site_sorted=[]\n\t\tinner_dot_site_sorted_1 = []\n\t\tinner_dot_node_sorted=[]\n\t\tinner_dot_node_sorted_1=[]\n\t\t\n\t\tfor i in range(len(sorted_sites)):\n\t\t\tinner_dot_site_sorted.append(np.dot(sorted_sites[0], sorted_sites[i]))\n\t\t\tinner_dot_node_sorted.append(np.dot(connection_node[0], connection_node[i]))\n\t\t\tinner_dot_site_sorted_1.append(np.dot(sorted_sites_1[1], sorted_sites_1[i]))\n\t\t\tinner_dot_node_sorted_1.append(np.dot(connection_node[1], connection_node[i]))\n\n\t\tratio_sorted = np.divide(inner_dot_site_sorted, inner_dot_node_sorted)\n\t\tratio_sorted_1 = np.divide(inner_dot_site_sorted_1, inner_dot_node_sorted_1)\n\n\t\tlocation_sorted=[]\n\t\tlocation_sorted_1=[]\n\t\tfor i in range(len(ratio_sorted)):\n\t\t\tif round(ratio_sorted[i],2)==1:\n\t\t\t\tlocation_sorted.append(i)\n\t\t\tif round(ratio_sorted_1[i],2)==1:\n\t\t\t\tlocation_sorted_1.append(i)\n\t\tif len(connection_node)>8 and len(connection_node)<24:\n\t\t\tlocation_sortednan=[]\n\t\t\tlocation_sortednan_1=[]\n\t\t\tfor i in range(len(ratio_sorted)):\n\t\t\t\tif np.isnan(ratio_sorted[i])==True or round(ratio_sorted[i],2)==0:\n\t\t\t\t\tlocation_sortednan.append(i)\n\t\t\t\tif np.isnan(ratio_sorted_1[i])==True:\n\t\t\t\t\tlocation_sortednan_1.append(i)\n\t\t\n\t\tif len(location_sorted)==1:\n\t\t\tlocation_sorted=[]\n\t\t\tlocation_sorted.append(0)\n\t\t\tdifference = []\n\t\t\tfor i in range(1, len(ratio_sorted)):\n\t\t\t\tif ratio_sorted[i] < 1:\n\t\t\t\t\tdifference.append(10000)\n\t\t\t\telif ratio_sorted[i] >1:\n\t\t\t\t\tdifference.append(abs(1 - ratio_sorted[i]))\n\t\t\tindex_ratio = min(enumerate(difference), key=itemgetter(1))[0]\n\t\t\tlocation_sorted.append(index_ratio +1)\n\n\t\ttfflag=0\n\n\t\tif len(connection_node)>10 and len(connection_node)<24: ## to deal with fcu and ftw\n\t\t\tif len(location_sortednan)<2:\n\t\t\t\tconnection_node_spec = [connection_node[location_sorted[0]], connection_node[location_sorted[1]], np.cross(connection_node[location_sorted[0]], connection_node[location_sorted[1]])]\n\t\t\t\tconnection_site_spec = [sorted_sites[location_sorted[0]], sorted_sites[location_sorted[1]], np.cross(sorted_sites[location_sorted[0]], sorted_sites[location_sorted[1]])]\n\t\t\telif len(location_sortednan)>=2:\n\t\t\t\tconnection_node_spec = [connection_node[location_sorted[0]], connection_node[location_sorted[1]], connection_node[location_sortednan[0]], connection_node[location_sortednan[1]]]\n\t\t\t\tconnection_site_spec = [sorted_sites[location_sorted[0]], sorted_sites[location_sorted[1]], sorted_sites[location_sortednan[0]], sorted_sites[location_sortednan[1]]]\n\t\t\t\t\n\t\t\t\n\t\t\tconnection_node_spec = np.asarray(connection_node_spec, dtype=np.float64)\n\t\t\tconnection_site_spec = np.asarray(connection_site_spec, dtype=np.float64)\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\ttfflag=1\n\t\t\n\t\tif len(connection_node)>12: ## to deal with rht\n\t\t\tconnection_node = [connection_node[location_sorted[0]], connection_node[location_sorted[1]], connection_node[location_sorted_1[0]], connection_node[location_sorted_1[1]]]\n\t\t\tconnection_site = [sorted_sites[location_sorted[0]], sorted_sites[location_sorted[1]], sorted_sites_1[location_sorted_1[0]], sorted_sites_1[location_sorted_1[1]]]\n\t\t\t\n\t\tif tfflag==0:## if number of connection points in topology is 8 or less, except *bct*. \n\t\t\tperm = np.asarray(list(itertools.permutations(connection_site)))#permutations of connection sites\n\t\t\t\n\t\t\t\n\t\t\tnode_site_distance=[]\n\t\t\tfor i in range(len(perm)):\n\t\t\t\ttrans_matrix = superimposition_matrix(np.transpose(perm[i]), np.transpose(connection_node), usesvd=False)\n\t\t\t\tperm_plus_one = np.append(perm[i], np.ones([len(perm[i]),1]),1)\n\t\t\t\ttrial_sites=[]\n\t\t\t\tfor k in range(len(perm_plus_one)):\n\t\t\t\t\ttest_sites=np.dot(trans_matrix, perm_plus_one[k])\n\t\t\t\t\ttrial_sites.append(test_sites)\n\t\t\t\tperm_sites = np.asarray(trial_sites)\n\t\t\t\tperm_sites = perm_sites[:, :-1]\n\t\t\t\tsite_distance=[]\n\t\t\t\tfor k in range(len(perm_sites)):\n\t\t\t\t\tsite_distance.append(np.linalg.norm(perm_sites[k]-connection_node[k]))\n\t\t\t\tnode_site_distance.append(sum(site_distance))\n\t\t\t\t#if node_site_distance[i] < 1:\n\t\t\t\t\t#break\n\t\t\t\n\t\t\tindex_perm = min(enumerate(node_site_distance), key=itemgetter(1))[0]#pick permutation that fits best\n\t\telif tfflag==1:# if connection points in topology is more than 8, except *bct*. Number of connection points has been decreased.\n\t\t\tperm = np.asarray(list(itertools.permutations(connection_site_spec)))\n\t\t\tnode_site_distance=[]\n\t\t\tfor i in range(len(perm)):\n\t\t\t\ttrans_matrix = superimposition_matrix(np.transpose(perm[i]), np.transpose(connection_node_spec), usesvd=False)\n\t\t\t\tperm_plus_one = np.append(perm[i], np.ones([len(perm[i]),1]),1)\n\t\t\t\ttrial_sites=[]\n\t\t\t\tfor k in range(len(perm_plus_one)):\n\t\t\t\t\ttest_sites=np.dot(trans_matrix, perm_plus_one[k])\n\t\t\t\t\ttrial_sites.append(test_sites)\n\t\t\t\tperm_sites=np.asarray(trial_sites)\n\t\t\t\tperm_sites = perm_sites[:, :-1]\n\t\t\t\tsite_distance=[]\n\t\t\t\tfor k in range(len(perm_sites)):\n\t\t\t\t\tsite_distance.append(np.linalg.norm(perm_sites[k] - connection_node_spec[k]))\n\t\t\t\tnode_site_distance.append(sum(site_distance))\n\t\t\tindex_perm = min(enumerate(node_site_distance), key=itemgetter(1))[0]#pick permutation that fits best\n\n\t\tconnection_site = perm[index_perm]\n\t\t\n\t\t#print index_perm\n\t\t##Calculate transformation matrix, using quaternions, to map building block vectors onto network vectors\n\t\tif tfflag==0:\n\t\t\ttfmatrix = superimposition_matrix(np.transpose(connection_site), np.transpose(connection_node), usesvd=False)\n\t\telif tfflag==1:\n\t\t\ttfmatrix = superimposition_matrix(np.transpose(connection_site), np.transpose(connection_node_spec), usesvd=False)\n\n\t\tconnection_site_plusone = np.append(connection_site, np.ones([len(connection_site),1]),1) # add a column of ones for dimension agreement\n\t\t\n\t\ttf_connection_site =[]\n\t\tfor i in range(len(connection_site)):\n\t\t\tnew_sites = np.dot(tfmatrix, connection_site_plusone[i]) #apply transformation matrix to each building block vector\n\t\t\ttf_connection_site.append(new_sites)\n\t\t\n\t\ttf_connection_site = np.asarray(tf_connection_site) #coordinates of building block connection sites, mapped onto network node sites\n\t\ttf_connection_site = tf_connection_site[:, :-1] #remove the column of ones, to obtain final set of coordinates\n\t\t\n\t\t###Apply transformation matrix to all atoms in building block\n\t\telement_coord_plusone = np.append(element_coord, np.ones([len(element_coord),1]),1)\n\t\t\n\t\ttf_element_coord=[]\n\t\tfor i in range(len(element_coord)):\n\t\t\tnew_element= np.dot(tfmatrix, element_coord_plusone[i])\n\t\t\ttf_element_coord.append(new_element)\n\t\ttf_element_coord = np.asarray(tf_element_coord)\n\t\ttf_element_coord = tf_element_coord[:, :-1]\n\t\t\n\t\t\n\t\ttf_frac_element_coord=[]\n\t\tfor i in range(len(tf_element_coord)):\n\t\t\tfrac_element_coord = np.dot(np.transpose(np.linalg.inv(unit_cell)), tf_element_coord[i])\n\t\t\tfrac_element_coord = frac_element_coord + vertex_coord[j]\n\t\t\ttf_frac_element_coord.append(frac_element_coord)\n\t\t\n\t\ttf_frac_element_coord = np.asarray(tf_frac_element_coord) #building block after transformation, in frac coords\n\t\t\n\t\tbb_elements.append(elements)\n\t\tbb_frac_coordinates.append(tf_frac_element_coord)\n\t\tbb_connectivity.append(connectivity)\n\tbb_elements = np.asarray(bb_elements)\n\tbb_frac_coordinates = np.asarray(bb_frac_coordinates)\n\tbb_connectivity=np.asarray(bb_connectivity)\n\treturn bb_elements, bb_frac_coordinates, bb_connectivity\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"tobacco-mofs/tobacco_1.0","sub_path":"placing_bb_func.py","file_name":"placing_bb_func.py","file_ext":"py","file_size_in_byte":18197,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"77"}
+{"seq_id":"31915886379","text":"\"\"\"\nModule for bilateral filtering and related ideas.\n\n* Right now, only bilateral averaging is implemented.\n* Should I have _zscores_standard and _zscores_percentile?\n\"\"\"\n\nimport numpy as np\n\nfrom . import misc\n\n\n# ------------------------------\n\ndef _zscores(y, plow=25, phigh=75, positive_only=False):\n \"\"\"\n Given a data vector, return percentile-based Z magnitudes. Optionally\n given negative values 0 weight.\n \"\"\"\n\n if y.shape[0] <= 1:\n return 0.\n\n if positive_only:\n ypos = y[y > 0]\n if ypos.shape[0] <= 1:\n return 0.\n median = np.median(ypos)\n variance = misc.ipr(ypos, plow, phigh)\n else:\n median = np.median(y)\n variance = misc.ipr(y, plow, phigh)\n\n if variance == 0.:\n return np.abs(y - median)\n else:\n return np.abs(y - median) / variance\n\n\ndef _gaussian_zweights(z, scale):\n \"\"\"\n Given a vector of Z scores an a Gaussian e-fold scale, return a\n vector of corresponding weights.\n \"\"\"\n\n return np.exp(-z**2 / scale**2)\n\n\ndef _negative_weights(y):\n \"\"\"\n Return a binary weighting vector that is 0 when y <= 0 and 1 otherwise.\n \"\"\"\n\n return (y > 0.).astype(float)\n\n\n# ------------------------------\n\ndef bilateral_weights(y, init_weights=None, zscale=None, positive_only=False):\n \"\"\"\n Given a vector of values, a vector of initial weights (defaulted to 1),\n and a scale for Z weights, return a vector of net bilateral weights with\n unit sum.\n \"\"\"\n\n y = np.atleast_1d(y)\n\n # Set initial weights to 1 if none provided\n if init_weights is None:\n init_weights = np.ones(y.shape[0])\n else:\n init_weights = np.atleast_1d(init_weights)\n w = init_weights\n\n # Weight NaN values by 0\n w *= (~np.isnan(y)).astype(float)\n\n # Z-based weights, if scale given\n if zscale is not None:\n w *= _gaussian_zweights(\n _zscores(y, positive_only=positive_only),\n zscale\n )\n\n # Weight negative data by 0 if requested\n if positive_only:\n w *= _negative_weights(y)\n\n # Return sum-normed weights\n return np.nan_to_num(w / w.sum())\n\n\ndef bilateral_average(y, init_weights=None, zscale=None, positive_only=False):\n \"\"\"\n Return the bilateral average of the given 1D data.\n\n Parameters\n ----------\n y: 1xN array-like\n Input 1D data\n init_weights: 1xN array-like\n Initial weights applied to data; defaults to np.ones(len(y)) if not\n given\n zscale: float\n If not None, the Z scale above which a point gets strong Gaussian\n suppressed; if None, Z weighting is not applied\n positive_only: bool\n If True, negative data is given weight 0\n\n Returns\n -------\n bilateral average: float\n\n Examples\n --------\n >>> y = np.ones(10)\n >>> y[5] = 10\n >>> bilateral_average(y)\n 1.9000000000000004\n >>> np.mean(y)\n 1.8999999999999999\n >>> bilateral_average(y, zscale=3)\n 1.0001234081118899\n\n Notes\n -----\n When init_weights == None, zscale == None, and positive_only=False, this\n function just returns the ordinary mean.\n \"\"\"\n\n yary = np.atleast_1d(y)\n\n return np.dot(\n bilateral_weights(\n yary,\n init_weights=init_weights,\n zscale=zscale,\n positive_only=positive_only\n ),\n yary\n )\n","repo_name":"epfahl/algolib","sub_path":"algolib/filters/bilateral.py","file_name":"bilateral.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"5990841793","text":"import os\nfrom pathlib import Path\n\nfrom nonebot import get_driver, logger\nfrom databases import Database\n\ndriver = get_driver()\n\nos.makedirs(\"data/database/notes\", exist_ok=True)\n__db_exists = (Path(\".\") / \"data\" / \"database\" / \"notes\" / \"notes.sqlite\").is_file()\nsqlite_pool = Database(\"sqlite:///data/database/notes/notes.sqlite\")\n\nddl = \"\"\"\n create table if not exists notes(\n gid int not null ,\n noteID int not null ,\n type varchar(10) not null ,\n matcherContent ntext not null ,\n resp ntext not null ,\n at bool false,\n primary key (gid, noteID)\n );\n create table if not exists mute(\n gid int not null ,\n noteID int not null ,\n primary key (gid, noteID)\n );\n\"\"\"\n\n\n@driver.on_startup\nasync def sqlite_connect():\n await sqlite_pool.connect()\n logger.info(\"成功连接到便签数据库\")\n if not __db_exists:\n for query in ddl.split(\";\"):\n await sqlite_pool.execute(query)\n logger.info(\"成功初始化便签数据库\")\n\n\n@driver.on_shutdown\nasync def sqlite_disconnect():\n await sqlite_pool.disconnect()\n logger.info(\"成功断开与便签数据库的连接\")\n","repo_name":"KoishiMoe/Flandre","sub_path":"src/plugins/notes/sqlite.py","file_name":"sqlite.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"77"}
+{"seq_id":"28999412472","text":"import asyncio\r\nfrom xoa_driver import (\r\n testers,\r\n modules,\r\n ports,\r\n utils,\r\n enums,\r\n exceptions\r\n)\r\nfrom xoa_driver.hlfuncs import mgmt\r\nfrom xoa_driver.misc import Hex\r\n\r\n\r\n#---------------------------\r\n# GLOBAL PARAMS\r\n#---------------------------\r\nCHASSIS_IP = \"10.20.1.170\"\r\nUSERNAME = \"XOA\"\r\nMODULE_IDX = 3\r\nPORT_IDX = 0\r\n\r\n#---------------------------\r\n# thor_ppm_anlt_eth\r\n#---------------------------\r\nasync def capture_example_func(stop_event: asyncio.Event):\r\n # create tester instance and establish connection\r\n async with testers.L23Tester(CHASSIS_IP, USERNAME) as tester:\r\n print(f\"{'Connect to chassis:':<20}{CHASSIS_IP}\")\r\n print(f\"{'Username:':<20}{CHASSIS_IP}\")\r\n\r\n # access the module object\r\n module = tester.modules.obtain(MODULE_IDX)\r\n\r\n if isinstance(module, modules.ModuleChimera):\r\n return None\r\n \r\n # access the port object\r\n port = module.ports.obtain(PORT_IDX)\r\n\r\n # reserve the port by force\r\n await mgmt.reserve_port(port=port, force=True)\r\n\r\n # configure capture trigger criteria\r\n await port.capturer.trigger.set(start_criteria=enums.StartTrigger.ON,\r\n start_criteria_filter=0,\r\n stop_criteria=enums.StopTrigger.FULL,\r\n stop_criteria_filter=0)\r\n \r\n # configure packets to keep\r\n await port.capturer.keep.set(kind=enums.PacketType.ALL, index=0, byte_count=-1)\r\n\r\n # start capture\r\n await port.capturer.state.set(on_off=enums.StartOrStop.START)\r\n # await port.capturer.state.set_start() # this is a shortcut func\r\n \r\n # wait a while\r\n # you should make sure your traffic is started during this period\r\n await asyncio.sleep(5)\r\n \r\n # stop capture\r\n await port.capturer.state.set(on_off=enums.StartOrStop.STOP)\r\n # await port.capturer.state.set_stop() # this is a shortcut func\r\n \r\n # check capture status\r\n resp = await port.capturer.stats.get()\r\n print(f\"Capture status: {'running' if resp.status == 0 else 'stopped'}\")\r\n print(f\"Number of captured packets: {resp.packets}\")\r\n\r\n # read captures packets from the buffer and show them one by one\r\n pkts = await port.capturer.obtain_captured()\r\n for i in range(len(pkts)):\r\n resp = await pkts[i].packet.get()\r\n print(f\"Packet content # {i}: {resp.hex_data}\")\r\n\r\n\r\nasync def main():\r\n stop_event = asyncio.Event()\r\n try:\r\n await capture_example_func(stop_event)\r\n except KeyboardInterrupt:\r\n stop_event.set()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n asyncio.run(main())","repo_name":"xenanetworks/open-automation-script-library","sub_path":"packet_capture/packet_capture.py","file_name":"packet_capture.py","file_ext":"py","file_size_in_byte":2783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"69870889849","text":"from extend import array\nimport json\nimport tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import messagebox as msg\nimport configparser\n\nrawConfigPath = \"config.ini\"\n\n## read configuration file and set game properties\nparser = configparser.ConfigParser()\nparser.read(rawConfigPath)\navailable = parser.sections()\ngameatr = parser['GAME']\n\n# set/extract game properties\nCANVAS_ADJUST = 6\nCELL_SPAN = int(gameatr['CELL_SPAN'])\nCELL_SIZE = int(gameatr['CELL_SIZE'])\nCELL_MARGIN = int(gameatr['CELL_MARGIN'])\nGAME_WRAP = True\nWINDOW_TITLE = gameatr['WINDOW_TITLE']\nENDGAME_TITLE = gameatr['ENDGAME_TITLE']\nENDGAME_MESSG = gameatr['ENDGAME_MESSG']\nBOARD_WIDTH = CELL_SPAN*CELL_SIZE - CANVAS_ADJUST\n\nPLAYER_BASE = (0,1,2)\nPLAYER_OTHER = (0,2,1)\nPLAYER_COLOR = eval(gameatr['PLAYER_COLOR'])\nPLAYER_TURN_LBL = gameatr['PLAYER_TURN_LBL']\nCELL_CLOSE = ((0, 1), (0, -1), (1, 0), (1, 1),\n (1, -1), (-1, 0), (-1, 1), (-1, -1))\nCELL_CRAXES = ((0,1),(2,5),(3,7),(4,6))\nG_WINCNT = 2\n\n# set tags\nT_PL = 'player'\nT_GR = 'gridline'\n\n# strip base configurations\nfor i in ('GAME','TYPES'): available.remove(i)\n# extract and process remaining configurations\ntypeset = parser['TYPES']\nDCONFIG = {}\nfor c in available:\n target = DCONFIG[c] = {}\n for a in parser[c]:\n target[a] = eval(typeset[a])(parser[c][a])\n\nclass board:\n\n def __init__(self, cell_span, cell_size,\\\n reference_canvas=None, config=None,\\\n wrap=True):\n self.cellSpan = cell_span\n self.cellSize = cell_size\n self.boardWidth = cell_span*cell_size\n\n self.wrap = wrap\n self.plCnfg = {1:config[\"Player 1\"],2:config[\"Player 2\"]}\n self.grCnfg = config[\"Grid Lines\"]\n\n self.canv = reference_canvas\n self.currentPlayer = 1\n\n # create board as array full of 0 (neutral)\n self.buildGrid()\n\n def buildGrid(self):\n self.grid = array(self.cellSpan, self.cellSpan, build=0)\n\n def switchPlayer(self):\n if self.currentPlayer in (1,2):\n self.currentPlayer = PLAYER_OTHER[self.currentPlayer]\n else: raise ValueError(\"current player value, {} not valid\".\\\n format(self.currentPlayer))\n\n def checkCoord(self, x, y, base='canv'):\n #print(\"checkCoord\",x,y,base)\n if base=='canv': limit = self.boardWidth\n elif base=='grid': limit = self.cellSpan-1\n else: raise ValueError(\"invalid argument for base, {}\".\\\n format(base))\n\n return 0<=x<=limit and 0<=y<=limit\n\n def canvToGrid(self, cx, cy):\n #print(\"canvToGrid\",cx,cy)\n if self.checkCoord(cx, cy, base='canv'):\n return tuple([ i//self.cellSize for i in (cx, cy)])\n else:\n raise ValueError(\"canvas coordinates {} out of bounds\".\\\n format((cx,cy)))\n\n def gridToCanv(self, gx, gy, center=True):\n if self.checkCoord(gx, gy, base='grid'):\n return tuple([ (i+(0.5*int(center)))*self.cellSize\\\n for i in (gx, gy)])\n else:\n raise ValueError(\"grid coordinates {} out of bounds\".\\\n format((cx,cy)))\n \n def getCellPlayer(self, gx, gy):\n player = self.grid[gx,gy]\n if player in PLAYER_BASE:\n return player\n else:\n raise ValueError(\"current player value, {} not valid\".\\\n format(self.player))\n \n def markCell(self, player, gx, gy):\n #print(\"markCell\",player,gx,gy)\n if self.getCellPlayer(gx, gy) == 0:\n #print(\"markCell>\",\"valid play\")\n self.grid[gx,gy] = player\n return True\n else:\n #print(\"markCell>\",\"invalid play\")\n return False\n\n def drawPlay(self, player, gx, gy):\n #print(\"drawPlay\",player,gx,gy)\n # calculate marker radius from cell size and default margin\n r = (self.cellSize//2)-CELL_MARGIN\n # marker center coordinates\n x, y = self.gridToCanv(gx, gy, center=True)\n self.canv.create_oval(x-r,y-r,x+r,y+r,\\\n tags=[T_PL],**self.plCnfg[player])\n\n def drawGrid(self):\n \n #print(\"drawGrid\")\n for n in range(self.cellSize,self.boardWidth,self.cellSize):\n # horizontal lines\n self.canv.create_line(0,n,self.boardWidth,n,\\\n tags=[T_GR],**self.grCnfg)\n # vertical lines\n self.canv.create_line(n,0,n,self.boardWidth,\\\n tags=[T_GR], **self.grCnfg)\n\n def wrapCoord(self, v):\n limit = self.cellSpan-1\n if v<0 or v>limit:\n return max(limit-v, v-limit)-1\n else:\n return v \n\n def getAdjacent(self, gx, gy, wrap=True):\n if wrap: wf = self.wrapCoord\n else: wf = lambda x:x\n \n return [ (wf(gx+dx),wf(gy+dy)) for dx,dy in CELL_CLOSE ]\n \n\n def scoreCell(self, gx, gy, wrap=True):\n if self.getCellPlayer(gx,gy) in (1,2):\n border = [ self.getCellPlayer(x,y) for x,y\\\n in self.getAdjacent(gx,gy,wrap) ]\n\n cellPlayer = self.getCellPlayer(gx, gy)\n cellEnemy = PLAYER_OTHER[cellPlayer]\n\n # check for opposite cells in a single axis with the same\n # state (player entered)\n\n boundCount = 0\n\n for i1, i2 in CELL_CRAXES:\n if border[i1] == cellEnemy and border[i2] == cellEnemy:\n boundCount += 1\n\n if boundCount >= G_WINCNT: return cellEnemy\n return 0\n\n def clearBoard(self):\n #print(\"clearBoard\")\n self.canv.delete(T_PL)\n\n def scoreAllCells(self):\n #print(\"scoreAllCells\")\n pl_current = self.currentPlayer\n pl_enemy = PLAYER_OTHER[pl_current]\n #print(\">\",pl_current,pl_enemy)\n \n cellStates = set()\n # get all possible win scenarios on board into cellStates\n for gx, gy in self.grid.itercoords():\n cellStates.add(self.scoreCell(gx,gy,self.wrap))\n\n #print(\">\",cellStates)\n\n # current player gets first pick on win, otherwise\n # enemy player wins if current player put themselves into\n # a loss scenario\n if pl_current in cellStates: return pl_current\n elif pl_enemy in cellStates: return pl_enemy\n else: return 0\n\n \n def runVictory(self, winner):\n #print(\"runVictory\",winner)\n self.currentPlayer = 0\n msg.showinfo(title=ENDGAME_TITLE,message=ENDGAME_MESSG.format(winner))\n self.currentPlayer = 1\n self.clearBoard()\n self.buildGrid()\n pass\n\n def play(self, cx, cy):\n #print(\">>>>\\n\",\"play\",cx,cy)\n try:\n gx, gy = self.canvToGrid(cx, cy)\n except ValueError:\n return False\n\n #print(\"play>\",gx,gy)\n\n if self.markCell(self.currentPlayer, gx, gy):\n #print(\"play>\",\"cell marked\")\n self.drawPlay(self.currentPlayer, gx, gy)\n #print(\"play>\",\"cell drawn\")\n\n checkWinner = self.scoreAllCells()\n if checkWinner != 0:\n #print(\"play>\",\"victory condition satisfied\")\n self.runVictory(checkWinner)\n else:\n #print(\"play>\",\"no victory, next play\")\n self.switchPlayer()\n \nroot = tk.Tk()\nroot.title(WINDOW_TITLE)\nroot.resizable(0,0)\n\nmain = ttk.Frame(root, relief=tk.SUNKEN,borderwidth=1)\nmain.grid(padx=5,pady=5)\ncanvas = tk.Canvas(main, width=BOARD_WIDTH, height=BOARD_WIDTH)\ncanvas.grid()\n\nvar_turn = tk.StringVar()\nlbl_turn = tk.Label(root, textvariable=var_turn)\nlbl_turn.grid(pady=4)\n\ngame = board(CELL_SPAN, CELL_SIZE, canvas, DCONFIG, GAME_WRAP)\ngame.drawGrid()\n\ndef updateTurn():\n player = game.currentPlayer\n var_turn.set(PLAYER_TURN_LBL.format(player, PLAYER_COLOR[player]))\n\ndef makePlay(event):\n game.play(event.x, event.y)\n updateTurn()\n\ncanvas.bind('', makePlay)\nupdateTurn()\nroot.mainloop()\n","repo_name":"dexgecko/4axisgame","sub_path":"source/playaxis.pyw","file_name":"playaxis.pyw","file_ext":"pyw","file_size_in_byte":8088,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"70961171769","text":"import gym\nimport operator\nimport math\nimport json\nimport sys\nfrom keras.models import Sequential\nfrom keras import optimizers, utils\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport sys\nfrom sklearn.model_selection import train_test_split, KFold, GridSearchCV\nfrom log_reg_network import LogReg\nfrom joblib import dump, load\nfrom network import Network\nimport env.env\nfrom collections import defaultdict\nfrom gym import spaces\nfrom datetime import datetime\n##############################################################################\n#\n#LOAD ENVIRONMENT\n#\nENV_NAME = \"BetEnv-v0\"\n\nenv = gym.make(ENV_NAME)\nnp.random.seed(420)\nenv.seed(420)\nnb_actions = 201 #env.action_space.n #should be 4\n\n###############################################################################\n#\n#LOAD MODEL\n#\n\nMODEL_TYPE = \"NN\"\n\nif len(sys.argv) > 1:\n MODEL_TYPE = sys.argv[1]\n\ncurr_model = None\nif MODEL_TYPE == \"SVM\":\n print(\"LOADING SVM...\")\n curr_model = load(\"svm.joblib\")\nelif MODEL_TYPE == \"LR\":\n print(\"LOADING LR...\")\n lr = LogReg(env.matches.shape[1])\n lr.load_weights(\"weights/lr/batch_run_1/99weights-improvement-100-0.49.hdf5\")\n curr_model = lr\nelif MODEL_TYPE == \"DT\":\n print(\"LOADING DT...\")\n curr_model = load(\"dt.joblib\")\nelif MODEL_TYPE == \"GB\":\n print(\"LOADING GB...\")\n curr_model = load(\"gb.joblib\")\nelif MODEL_TYPE == \"RF\":\n print(\"LOADING RF...\")\n curr_model = load(\"rfc.joblib\")\nelif MODEL_TYPE == \"NB\":\n print(\"LOADING NB...\")\n curr_model = load(\"nb.joblib\")\nelif MODEL_TYPE == \"AB\":\n print(\"LOADING AB...\")\n curr_model = load(\"ab.joblib\")\nelse:\n print(\"LOADING NN...\")\n BetNet = Network(env.matches.shape[1])\n BetNet.load_weights(\"weights/Adadelta/test13_100iter_reglast2/weights-improvement-100-0.52.hdf5\") # Most recent weights\n curr_model = BetNet\n\n###############################################################################\n\n#GETS THE PREDICTION VEC GIVEN MODEL\ndef generatePrediction(mt, curr_model, to_process):\n prediction = None\n if mt == \"SVM\" or mt == \"DT\" or mt == \"GB\" or mt == \"NB\" or mt == \"RF\" or mt==\"AB\":\n temp_pred = curr_model.predict(np.asarray([np.transpose(to_process[0])]))\n hardmax = np.zeros((1,3))\n hardmax[0][temp_pred[0]] = 1\n prediction = tuple(hardmax[0].tolist())\n elif mt == \"LR\":\n net_pred = curr_model.model.predict(np.asarray([np.transpose(to_process[0])]))\n idx = np.argmax(net_pred)\n hardmax = np.zeros_like(net_pred[0])\n hardmax[idx] = 1\n prediction = tuple(hardmax.tolist())\n elif mt == \"DT\":\n temp_pred = curr_model.predict(np.asarray([np.transpose(to_process[0])]))\n hardmax = np.zeros((1, 3))\n hardmax[0][temp_pred[0]] = 1\n prediction = tuple(hardmax[0].tolist())\n else:\n net_pred = curr_model.model.predict(np.asarray([np.transpose(to_process[0])]))\n idx = np.argmax(net_pred)\n hardmax = np.zeros_like(net_pred[0])\n hardmax[idx] = 1\n prediction = tuple(hardmax.tolist())\n #print(prediction)\n return prediction\n\nPREDICT_BET = True\nif len(sys.argv) > 2:\n print(\"PREDICT_BET: \", sys.argv[2])\n PREDICT_BET = bool(sys.argv[2])\n\n\nq_table = defaultdict( lambda: defaultdict(float))\n\nimport random\n# from IPython.display import clear_output\n\n# Hyperparameters\nalpha = 0.1\ngamma = 0.7\nepsilon = 0.4\n\n# For plotting metrics\nall_epochs = []\nall_penalties = []\nstarttime = datetime.now()\nfor i in range(1, 90001):\n state_to_process = env.reset()\n #print(\"RESET\", state_to_process, env.action_space.spaces[1].n)\n epochs, penalties, reward, = 0, 0, 0\n done = False\n\n while not done:\n\n def makeState(to_process):\n prediction = generatePrediction(MODEL_TYPE, curr_model, to_process)\n\n return (prediction, to_process[1])\n\n state = makeState(state_to_process)\n #print(state)\n def getMaxAction(state_for_action):\n newAct = None\n #print(state_for_action, q_table[state_for_action].items())\n for act in max(q_table[state_for_action].items(), key=operator.itemgetter(1)):\n #print(\"max\", act, env.cash)\n #print(act)\n if newAct or type(act) != tuple:\n break\n if act[0] <= env.cash and act[0] > 0:\n newAct = act\n\n if not newAct:\n action = env.action_space.sample()\n if PREDICT_BET:\n #print(action)\n temp_act = [action[0]]\n temp_act.append(np.argmax(np.asarray(state_for_action[0]))) # Explore action space\n newAct = tuple(temp_act)\n #print(action, \"\\n\\n\")\n\n return newAct\n\n def makeAction(state_for_action, rand=True):\n action = None\n #print(q_table[state_for_action])\n if rand:\n if random.uniform(0, 1) < epsilon or not q_table[state_for_action]:\n\n action = env.action_space.sample()\n if PREDICT_BET:\n #print(action)\n temp_act = [action[0]]\n temp_act.append(np.argmax(np.asarray(state_for_action[0])))#Explore action space\n action = tuple(temp_act)\n #print(action, \"\\n\\n\")\n #print(action)\n else:\n action = getMaxAction(state_for_action)\n else:\n if not q_table[state_for_action]:\n action = env.action_space.sample() # Explore action space\n else:\n action = getMaxAction(state_for_action)\n # print(action)\n\n return action\n\n action = makeAction(state)\n\n next_state_to_process, reward, done, info = env.step(action) #STEP\n #print(next_state_to_process, reward, done, info)\n if done: #DONE\n #print(\"DONE\")\n break\n\n old_value = q_table[state][action] #TODO\n next_state = makeState(next_state_to_process)\n next_action = makeAction(next_state, False)\n next_max = q_table[next_state][next_action] #TODO\n\n new_value = (1 - alpha) * old_value + alpha * (reward + gamma * next_max)\n q_table[state][action] = new_value\n\n # if reward == -10:\n # penalties += 1\n\n state_to_process = next_state_to_process\n epochs += 1\n\n if i % 100 == 0:\n #clear_output(wait=True)\n print(f\"Episode: {i}\")\n\nprint(\"Training finished.\\n\")\nprint(\"Time Taken: \", datetime.now()-starttime)\n\nprint(q_table)\nnew_q_table = {}\nfor key in q_table.keys():\n newInner = {}\n for key2 in q_table[key]:\n newInner[str(key2)] = q_table[key][key2]\n new_q_table[str(key)] = newInner\n\n\n#print(q_table)\n#json_str = json.dumps(dict(q_table))\nwith open(\"q_table.json\", 'w') as f:\n json.dump(dict(new_q_table), f, indent=4, separators=(',', ': '))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\"\"\" #THIS IS THE DQN MODEL TO FIGURE OUT LATER\nmemory = SequentialMemory(limit=50000, window_length=1)\npolicy = BoltzmannQPolicy()\ndqn = DQNAgent(model=BetNet.model, nb_actions=nb_actions, memory=memory, nb_steps_warmup=10,\n target_model_update=1e-2, policy=policy)\n\nadadelta = optimizers.Adadelta()\ndqn.compile(optimizer=adadelta, metrics=['accuracy'])\n\ndqn.fit(env, nb_steps=50000, visualize=True, verbose=2)\n\ndqn.save_weights('dqn_{}_weights.h5f'.format(ENV_NAME), overwrite=True)\n\ndqn.test(env, nb_episodes=5, visualize=True)\"\"\"","repo_name":"zsimone10/FIFABets","sub_path":"betRL.py","file_name":"betRL.py","file_ext":"py","file_size_in_byte":7574,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"5137541628","text":"nums = [1,2,3,4,5,6]\nprint(\"Array before rotated\")\nfor i in range(len(nums)):\n print(nums[i],end=\" \")\nprint(\"\\r\")\n\nk = int(input(\"Enter the times have to rotated the array: \"))\ndef rotate(nums, k):\n\n n = len(nums)\n k = k % n\n nums[:] = nums[n-k:] + nums[:n-k]\n return nums\n\nprint(rotate(nums, k))","repo_name":"rishabhrathore055/DSA.","sub_path":"Arrays/arrayRotation.py","file_name":"arrayRotation.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"40946977602","text":"from tkinter import *\n\nwindow = Tk()\n\nwindow.title(\"My First GUI Program in Python\")\nwindow.minsize(width=500, height=300)\n\n#Label\nmy_label = Label(text=\"I am a label\", font=(\"Arial\", 24, \"bold\"))\n#my_label.pack(side=\"left\")\nmy_label.pack()\nmy_label[\"text\"] = \"new text\"\nmy_label.config(text=\"label text\")\n\n#button\ndef button_clicked():\n my_label[\"text\"] = input.get()\n print(\"I got clicked!\")\nbutton = Button(text=\"Click Me\", command=button_clicked)\nbutton.pack()\n\ninput = Entry(width=10)\ninput.pack()\n\n\n\n\nwindow.mainloop()","repo_name":"sean-blessing/100-doc-python","sub_path":"sec-027/249-buttons-entry-set-options/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"47469439476","text":"# Given nums = [2, 7, 11, 15], target = 9, return [0,1]\n\n# nums = [2, 7, 11, 15]\nnums = [3, 7, 8, 11, 5]\n\ntarget = 19\n\n\ndef twoSum(nums, target):\n result = []\n for i in range(0, len(nums)):\n for j in range(1, len(nums)):\n if(nums[i]+nums[j] == target):\n result.append(i)\n result.append(j)\n break\n\n return result\n\n\nprint(twoSum(nums, target))\n","repo_name":"RuntimeTerror-404/leetcode-easy_medium","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"17942331561","text":"import atexit\nimport time\nfrom random import random, randint\n\nimport mlflow\n\n\ndef train():\n mlflow.log_param(\"param1\", randint(0, 100))\n\n # Log a metric; metrics can be updated throughout the run\n mlflow.log_metric(\"foo\", random())\n mlflow.log_metric(\"foo\", random() + 1)\n mlflow.log_metric(\"foo\", random() + 2)\n\n time.sleep(3)\n\n # error\n error = 1 / 0\n print(error)\n\n\ndef end_up():\n\n run_id = mlflow.active_run().info.run_id\n\n mlflow.end_run()\n # Check for any active runs\n print(\"Active run: {}\".format(mlflow.active_run()))\n\n run = mlflow.get_run(run_id)\n print(\"end_time\", run.info.end_time)\n # status is FINISHED\n print(\"run_id: {}; status: {}\".format(run.info.run_id, run.info.status))\n\n\natexit.register(end_up)\n\nif __name__ == \"__main__\":\n train()\n","repo_name":"shenwpo/test_mlflow","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"21061036859","text":"import pygame.font\r\n\r\n\r\nclass Button:\r\n\r\n def __init__(self, mg_game, msg):\r\n \"\"\"Initialize button attributes.\"\"\"\r\n self.mg_game = mg_game\r\n self.screen = mg_game.screen\r\n self.screen_rect = self.screen.get_rect()\r\n\r\n # Set the dimension and properties of the button.\r\n self.width, self.height = 200, 50\r\n self.button_color = (0, 0, 130)\r\n self.text_color = (255, 255, 255)\r\n self.font = pygame.font.SysFont(None, 48)\r\n\r\n # Build the button's rect object and display it at the bottom right of the screen.\r\n self.rect = pygame.Rect(0, 0, self.width, self.height)\r\n self.rect.bottomright = self.screen_rect.bottomright\r\n\r\n # The button message needs to be prepped only once.\r\n self._prep_msg(msg)\r\n\r\n def check_event_button(self, event):\r\n if event.type == pygame.MOUSEBUTTONDOWN:\r\n mouse_pos = pygame.mouse.get_pos()\r\n button_clicked = self.rect.collidepoint(mouse_pos)\r\n if button_clicked:\r\n # Mouse click occurred\r\n self._button_click_action()\r\n\r\n def _button_click_action(self):\r\n pass\r\n\r\n def _prep_msg(self, msg):\r\n \"\"\"Turn msg into a rendered image and center text on the button.\"\"\"\r\n self.msg_image = self.font.render(msg, True, self.text_color, self.button_color)\r\n self.msg_image_rect = self.msg_image.get_rect()\r\n self.msg_image_rect.center = self.rect.center\r\n\r\n def draw_button(self):\r\n # Draw blank button and then draw message.\r\n self.screen.fill(self.button_color, self.rect)\r\n self.screen.blit(self.msg_image, self.msg_image_rect)\r\n\r\n\r\nclass PlayButton(Button):\r\n def _button_click_action(self):\r\n \"\"\"Start a new game when the player clicks play.\"\"\"\r\n if not self.mg_game.settings.game_active:\r\n self.mg_game.settings.game_active = True\r\n self.mg_game.settings.game_active_start_time = pygame.time.get_ticks()\r\n\r\n\r\nclass SubmitButton(Button):\r\n def _button_click_action(self):\r\n \"\"\"Submit answers.\"\"\"\r\n if self.mg_game.settings.grade_answer is False:\r\n self.mg_game.settings.grade_answer = True\r\n self.mg_game.total_score = self.mg_game.scoreboard.check_answer()\r\n","repo_name":"xuanwei20/Memory_Game","sub_path":"button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"14727518055","text":"from tornado.ioloop import IOLoop\nfrom tornado.web import Application\nfrom config.config import config\n\nclass kernel:\n __singleton_instance = {}\n \n @staticmethod\n def boot():\n router = kernel.single('base_router').router()\n webapp = Application(router, settings={\"debug\": config.debug})\n webapp.listen(config.http_port)\n IOLoop.current().start()\n \n @staticmethod\n def single(classname):\n p = classname.index('_')\n if p:\n appname = classname[:p]\n classmodule = classname[p+1:]\n type = classmodule[:3]\n if type == 'ctl':\n classmodule = classmodule[4:].replace('_', '.')\n mvc = 'controller'\n elif type == 'mdl':\n classmodule = classmodule[4:].replace('_', '.')\n mvc = 'model'\n else:\n classmodule = classmodule.replace('_', '.')\n mvc = 'lib'\n path = config.app_dir+'.'+appname+'.'+mvc+'.'+classmodule\n if classname not in kernel.__singleton_instance:\n kernel.__singleton_instance[classname] = __import__(path).__getattribute__(appname).__getattribute__(mvc).__getattribute__(classmodule).__getattribute__(classname)\n return kernel.__singleton_instance[classname]\n return None\n","repo_name":"KylinHuang7/xianyang","sub_path":"app/kernel.py","file_name":"kernel.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"13097122393","text":"import h5py\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nf1 = h5py.File(\"sedov_hllc.hdf5\", \"r\")\nf2 = h5py.File(\"sedov_hll.hdf5\", \"r\")\nf3 = h5py.File(\"sedov_exact.hdf5\", \"r\")\n\n# get the exact solution\nexact = np.loadtxt(\"sedov_2d.dat\")\n\nx_exact = exact[:,1]\nrho_exact = exact[:,2]\np_exact = exact[:,4]\nu_exact = exact[:,5]\n\n# convert to radial\nnum = f1[\"/density\"].size\nx1 = f1[\"/particles\"][0,:num]\ny1 = f1[\"/particles\"][1,:num]\nr1 = np.sqrt((x1-0.5)**2 + (y1-0.5)**2)\n\nnum = f2[\"/density\"].size\nx2 = f2[\"/particles\"][0,:num]\ny2 = f2[\"/particles\"][1,:num]\nr2 = np.sqrt((x2-0.5)**2 + (y2-0.5)**2)\n\nnum = f3[\"/density\"].size\nx3 = f3[\"/particles\"][0,:num]\ny3 = f3[\"/particles\"][1,:num]\nr3 = np.sqrt((x3-0.5)**2 + (y3-0.5)**2)\n\nplt.figure(figsize=(8,8))\n\nplt.subplot(3,1,1)\nplt.scatter(r1, f1[\"/density\"][:], facecolors='none', edgecolors='b', label=\"Hllc\")\nplt.scatter(r2, f2[\"/density\"][:], facecolors='none', edgecolors='c', label=\"Hll\")\nplt.scatter(r3, f3[\"/density\"][:], facecolors='none', edgecolors='r', label=\"Exact\")\nplt.plot(x_exact, rho_exact, \"k\")\nplt.xlim(0,0.5)\nplt.ylim(-1,7)\nplt.xlabel(\"Position\")\nplt.ylabel(\"Density\")\nplt.title(\"Linear Reconstruction, Time: %0.2f\" % f1.attrs[\"time\"], fontsize=12)\nl = plt.legend(loc=\"upper left\", prop={\"size\":12})\nl.draw_frame(False)\n\nplt.subplot(3,1,2)\nplt.scatter(r1, np.sqrt(f1[\"/velocity-x\"][:]**2 + f1[\"/velocity-y\"][:]**2), facecolors='none', edgecolors='b', label=\"Hllc\")\nplt.scatter(r2, np.sqrt(f2[\"/velocity-x\"][:]**2 + f2[\"/velocity-y\"][:]**2), facecolors='none', edgecolors='c', label=\"Hll\")\nplt.scatter(r3, np.sqrt(f3[\"/velocity-x\"][:]**2 + f3[\"/velocity-y\"][:]**2), facecolors='none', edgecolors='r', label=\"Exact\")\nplt.plot(x_exact, u_exact, \"k\")\nplt.xlim(0,0.5)\nplt.ylim(-0.5,2.0)\nplt.ylabel(\"Velocity\")\n\nplt.subplot(3,1,3)\nplt.scatter(r1, f1[\"/pressure\"][:], facecolors='none', edgecolors='b', label=\"Hllc\")\nplt.scatter(r2, f2[\"/pressure\"][:], facecolors='none', edgecolors='c', label=\"Hll\")\nplt.scatter(r3, f3[\"/pressure\"][:], facecolors='none', edgecolors='r', label=\"Exact\")\nplt.plot(x_exact, p_exact, \"k\")\nplt.xlim(0,0.5)\nplt.ylim(-0.5,3.0)\nplt.ylabel(\"Pressure\")\n\nplt.savefig(\"sedov.pdf\")\nplt.show()\n","repo_name":"rickyfernandez/phd-code","sub_path":"phd/graveyard/test_problems/two_dim/sedov/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"77"}
+{"seq_id":"35113381730","text":"#Uses python3\nfrom collections import namedtuple\n\ncoordinate_point = namedtuple('coordinate_point', ['x', 'y'])\n\n\ndef calculated_min_distance(points):\n calculated_distances = []\n for i in range(len(points)):\n for j in range(i+1, len(points)):\n calculated_distances.append(calculate_distance(points[i], points[j]))\n return min(calculated_distances)\n\n\ndef calculate_distance(p1, p2):\n return ((p1.x - p2.x)**2+(p1.y - p2.y)**2)**(1/2)\n\n\ndef calculate_minimum_strip_distance(strip_points, min_distance):\n min_dist = min_distance\n for i in range(len(strip_points)):\n for j in range(i+1, len(strip_points)):\n distance = calculate_distance(strip_points[i], strip_points[j])\n if distance < min_dist:\n min_dist = distance\n return min_dist\n\n\ndef calculate_minimum_distance(points):\n #write your code here\n if len(points) <= 3:\n return calculated_min_distance(points)\n mid_value = len(points)//2\n section_l = calculate_minimum_distance(points[:mid_value])\n section_r = calculate_minimum_distance(points[mid_value::])\n minimum_distance = min(section_l, section_r)\n\n mid_point = points[mid_value]\n strip_points = [point for point in points if abs(mid_point.x - point.x) < minimum_distance]\n\n if len(strip_points) > 1:\n minimum_distance = calculate_minimum_strip_distance(strip_points, minimum_distance)\n return minimum_distance\n\n\nif __name__ == '__main__':\n num_points = int(input())\n points = []\n for i in range(num_points):\n x, y = list(map(int, input().split()))\n points.append(coordinate_point(x, y))\n points = sorted(points)\n min_distance = calculate_minimum_distance(points)\n print(min_distance)\n","repo_name":"Anzanrai/AlgorithmicToolbox","sub_path":"week4_solution/closest.py","file_name":"closest.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"15840699239","text":"# standard library\nimport itertools\nimport json as _json\nimport os\nimport shutil\n\nfrom dataclasses import dataclass\nfrom os import PathLike\nfrom pathlib import Path\n\n# typing\nfrom typing import Mapping, Union, cast\n\n# third parties\nfrom fastapi import HTTPException\n\n# Youwol utilities\nfrom youwol.utils.clients.storage.models import FileData\nfrom youwol.utils.clients.utils import get_default_owner\nfrom youwol.utils.exceptions import ResourcesNotFoundException\nfrom youwol.utils.types import JSON\n\nflatten = itertools.chain.from_iterable\n\n\ndef create_dir_if_needed(full_path: Path):\n dir_path = full_path.parent\n if not dir_path.exists():\n os.makedirs(cast(PathLike, dir_path))\n\n\n@dataclass(frozen=True)\nclass LocalStorageClient:\n root_path: Path\n bucket_name: str\n\n @property\n def bucket_path(self) -> Path:\n return self.root_path / self.bucket_name\n\n def get_full_path(self, owner: str, path: Union[str, Path]) -> Path:\n return self.bucket_path / owner[1:] / path\n\n async def delete_bucket(self, **_kwargs):\n if self.bucket_path.exists():\n shutil.rmtree(self.bucket_path)\n\n async def ensure_bucket(self, **_kwargs):\n if not self.bucket_path.exists():\n os.makedirs(cast(PathLike, self.bucket_path))\n\n return True\n\n async def post_file(\n self, form: FileData, headers: Mapping[str, str] = None, **_kwargs\n ):\n owner = form.owner\n if not headers:\n headers = {}\n if not owner:\n owner = get_default_owner(headers)\n\n full_path = self.get_full_path(owner, form.objectName)\n\n create_dir_if_needed(full_path)\n full_path.open(\"wb\").write(form.objectData)\n return {}\n\n async def post_object(\n self,\n path: Union[Path, str],\n content: bytes,\n owner: Union[str, None],\n headers: Mapping[str, str] = None,\n **_kwargs,\n ):\n if not headers:\n headers = {}\n if not owner:\n owner = get_default_owner(headers)\n\n if isinstance(content, str):\n content = str.encode(content)\n\n data = content\n\n full_path = self.get_full_path(owner, path)\n create_dir_if_needed(full_path)\n full_path.open(\"wb\").write(data)\n\n async def post_json(\n self,\n path: Union[str, Path],\n json: JSON,\n owner: Union[str, None],\n headers: Mapping[str, str] = None,\n **_kwargs,\n ):\n if not headers:\n headers = {}\n if not owner:\n owner = get_default_owner(headers)\n\n full_path = self.get_full_path(owner, path)\n create_dir_if_needed(full_path)\n full_path.open(\"w\").write(_json.dumps(json, indent=4))\n return {}\n\n async def post_text(\n self,\n path: Union[str, Path],\n text,\n owner: Union[str, None],\n headers: Mapping[str, str] = None,\n **_kwargs,\n ):\n if not headers:\n headers = {}\n if not owner:\n owner = get_default_owner(headers)\n\n full_path = self.get_full_path(owner, path)\n create_dir_if_needed(full_path)\n full_path.open(\"w\").write(text)\n return {}\n\n async def delete_group(\n self,\n prefix: Union[Path, str],\n owner: Union[str, None],\n headers: Mapping[str, str] = None,\n **_kwargs,\n ):\n if not headers:\n headers = {}\n if not owner:\n owner = get_default_owner(headers)\n\n path = self.get_full_path(owner, prefix)\n if path.exists():\n shutil.rmtree(path)\n\n async def delete(\n self,\n path: Union[str, Path],\n owner: Union[str, None],\n headers: Mapping[str, str] = None,\n **_kwargs,\n ):\n if not headers:\n headers = {}\n if not owner:\n owner = get_default_owner(headers)\n\n full_path = self.get_full_path(owner, path)\n if full_path.is_dir():\n shutil.rmtree(full_path)\n return\n\n if not full_path.exists():\n raise HTTPException(\n status_code=404, detail=f\"File {full_path.name} not found\"\n )\n os.remove(full_path)\n\n return {}\n\n async def list_files(\n self,\n prefix: Union[str, Path],\n owner: Union[str, None],\n headers: Mapping[str, str] = None,\n **_kwargs,\n ):\n if not headers:\n headers = {}\n if not owner:\n owner = get_default_owner(headers)\n\n owner = owner[1:]\n results = [\n [(Path(root) / f).relative_to(self.bucket_path / owner) for f in files]\n for root, _, files in os.walk(self.bucket_path / owner / prefix)\n ]\n\n return [{\"name\": str(r)} for r in flatten(results)]\n\n async def get_bytes(\n self,\n path: Union[str, Path],\n owner: Union[str, None],\n headers: Mapping[str, str] = None,\n **_kwargs,\n ):\n if not headers:\n headers = {}\n if not owner:\n owner = get_default_owner(headers)\n\n full_path = self.get_full_path(owner, path)\n if not full_path.is_file():\n raise ResourcesNotFoundException(path=str(full_path))\n\n return full_path.open(\"rb\").read()\n\n async def get_json(\n self,\n path: Union[str, Path],\n owner: Union[str, None],\n headers: Mapping[str, str] = None,\n **kwargs,\n ):\n return _json.loads(await self.get_bytes(path, owner, headers, **kwargs))\n\n async def get_text(\n self,\n path: str,\n owner: Union[str, None],\n headers: Mapping[str, str] = None,\n **kwargs,\n ):\n raw = await self.get_bytes(path, owner, headers, **kwargs)\n return raw.decode(\"utf-8\")\n","repo_name":"youwol/py-youwol","sub_path":"src/youwol/utils/clients/storage/local_storage.py","file_name":"local_storage.py","file_ext":"py","file_size_in_byte":5853,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"6175997253","text":"# Kate Bowers\n# Levin Lab Tufts University\n# Program development started March 2021\n# Beckman Scholars - Tadpole Bullying\n# collisionsPerVideo.py -- for a given video csv folder, computes all collisions between WT and deformed tadpoles\n\nfrom utilities import mins, find_def_start_time, makeSteps\nimport findCollisionsClasses # UPDATED FOR CLASSES BRANCH\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport fileIO\n\n# TODO for plots -- show proximity length as well as just collision length? somehow? idk\n\n\ndef find_collisions_per_video(datfile, csvs_path):\n # datfile - wt num, wrong_distances, num of tadpoles\n print(csvs_path)\n def_num = datfile[0]\n wrong_distances = datfile[1]\n num_tads = datfile[2]\n\n # Calculate for all\n all_collisions = []\n all_steps = [] # for plotting\n total_collisions = 0\n\n # Know when the deformed tadpole shows up\n def_start_time = find_def_start_time(def_num, csvs_path)\n time_with_def = None\n\n timer = 45500 # TODO this is just the limit in steps for testing (ie first 15 min = 28500 slots)\n\n for subject in range(1, num_tads + 1): # calculate for all\n if subject == def_num: # skip deformed lol\n continue\n result = findCollisionsClasses.find_collisions(subject, def_num, csvs_path, wrong_distances, \\\n def_start_time, all_collisions)\n # this is where I would add the plot stuff\n subj_collisions = result[2]\n timeline = result[3]\n print(\"calculating plot steps for \", subject)\n subj_steps = makeSteps(subj_collisions, list(timeline)) # [:timer + 1])) 25 minute timer\n all_steps.append(list(subj_steps))\n\n all_collisions = list(result[0]) # because all colliisons is reset every time\n time_with_def = result[1] # this is a stupid way to find this\n\n total_collisions = len(all_collisions)\n\n ####### PLOTS #######\n cmap = plt.cm.get_cmap(\"hsv\", len(all_steps))\n\n #print(cmap(1/len(all_steps), bytes=True))\n #print(cmap(2/len(all_steps), bytes=True))\n #print(\"made cmap\")\n\n # Broken axis collision plot\n fig, (axoutlier, axmost) = plt.subplots(2, 1, sharex='all', gridspec_kw={'height_ratios':[6,12]})\n fig.subplots_adjust(hspace=0.05)\n\n for i in np.arange(0, len(all_steps)):\n #axmost.step(timeline[:timer + 1], all_steps[i], c=cmap(i), where='post')\n #axoutlier.step(timeline[:timer + 1], all_steps[i], c=cmap(i), where='post')\n axmost.step(timeline, all_steps[i], c=cmap(i), where='post')\n axoutlier.step(timeline, all_steps[i], c=cmap(i), where='post')\n\n\n axmost.set_ylim(0, 12.5)\n axoutlier.set_yticks([25, 50, 75, 100, 125, 150, 175])\n #axmost.set_xlim(250, 400)\n axoutlier.set_ylim(12.5, 140)\n #axoutlier.set_xlim(250, 400)\n\n\n # setting slanted lines for broken axis plots\n d = .5 # proportion of vertical to horizontal extent of the slanted line\n kwargs = dict(marker=[(-1, -d), (1, d)], markersize=12,\n linestyle=\"none\", color='k', mec='k', mew=1, clip_on=False)\n axoutlier.plot([0, 1], [0, 0], transform=axoutlier.transAxes, **kwargs)\n axmost.plot([0, 1], [1, 1], transform=axmost.transAxes, **kwargs)\n\n plt.xlabel(\"Time(s)\")\n plt.ylabel(\"Collision Velocity (mm/s)\")\n this_title = \"Collision duration and velocity over time \\n\" \\\n \"in \" + fileIO.userinput[2] + \" video: \"+str(total_collisions)+\" collisions\"\n axoutlier.set_title(this_title)\n plt.show()\n\n # Zoomed in plot\n '''\n print(\"zoomed in plot \")\n cmap = plt.cm.get_cmap(\"hsv\", len(all_steps))\n #print(\"made cmap\")\n axmost = plt.subplots(figsize=(8,4.8))\n #fig.subplots_adjust(hspace=0.05)\n\n #print(\"made fig ax\")\n\n # plt.xticks(timeline)\n # print(\"made xticks\")\n\n for i in np.arange(0, len(all_steps)):\n plt.step(timeline[:timer + 1], all_steps[i], c=cmap(i), where='post')\n #axoutlier.step(timeline, all_steps[i], c=cmap(i), where='post')\n\n plt.ylim(0, 12.5)\n #axoutlier.set_yticks([25, 50, 75, 100, 125, 150, 175])\n plt.xlim(800, 1000)\n #axoutlier.set_ylim(12.5, 140)\n #axoutlier.set_xlim(250, 400)\n\n\n # plt.show()\n #\n # d = .5 # proportion of vertical to horizontal extent of the slanted line\n # kwargs = dict(marker=[(-1, -d), (1, d)], markersize=12,\n # linestyle=\"none\", color='k', mec='k', mew=1, clip_on=False)\n # axoutlier.plot([0, 1], [0, 0], transform=axoutlier.transAxes, **kwargs)\n # axmost.plot([0, 1], [1, 1], transform=axmost.transAxes, **kwargs)\n\n plt.xlabel(\"Time(s)\")\n plt.ylabel(\"Collision Velocity (mm/s)\")\n # plt.show()\n #\n '''\n\n # another zoomed in plot\n '''\n cmap = plt.cm.get_cmap(\"hsv\", len(all_steps))\n axmost = plt.subplots(figsize=(8, 4.8))\n # fig.subplots_adjust(hspace=0.05)\n\n # plt.xticks(timeline)\n # print(\"made xticks\")\n\n for i in np.arange(0, len(all_steps)):\n plt.step(timeline[:timer + 1], all_steps[i], c=cmap(i), where='post')\n # axoutlier.step(timeline, all_steps[i], c=cmap(i), where='post')\n # break\n # scatter(X, Y, c=cmap(i))\n\n plt.ylim(0, 12.5)\n # axoutlier.set_yticks([25, 50, 75, 100, 125, 150, 175])\n plt.xlim(0, 400)\n # axoutlier.set_ylim(12.5, 140)\n # axoutlier.set_xlim(250, 400)\n\n # plt.show()\n #\n # d = .5 # proportion of vertical to horizontal extent of the slanted line\n # kwargs = dict(marker=[(-1, -d), (1, d)], markersize=12,\n # linestyle=\"none\", color='k', mec='k', mew=1, clip_on=False)\n # axoutlier.plot([0, 1], [0, 0], transform=axoutlier.transAxes, **kwargs)\n # axmost.plot([0, 1], [1, 1], transform=axmost.transAxes, **kwargs)\n\n plt.xlabel(\"Time(s)\")\n plt.ylabel(\"Collision Velocity (mm/s)\")\n #plt.show()\n '''\n\n # Another kind of zoomed in plot\n '''\n cmap = plt.cm.get_cmap(\"hsv\", len(all_steps))\n print(\"made cmap\")\n axmost = plt.subplots(figsize=(8, 4.8))\n # fig.subplots_adjust(hspace=0.05)\n\n print(\"made fig ax\")\n\n # plt.xticks(timeline)\n # print(\"made xticks\")\n\n for i in np.arange(0, len(all_steps)):\n plt.step(timeline[:timer + 1], all_steps[i], c=cmap(i), where='post')\n # axoutlier.step(timeline, all_steps[i], c=cmap(i), where='post')\n # break\n # scatter(X, Y, c=cmap(i))\n\n plt.ylim(0, 12.5)\n # axoutlier.set_yticks([25, 50, 75, 100, 125, 150, 175])\n plt.xlim(0, 600)\n # axoutlier.set_ylim(12.5, 140)\n # axoutlier.set_xlim(250, 400)\n\n # plt.show()\n #\n # d = .5 # proportion of vertical to horizontal extent of the slanted line\n # kwargs = dict(marker=[(-1, -d), (1, d)], markersize=12,\n # linestyle=\"none\", color='k', mec='k', mew=1, clip_on=False)\n # axoutlier.plot([0, 1], [0, 0], transform=axoutlier.transAxes, **kwargs)\n # axmost.plot([0, 1], [1, 1], transform=axmost.transAxes, **kwargs)\n\n plt.xlabel(\"Time(s)\")\n plt.ylabel(\"Collision Velocity (mm/s)\")\n plt.show()\n '''\n\n #####\n print(str(total_collisions) + \" by \" + str(num_tads - 1) + \" wt tadpoles\") # + \" in \" + deformed_csv[14][1])\n print(\"in \" + mins(time_with_def) + \" minutes\")\n # Flatten into time-based mega list\n # print(all_collisions)\n # all_collisions_flat_bytime = sum(all_collisions, []) # flattens from subjects to full video\n # sort by time\n all_collisions_flat_bytime = all_collisions\n all_collisions_flat_bytime.sort(key=lambda x: x.time)\n\n # report_concurrents(all_collisions_flat_bytime, def_num, csvs_path, def_start_time, num_tads) # concurrents\n\n '''\n all_collisions_flat_times = list(map(lambda x: x[0], all_collisions_flat_bytime))\n if (wrong_distances == False):\n all_collisions_flat_disps = list(map(lambda x: x[1], all_collisions_flat_bytime)) \n all_collisions_flat_velocities = list(map(lambda x: x[2], all_collisions_flat_bytime))\n else:\n all_collisions_flat_disps = list(map(lambda x: x[1]/10, all_collisions_flat_bytime)) # \tDIVIDE BY 10 FOR NEW VIDEO 1 (and below)\n all_collisions_flat_velocities = list(map(lambda x: x[2]/10, all_collisions_flat_bytime))\n '''\n\n # would call plotting thigns now\n\n # print(all_steps)\n print(\"all steps graphs done\")\n return (all_collisions_flat_bytime, time_with_def, all_steps, timeline)\n\n","repo_name":"kate-bowers/tadpole-bullying","sub_path":"src/collisionsPerVideo.py","file_name":"collisionsPerVideo.py","file_ext":"py","file_size_in_byte":8353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"10786423221","text":"import sys\n\nsys.stdin = open(\"1208.Flatten.txt\", 'r')\n\nT = 10\nfor tc in range(1, T+1):\n N = int(input())\n arr = list(map(int, input().split()))\n \n arr.sort()\n res = 0\n for i in range(N):\n arr[-1] -= 1\n arr[0] += 1\n arr.sort()\n res = arr[-1] - arr[0]\n \n print(f\"#{tc} {res}\")","repo_name":"nonusDev/Algorithm","sub_path":"SWEA/D3/1208.Flatten.py","file_name":"1208.Flatten.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"86261771983","text":"# pylint: disable=missing-docstring, line-too-long, protected-access\nimport unittest\nfrom unittest import mock\nfrom runner import Runner\n\n\nclass TestRunnerMethods(unittest.TestCase):\n def setUp(self):\n self.snippet = \"string\"\n self.tmpdir = \"foo\"\n\n @mock.patch(\"tempfile.mkdtemp\")\n def test_mktmpdir(self, tempfile_mock):\n tempfile_mock.return_value = \"path\"\n Runner._mktmpdir(self)\n self.assertEqual(self.tmpdir, \"path\")\n\n @unittest.skip # @TODO\n def test_run(self):\n # runner.run()\n self.assertEqual('{dict}', '{dict}')\n\n @mock.patch(\"shutil.rmtree\")\n def test_removetmpdir(self, shutil_mock):\n Runner._removetmpdir(self)\n shutil_mock.assert_called_once_with(self.tmpdir)\n\n @mock.patch(\"subprocess.call\")\n def test__terraform_init(self, subprocess_mock):\n Runner._terraform_init(self)\n subprocess_mock.assert_called_once_with([\"terraform\", f\"-chdir={self.tmpdir}\", \"init\"])\n\n @mock.patch(\"os.system\")\n def test_teraform_plan(self, os_mock):\n Runner._terraform_plan(self)\n os_mock.assert_called_once_with(\n f\"terraform -chdir={self.tmpdir} plan -input=false -out={self.tmpdir}/mytf.tfplan\")\n\n @unittest.skip # @TODO\n @mock.patch(\"os.system\")\n def test__copy_tf_files(self, os_mock):\n Runner._copy_tf_files(self)\n os_mock.assert_any_call(\"rm -rf .terraform/modules\")\n os_mock.assert_any_call(\"mkdir \" + self.tmpdir + \"/mymodule\")\n\n @mock.patch(\"subprocess.check_output\")\n def test_snippet_to_json(self, subprocess_mock):\n Runner.snippet_to_json(self)\n subprocess_mock.assert_called_once_with(\n [\"terraform\", f\"-chdir={self.tmpdir}\", \"show\",\n \"-no-color\", \"-json\", f\"{self.tmpdir}/mytf.tfplan\"])\n\n @mock.patch(\"json.loads\")\n def test_json_to_dict(self, mock_json):\n mock_json.return_value = {}\n json_file = {}\n self.assertEqual(Runner.json_to_dict(json_file), {})\n\n\nclass TestE2E(unittest.TestCase):\n def setUp(self):\n self.snippet = \"\"\"\n provider aws {\n region = \"eu-west-2\"\n access_key = \"foo\"\n secret_key = \"bar\"\n skip_credentials_validation = true\n skip_requesting_account_id = true\n }\n\n resource \"aws_instance\" \"foo\" {\n ami = \"foo\"\n instance_type = \"t2.micro\"\n }\n \"\"\"\n self.runner = Runner(self.snippet)\n self.result = self.runner.result\n\n def test_terraform_version(self):\n print(self.result)\n self.assertEqual(self.result[\"terraform_version\"], \"1.6.6\")\n\n def test_create_action(self):\n self.assertEqual(self.result[\"resource_changes\"][0][\"change\"][\"actions\"], ['create'])\n\n def test_instance_type(self):\n self.assertEqual(self.runner.get_value(\"aws_instance.foo\", \"instance_type\"), \"t2.micro\")\n\n def test_ami(self):\n self.assertEqual(self.runner.get_value(\"aws_instance.foo\", \"ami\"), \"foo\")\n\n\nclass TestE2EModule(unittest.TestCase):\n def setUp(self):\n self.snippet = \"\"\"\n provider aws {\n region = \"eu-west-2\"\n access_key = \"foo\"\n secret_key = \"bar\"\n skip_credentials_validation = true\n skip_requesting_account_id = true\n }\n\n module \"foo\" {\n source = \"./mymodule\"\n }\n \"\"\"\n self.runner = Runner(self.snippet)\n self.result = self.runner.result\n\n def test_root_module(self):\n print(self.result)\n self.assertEqual(self.result[\"configuration\"][\"root_module\"][\"module_calls\"][\"foo\"][\"source\"], \"./mymodule\")\n\n def test_instance_type(self):\n self.assertEqual(self.runner.get_value(\"module.foo.aws_instance.foo\", \"instance_type\"), \"t2.micro\")\n\n def test_ami(self):\n self.assertEqual(self.runner.get_value(\"module.foo.aws_instance.foo\", \"ami\"), \"foo\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"UKHomeOffice/tf-testrunner","sub_path":"tests/runner_test.py","file_name":"runner_test.py","file_ext":"py","file_size_in_byte":3987,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"77"}
+{"seq_id":"32529908349","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # INTRODUCTION\n# \n# There are given two datasets. \n# \n# One of them is \"clicked items investigation\" and the other one is \"session investigation\".\n# \n# First of all, i should write my methodology and solution approach.\n# \n# I follow five instruction to solve data science problems:\n# \n# - Define the problem\n# \n# - Prepare Data / Data Preprocessing\n# Get Data\n# Data Cleaning/Wrangling\n# Statistical Analysis\n# Data Visualization\n# Feature Selection/Scaling\n# Data Transformation\n# \n# - Check Algorithms\n# Train & Test Data\n# Apply ML Algorithm\n# Test\n# Perform Measure\n# Evaulate accuarcy of different algorithm\n# \n# - Improve Results\n# Algorithm Tuning\n# \n# - Present Results\n# Conclusion\n# Presentation\n\n# ## DEFINITION THE PROBLEM\n# \n# We have some information about the items(hotels) and we will try to solve questions using data_analysis_case_study_part1.csv and data_analysis_case_study_part2.csv datasets.\n# \n# The aim is to analyze customer click-out behaivour. On the other hand, one of the most important point is click through rates. These informations helps us to evaulate the hotel performance, provide insight for ranking, in addition to that we can predict other hotels might be interesting for the end users. \n\n# ### 1-CLICKED ITEM INVESTIGATION\n# \n# For this section we will try to find answer following questions the below.\n# \n# 1-Calculate the CTR of each item. What is the overall avg CTR?\n# \n# 2-What is the distribution of clicks among the top 25 positions? What is the share of the first positions? On how many positions are approx. Half of the click-outs made?\n# \n# 3-Describe the relationship between the average displayed position and the clicked displayed position. What are your thoughts about the variance between the two?\n# \n# 4-In the dataset, we provided you with the average displayed position. What can be wrong with using averages?\n# \n# So let's start data analysis...\n\n# In[1]:\n\n\n# Import essential libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport statistics as st\nimport math as m\nimport scipy.stats as sct\n#from scipy import stats as st\n\nfrom IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = \"all\"\nsns.set()\n\n\n# In[2]:\n\n\n# Log\nimport logging\nlogger = logging.getLogger()\nfhandler = logging.FileHandler(filename='data_analyst_search.log', mode='a')\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nfhandler.setFormatter(formatter)\nlogger.addHandler(fhandler)\nlogger.setLevel(logging.DEBUG)\n\n\n# ###### 1-Calculate the CTR of each item. What is the overall avg CTR?\n\n# In[3]:\n\n\n# Get data\nfile = 'data_analysis_case_study_part1.csv'\ndata = pd.read_csv(file)\n\ndata.head(5)\ndata.shape\n\nlogging.debug('data received...')\n\n\n# In[4]:\n\n\n# Data types and size\ndata.info()\n\n\n# In[5]:\n\n\n# check negative values; if it is exist, update or ignore these values\n\n#data['impressions'] = np.where((data['impressions'] < 0), 0, data['impressions'])\n\nneg_imp = set(data.loc[data.impressions < 0, 'impressions'])\nneg_cli = set(data.loc[data.clicks < 0, 'clicks'])\nneg_avg = set(data.loc[data.avg_impressed_position < 0, 'avg_impressed_position'])\nneg_user = set(data.loc[data.num_users < 0, 'num_users'])\nneg_sess = set(data.loc[data.num_sessions < 0, 'num_sessions'])\n\nprint(\"impression : \", neg_imp)\nprint(\"clicks : \", neg_cli)\nprint(\"avg_impressed_position : \", neg_avg)\nprint(\"num_users : \", neg_user)\nprint(\"num_sessions : \", neg_sess)\n\nlogging.debug('check negative values')\n\n\n# In[6]:\n\n\n# check null values\ncheck_null_columns = data.isnull().sum()\nprint('**************************')\nprint('Check Null Values Column by Column')\nprint(check_null_columns)\nprint('count of null values ', data.isnull().values.sum())\nprint('**************************')\n\nlogging.debug('check null values')\n\n\n# In[7]:\n\n\n# check unique hotel id\ndata[data.duplicated(subset=['item_id'],keep=False)]\n\nlogging.debug('check unique hotel')\n\n\n# In[8]:\n\n\n# some statistical information\ndata.describe()\n\n\n# ###### CTR of each item and overall avg CTR?\n\n# In[9]:\n\n\n# CTR\n# overall CTR\n\ndata['CTR'] = (data.clicks)/(data.impressions)\ndata['CTR_overall'] = sum(data.clicks)/sum(data.impressions)\n\ndata.head(5)\n\nlogging.debug('CTR and overall CTR')\n\n\n# ###### 2-What is the distribution of clicks among the top 25 positions? What is the share of the first positions? On how many positions are approx. Half of the click-outs made?\n\n# In[10]:\n\n\n# convert from semicolon to list\nclicked_distribution = pd.Series(data.clicked_displayed_positions.str.cat(sep=';').split(';')).value_counts()\nclicked_distribution\n\nlogging.debug('parsing semicolon data')\n\n\n# In[11]:\n\n\n# we expect that the positions should be between 0 and 24. \n# so we need to remove -11 position, because this data is not valid for our analysis.\nclicked_distribution = clicked_distribution.drop(labels=['-11'])\nclicked_distribution\n\nlogging.debug('cleaning the unexpected positions')\n\n\n# ###### What is the share of the first positions?\n\n# In[12]:\n\n\n# distribution of clicks\nprint(\" \")\nprint(\" \")\nprint ('please find distribution of clicks from the pie chart below!')\n\nlabels = clicked_distribution.index\nsizes = clicked_distribution.values\nexplode = (0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)\n\nfig = plt.figure(figsize=(10, 10))\n_=plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=180)\n_=plt.axis('equal')\nplt.show();\n\nlogging.debug('distribution of positions')\n\n\n# ###### On how many positions are approx. Half of the click-outs made?\n\n# In[13]:\n\n\n# share of the first position\n# half of the click-outs made\n\nprint ('share of the first position : ', '% 31.1')\nprint ('half of the click-outs made : ', 'First three positions= 0,1,2')\n\n\n# ###### 3-Describe the relationship between the average displayed position and the clicked displayed position. What are your thoughts about the variance between the two?\n# \n\n# In[14]:\n\n\n# thanks to some range setting assumption, we can find total clicks according to average displayed position.\n \n # 0.0-0.5 = 0 position\n # 0.5-1.5 = 1 position\n # 1.5-2.5 = 2 position \n # ...\n # 22.5-23.5 = 23 position\n # 23.5-24.0 = 24 position\n\nimpressed_distribution = pd.Series(data['clicks'][data['avg_impressed_position'] <= 0.5].sum())\n\nfor i in range(1,24,1):\n impressed_distribution = impressed_distribution.append(pd.Series(data['clicks'][((data['avg_impressed_position'] >= (i-0.5)) & \n (data['avg_impressed_position'] <= (i+0.5)))].sum()), \n ignore_index=True)\n \nimpressed_distribution = impressed_distribution.append(pd.Series(data['clicks'][data['avg_impressed_position'] >= 23.5].sum()), \n ignore_index=True)\nimpressed_distribution\n\n\n# In[15]:\n\n\n# number of clicks vs clicked displayed position\nfig = plt.figure(figsize=(12,5))\n_=plt.bar(clicked_distribution.index, clicked_distribution.values, color='red')\n_=plt.xlabel('clicked_displayed_position')\n_=plt.ylabel('number_of_clicks')\n_=plt.title('clicks' + ' & displayed_position')\nplt.show();\n\nlogging.debug('clicks & avg impressed position')\n\n\n# avg impressions vs clicks\nfig = plt.figure(figsize=(12,5))\n_=plt.bar(impressed_distribution.index, impressed_distribution.values, color='green')\n_=plt.xlabel('avg_impressed_position')\n_=plt.ylabel('number_of_clicks')\n_=plt.title('clicks' + ' & avg_impressed_position')\nplt.show();\n\nlogging.debug('clicks & displayed position')\n\n\n# step one- Describe the relationship between the avg_impressed_position and the clicked displayed position.\nfig = plt.figure(figsize=(12,5))\np1, = plt.plot(impressed_distribution.index, impressed_distribution.values, color='green')\np2, = plt.plot(clicked_distribution.index, clicked_distribution.values, color='red')\n_=plt.legend([p1, p2], ['avg_imp','click_pos'], loc='best')\n_=plt.xlabel('positions')\n_=plt.ylabel('clicked_position / avg_impressed')\n_=plt.title('clicked_position & avg_impressed')\nplt.show();\n\nlogging.debug('clicked position & avg impressed position')\n\n\n# In[16]:\n\n\n# step two- Describe the relationship between the avg_impressed_position and the clicked displayed position.\n\nimpressed_distribution.index = impressed_distribution.index.astype(int)\nimpressed_distribution.sort_index(inplace=True)\n\nclicked_distribution.index = clicked_distribution.index.astype(int)\nclicked_distribution.sort_index(inplace=True)\n\ncorr_map = {'avg_impressed' : impressed_distribution, 'clicked_displayed' : clicked_distribution}\ncorr_df = pd.DataFrame(corr_map)\n\npd.set_option('precision', 5)\ncorrelations = corr_df.corr(method='pearson')\n\nprint('')\nprint('')\nprint('')\nprint('*********************')\nprint('correlation table')\ncorr_df.head(5)\n\nprint('')\nprint('')\nprint('')\nprint('*********************')\nprint('correlation coefficient')\ncorrelations\n\nprint('')\nprint('')\nprint('')\ncolormap = sns.diverging_palette(210, 20, as_cmap=True)\n_=sns.heatmap(correlations, cmap=colormap, annot=True, fmt=\".2f\")\n_=plt.xticks(range(len(correlations.columns)), correlations.columns)\n_=plt.yticks(range(len(correlations.columns)), correlations.columns)\nplt.show();\n\nlogging.debug('correlation')\n\n\n# ###### What are your thoughts about the variance between the two?\n\n# This analysis shows us clearly that there is not any direct relationship between \"impressions\" and \"clicks\".\n# \n# Moreover, we can say that if you would like to increase the number of clicks you should stay in the first 3 positions on the list.\n# \n# On the other hand, one of the important value is the impression. \n# But impression says that your position should be between 6 and 14 for many clicks.\n# \n# As a result, we should think together, both clicked position and avg impressed position.\n# \n# Your position can be at a different location on the list, but in general, it is in the first 3 positions when the hotel is clicked by users.\n# \n# Your position depends on some filters or searches criteria.\n# \n# In this time, your click chance is decreasing because of your avg impressed position calculating.\n# \n# The last one, you should focus your \"currently position\" not \"average impressed position\". \n# \n# Because you can slip down on the list and your avg impressed position can be changed, but it is normal and not vital.\n\n# ###### 4-In the dataset, we provided you with the average displayed position. What can be wrong with using averages?\n\n# One of the most important questions that are how and why to calculate the avg result.\n# \n# We analyzed avg output the above and this information is not helpful for the next step.\n# \n# Because each customer wants to choose different features and filters.\n# \n# Then sometimes your position drops behind because of ranking or filters, but this not mean you will not be selected by the customers.\n# \n# Your \"avg impressed position\" can be increased because of all these factors. But when you are placed near the top, your click possibility can increase and not affects from avg impressed position.\n\n# ### 2-SESSION INVESTIGATION\n# \n# For this section we will try to find answer following questions the below.\n# \n# 1-Describe the data set that you have received. Calculate the 5 most frequent values per column (with frequency). Can you find any suspicious results? If so, what are they? And how would you fix these for the analysis?\n# \n# 2-Which search type has the lowest average displayed position? What is the best sorting order for this search type? Which search type should be excluded for a statistical reason?\n# \n# 3-What are the top 10 “best” and “worst” performing items? Explain what metric you have chosen to evaluate the performance and why.\n# \n# 4-Describe and visualise the relationship between the average displayed position and the CTR among the top 1000 most clicked items.\n# \n# So let's start data analysis...\n\n# ###### 1-Describe the data set that you have received. Calculate the 5 most frequent values per column (with frequency). Can you find any suspicious results? If so, what are they? And how would you fix these for the analysis?\n\n# In[17]:\n\n\n# Get data\nfile2 = 'data_analysis_case_study_part2.csv'\nbig_data = pd.read_csv(file2, low_memory=False)\n\nbig_data.head(5)\nbig_data.shape\n\nlogging.debug('big data received...')\n\n\n# In[18]:\n\n\n# Data types and size\nbig_data.info()\n\n\n# In[19]:\n\n\n# some statistical informations\nbig_data.describe()\n\n\n# In[20]:\n\n\n# check null values\ncheck_null_columns_2 = big_data.isnull().sum()\nprint('**************************')\nprint('Check Null Values Column by Column')\nprint(check_null_columns_2)\nprint('**************************')\nprint('count of null values ', big_data.isnull().values.sum())\nprint('**************************')\n\nlogging.debug('check null values')\n\n\n# In[21]:\n\n\n# delete null values\nprint('**************************')\nprint('before :')\nbig_data[big_data['session_id'].isnull()]\nbig_data = big_data.drop([1903795])\nprint(\"\")\nprint('**************************')\nprint('after :')\nbig_data[big_data['session_id'].isnull()]\n\nlogging.debug('remove null values')\n\n\n# In[22]:\n\n\n# check negative values; if it is exist, update or ignore these values\n\n#data['sess_id'] = np.where((data['sess_id'] < 0), 0, data['sess_id'])\n\nneg_sess_id = set(big_data.loc[big_data.session_id < 0, 'session_id'])\nneg_clic_it_id = set(big_data.loc[big_data.clicked_item_id < 0, 'clicked_item_id'])\nneg_disp_pos = set(big_data.loc[big_data.displayed_position < 0, 'displayed_position'])\nneg_pg_num = set(big_data.loc[big_data.page_num < 0, 'page_num'])\nneg_srt_ord = set(big_data.loc[big_data.sort_order < 0, 'sort_order'])\nneg_src_type = set(big_data.loc[big_data.search_type < 0, 'search_type'])\nneg_pth_id = set(big_data.loc[big_data.path_id < 0, 'path_id'])\nneg_arr_days = set(big_data.loc[big_data.arrival_days < 0, 'arrival_days'])\nneg_dpt_days = set(big_data.loc[big_data.departure_days < 0, 'departure_days'])\nneg_trf_typ = set(big_data.loc[big_data.traffic_type < 0, 'traffic_type'])\n\nprint(\"session_id : \", neg_sess_id)\nprint(\"clicked_item_id : \", neg_clic_it_id)\nprint(\"displayed_position : \", neg_disp_pos)\nprint(\"page_num : \", neg_pg_num)\nprint(\"sort_order : \", neg_srt_ord)\nprint(\"search_type : \", neg_src_type)\nprint(\"path_id : \", neg_pth_id)\nprint(\"arrival_days : \", neg_arr_days)\nprint(\"departure_days : \", neg_dpt_days)\nprint(\"traffic_type : \", neg_trf_typ)\nprint(\"************************\")\nprint(\"\")\nbig_data[((big_data['displayed_position'] < 0) | (big_data['displayed_position'] > 24)) & (big_data['displayed_position'] != -11)]\n\nlogging.debug('check negative values')\n\n\n# ###### Calculate the 5 most frequent values per column (with frequency)\n\n# In[23]:\n\n\n# Calculate the 5 most frequent values per column (with frequency)\n\nbig_data.user_id = big_data.user_id.astype(float)\n\nimpressed_item_ids_distr = pd.Series(big_data[\"impressed_item_ids \"].str.cat(sep=';').split(';')).value_counts()\nimpressed_item_ids_distr.index = impressed_item_ids_distr.index.astype(int)\n\nfor c in big_data.columns:\n if c == \"impressed_item_ids \":\n continue \n print('*********************')\n print(c)\n big_data[c].value_counts().nlargest(5)\n \nprint('*********************')\nprint('impressed_item_ids ')\nimpressed_item_ids_distr.head(5)\n\nlogging.debug('frequency analysis')\n\n\n# ###### Can you find any suspicious results? If so, what are they? And how would you fix these for the analysis?\n\n# In[24]:\n\n\n# displayed_position should be in between 0 and 24, so -11 is incorrect, \n# market share should be updated.\n# we have enough data for analysis and -11 position data is not big, so no big affect to our analysis.\n\n# On the other way if you want to use -11 position data, you need to find a pattern for each position.\n# after that, you should change -11 position data with the most matched pattern values.\n\n_=plt.hist(big_data.displayed_position)\n_=plt.title(\"displayed_position\")\n_=plt.xlabel(\"position\")\n_=plt.ylabel(\"frequency\")\nplt.show();\n\n\n# In[25]:\n\n\n# min arrival_days should be 0, the negative values are meaningless. \n# -1 value frequency is very small into the arrival_days column.\n# Then it does not affect our analysis and I can ignore and also I don't need to use it for analysis.\n\n_=plt.hist(big_data.arrival_days)\n_=plt.title(\"arrival days\")\n_=plt.xlabel(\"days\")\n_=plt.ylabel(\"frequency\")\nplt.show();\n\n\n# In[26]:\n\n\n# min departure_days should be 0, the negative values are meaningless. \n# -1000000 value frequency is too small.\n# Then it does not affect our analysis and I can ignore and also I don't need to use it for analysis.\n\n# but if you want to use this data, you can do analysis with other columns and try to find a pattern by this means \n# you can update the correct value. For example, departure_days = -1000000 we can use 0 instead of -1000000.\n\n# in addition to that, you can create insight based on user behavior. \n# thanks to behavior analysis, you can change with an ideal value\n\n_=plt.hist(big_data.departure_days)\n_=plt.title(\"departure days\")\n_=plt.xlabel(\"days\")\n_=plt.ylabel(\"frequency\")\nplt.show();\n\n\n# ###### 2-Which search type has the lowest average displayed position? What is the best sorting order for this search type? Which search type should be excluded for a statistical reason?\n\n# In[27]:\n\n\n# average displayed position according to search type\nsearch_type = big_data[(big_data.displayed_position != -11)].groupby('search_type').agg({\"displayed_position\": \"sum\", \n \"search_type\": \"count\"})\nsearch_type.columns = ['sum_displayed_position', 'count_search_type']\nsearch_type[\"average_displayed_position\"] = search_type.sum_displayed_position/search_type.count_search_type\nsearch_type.sort_values(by=[\"average_displayed_position\"])\n\nlogging.debug('calculate average displayed position according to search type')\n\n\n# ###### What is the best sorting order for this search type?\n\n# In[28]:\n\n\n# best sorting order according to this search type\nsorting_order = big_data[(big_data.displayed_position != -11) & (big_data.search_type == 2116)].groupby('sort_order').agg({\"sort_order\": \"count\"})\nsorting_order.columns = ['count_sort_order']\nsorting_order.sort_values(by=[\"count_sort_order\"], ascending=False)\n\nlogging.debug('calculate best sorting order according to this search type')\n\n\n# ###### Which search type should be excluded for a statistical reason?\n\n# In[29]:\n\n\n# Normally, we can decide to exclude search_id=2100. \n# Because the search is done for two times using this type by users. It is too small.\n# But we have to demonstrate as statistically.\n# I want to use a confidence interval for deciding the importance level.\n\n# check current dataset distribution\n_=sns.distplot(search_type.count_search_type, \n hist=True, kde=True, color='darkblue', \n hist_kws={'edgecolor':'black'}, \n kde_kws={'linewidth': 3})\n\n\n# In[30]:\n\n\n# I apply the central limit theorem to convert it to Gauss distribution \n# because now our dataset doesn't have a normal distribution.\n\nbs_search = np.array([])\nfor i in range(100000):\n bs_search = np.append(bs_search, np.mean(np.random.choice(search_type.count_search_type, \n replace=True, size=len(search_type))))\n\nprint(\"\")\nprint(\"\")\nconf_int_search = np.percentile(bs_search, [2.5, 97.5])\nprint(\"confidence interval for p=0.05 : \",conf_int_search)\nprint(\"\")\nprint(\"search_type_2100_frequency : \",2)\nprint(\"\")\nprint(\"search_type_2113_frequency : \",854294)\nprint(\"\")\nprint(\"\")\nprint(\"search_type_2100 and search_type_2113 are out of confidence interval, because of their frequency\")\nprint(\"\")\nprint(\"bigger frequency is the desired result, the opposite way smaller frequency is the undesired result\")\nprint(\"\")\nprint(\"big frequency means that this search type is used by the user, otherwise small frequency is not\")\nprint(\"\")\nprint(\"\")\nprint(\"so we should exclude search_type_2100\")\nprint(\"\")\nprint(\"\")\n\n# plot normal distributed dataset\n_=sns.distplot(bs_search, \n hist=True, kde=True, color='darkblue', \n hist_kws={'edgecolor':'black'}, \n kde_kws={'linewidth': 3})\n_=plt.axvline(conf_int_search[0], color='red', linestyle='dashed', linewidth=2)\n_=plt.axvline(conf_int_search[1], color='red', linestyle='dashed', linewidth=2)\nplt.show()\n\n\n# ###### 3-What are the top 10 “best” and “worst” performing items? Explain what metric you have chosen to evaluate the performance and why.\n\n# -Best performed hotel is the most chosen hotel. This means that is many people have chosen it.\n# -So, I think that the most important criteria are the number of clicks.\n# -Contrary to best performance criteria, the worst performance hotel is the least chosen hotel. \n# \n# -But we have many hotels one-clicked. Therefore, we should do extra analysis together with other columns.\n# -For example, all columns values seem perfect but it still is one-clicked, so in this case, shows us this type of hotels is worst than the other one-clicked hotels. For this analysis, we should use \"displayed_position\" and \"page number\". In addition to that, we can use \"search type\" and \"sort_order\" values.\n# \n# -I calculated the coefficient for each column in order to measure hotel performance.\n\n# In[31]:\n\n\n# the top 10 best and worst hotels\n\n# calculate displayed_position coefficient\ndisp = pd.DataFrame(big_data[(big_data.displayed_position != -11)].groupby('displayed_position').agg({\"displayed_position\": \"count\"}))\ndisp.columns=[\"displayed_position_count\"]\ndisp_coeff = disp[\"displayed_position_count\"].sum()\ndisp[\"disp_coefficient\"] = disp_coeff / disp[\"displayed_position_count\"]\ndisp.index = disp.index + 1\n\n# calculate page_num coefficient\npage = pd.DataFrame(big_data[(big_data.displayed_position != -11)].groupby('page_num').agg({\"page_num\": \"count\"}))\npage.columns=[\"page_num_count\"]\npage_coeff = page[\"page_num_count\"].sum()\npage[\"page_coefficient\"] = page_coeff / page[\"page_num_count\"]\npage.index = page.index + 1\n\n# calculate sort_order coefficient\nsort = pd.DataFrame(big_data[(big_data.displayed_position != -11)].groupby('sort_order').agg({\"sort_order\": \"count\"}))\nsort.columns=[\"sort_order_count\"]\nsort_coeff = sort[\"sort_order_count\"].sum()\nsort[\"sort_coefficient\"] = sort[\"sort_order_count\"] / sort_coeff\nsort.index = sort.index + 1\n\n# calculate search_type coefficient\nsearch = pd.DataFrame(big_data[(big_data.displayed_position != -11)].groupby('search_type').agg({\"search_type\": \"count\"}))\nsearch.columns=[\"search_type_count\"]\nsearch_coeff = search[\"search_type_count\"].sum()\nsearch[\"search_coefficient\"] = search[\"search_type_count\"] / search_coeff\n\nclicked_hotel = big_data\nclicked_hotel.drop(clicked_hotel[clicked_hotel['displayed_position'] == -11].index , inplace=True)\n\nclicked_hotel[[\"displayed_position\", \"page_num\", \"sort_order\"]] = pd.DataFrame(clicked_hotel[[\"displayed_position\", \n \"page_num\",\"sort_order\"]].add(1))\n\nclicked_hotel = pd.merge(clicked_hotel, disp[[\"disp_coefficient\"]], on=\"displayed_position\", how=\"left\")\nclicked_hotel = pd.merge(clicked_hotel, page[[\"page_coefficient\"]], on=\"page_num\", how=\"left\")\nclicked_hotel = pd.merge(clicked_hotel, search[[\"search_coefficient\"]], on=\"search_type\", how=\"left\")\nclicked_hotel = pd.merge(clicked_hotel, sort[[\"sort_coefficient\"]], on=\"sort_order\", how=\"left\")\n\nclicked_hotel[\"performance_value\"] = (clicked_hotel[(\"disp_coefficient\")] * \n clicked_hotel[(\"page_coefficient\")] * \n clicked_hotel[(\"search_coefficient\")] * \n clicked_hotel[(\"sort_coefficient\")])\n\nclicked_hotel = clicked_hotel.groupby('clicked_item_id').agg({\"displayed_position\": \"sum\",\n \"page_num\": \"sum\",\n \"clicked_item_id\": \"count\",\n \"performance_value\": \"sum\",\n \"search_type\": \"sum\",\n \"sort_order\": \"sum\"})\n\ntotal_performance = clicked_hotel.performance_value.sum()\n\nclicked_hotel.columns = [\"sum_displayed_position\", \"sum_page_num\", \"count_item\", \n \"performance\", \"sum_search_type\", \"sum_sort_order\"]\nclicked_hotel[\"average_page_number\"] = clicked_hotel.sum_page_num/clicked_hotel.count_item\nclicked_hotel[\"average_displayed_position\"] = clicked_hotel.sum_displayed_position/clicked_hotel.count_item\nclicked_hotel[\"average_search_type\"] = clicked_hotel.sum_search_type/clicked_hotel.count_item\nclicked_hotel[\"average_sort_order\"] = clicked_hotel.sum_sort_order/clicked_hotel.count_item\nclicked_hotel[\"performance\"] = clicked_hotel.performance / total_performance\n\n# the top 10 best hotels\nprint(\"\")\nprint(\"\")\nprint(\"**********************\")\nprint(\"\")\nprint(\"\")\nprint(\"the top 10 best hotels\")\nclicked_hotel.sort_values(by=[\"performance\"], ascending=False).head(10)\n\n# the top 10 worst hotels\nprint(\"\")\nprint(\"\")\nprint(\"**********************\")\nprint(\"\")\nprint(\"\")\nprint(\"the top 10 worst hotels\")\nclicked_hotel.sort_values(by=[\"performance\"], ascending=True).head(10)\n\nlogging.debug('find the top 10 best and worst hotels')\n\n\n# ###### 4-Describe and visualise the relationship between the average displayed position and the CTR among the top 1000 most clicked items.\n\n# In[32]:\n\n\n# step one-prepare dataframe for description and visualization relationship between avg_disp_pos and CTR\n\n# most_clicked_hotels dataframe\nmost_clicked_hotels = big_data[(big_data.displayed_position != -11)].groupby('clicked_item_id').agg({\"clicked_item_id\":\"count\",\n \"displayed_position\": \"sum\"})\nmost_clicked_hotels.columns = [\"count_clicked_items\", \"sum_displayed_position\"]\n\nmost_clicked_hotels = (most_clicked_hotels.sort_values(by=[\"count_clicked_items\"], ascending=False).\n nlargest(columns=[\"count_clicked_items\"], n=1000))\n\nmost_clicked_hotels[\"avg_displayed_position\"] = (most_clicked_hotels.sum_displayed_position / \n most_clicked_hotels.count_clicked_items)\n\nmost_clicked_hotels.head(5)\n\n# click through rates dataframe\nctr = impressed_item_ids_distr.to_frame()\nctr.columns = [\"count_imp_item\"]\nctr.index.names = ['imp_item_id']\nctr.head(5)\n\n# join the dataframes\nmost_clicked_hotels = most_clicked_hotels.join(ctr, lsuffix='_x', rsuffix='_y')\nmost_clicked_hotels.head(5)\n\n# calculate CTR\nmost_clicked_hotels[\"CTR\"] = most_clicked_hotels.count_clicked_items / most_clicked_hotels.count_imp_item\nmost_clicked_hotels.head(5)\n\n\n# In[33]:\n\n\n# step two-describe and visualise relationship between avg_disp_pos and CTR\n\n# correlation coefficient\ncorr_ctr_disp = {'avg_displayed_position' : most_clicked_hotels.avg_displayed_position, 'ctr' : most_clicked_hotels.CTR}\ncorr_ctr_disp = pd.DataFrame(corr_ctr_disp)\n\npd.set_option('precision', 5)\ncorr_coeff = corr_ctr_disp.corr(method='pearson')\n\nprint('')\nprint('')\nprint('')\nprint('*********************')\nprint('correlation table')\ncorr_ctr_disp.head(5)\n\nprint('')\nprint('')\nprint('')\nprint('*********************')\nprint('correlation coefficient')\ncorr_coeff\n\nprint('')\nprint('')\nprint('')\nfig = plt.figure(figsize=(12,5))\n_=plt.scatter(corr_ctr_disp.avg_displayed_position, corr_ctr_disp.ctr)\n_=plt.xlabel('avg_displayed_position')\n_=plt.ylabel('CTR')\n_=plt.title('avg_disp_pos & CTR')\nplt.show();\n\nprint('')\nprint('')\nprint('')\ncolormap = sns.diverging_palette(210, 20, as_cmap=True)\n_=sns.heatmap(corr_coeff, cmap=colormap, annot=True, fmt=\".2f\")\n_=plt.xticks(range(len(corr_coeff.columns)), corr_coeff.columns)\n_=plt.yticks(range(len(corr_coeff.columns)), corr_coeff.columns)\nplt.show();\n\nlogging.debug('correlation')\n\n","repo_name":"MHMTCLK/Data_Analyst_Search","sub_path":"MahmutCOLAK_DataAnalyst_Search.py","file_name":"MahmutCOLAK_DataAnalyst_Search.py","file_ext":"py","file_size_in_byte":28621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"4592448095","text":"# 类的基本作用:封装\n# 类是现实世界或思维世界中的实体在计算机中的反映\n# 它将数据以及这些数据上的操作封装在一起\n# 类 - > 类变量\n# 实例 - > 实例变量\nclass Student():\n\n name = 'skyl'\n age = 0\n sum = 0\n score = 0 \n # 私有成员变量\n __scr = 0\n # 实例方法\n def __init__(self,name,age):\n # 构造函数\n # 初始化对象的属性\n self.name = name\n self.age = age\n # print(age)\n # print(name)\n self.__class__.sum +=1\n print('当前班级学生总数为:'+str(self.__class__.sum))\n\n def print_file(self):\n print('name: '+self.name)\n print('age: '+str(self.age))\n\n #私有方法\n def __print_file_private(self):\n print('name: '+self.name)\n print('age: '+str(self.age))\n\n #类方法\n @classmethod\n def plus_sum(cls):\n cls.sum +=1 \n print(cls.sum)\n\n @staticmethod\n def add(x,y):\n print('This is a static method')\n\n def marking(self,score):\n self.score = score;\n print(self.name)\n\n\n\n# 类的实例化\nstudent = Student('xiao',18)\n# student2 = Student('da',118)\nStudent.plus_sum()\nstudent.print_file()\n# student2.print_file()\n# print(Student.name)\nprint(student.__dict__)\n\nstudent2 = Student('zhong', 19)\nStudent.plus_sum()\nstudent3 = Student('da', 20)\nStudent.plus_sum()\nstudent3.marking(59)\n\n\n\n\n\n\n\n ","repo_name":"NewPracticer/python_study_route","sub_path":"d/c15.py","file_name":"c15.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"20385997571","text":"# 727D: T-Shirts Distribution\n\ndef solve(n, sizes, allocation, demands):\n for i in range(n):\n curr = input()\n if len(curr.split(',')) == 1:\n if sizes[curr] > 0:\n sizes[curr] -= 1\n allocation[i] = curr\n else:\n return False\n else:\n demands[curr].append(i)\n\n for demand, people in demands.items():\n poss_1, poss_2 = demand.split(',')\n for i in range(len(people)):\n if sizes[poss_1] > 0:\n sizes[poss_1] -= 1\n allocation[people[i]] = poss_1\n elif sizes[poss_2] > 0:\n sizes[poss_2] -= 1\n allocation[people[i]] = poss_2\n else:\n return False\n return True\n\ns, m, l, xl, xxl, xxxl = map(int, input().split())\nn = int(input())\n\nsizes = { 'S': s, 'M': m, 'L': l, 'XL': xl, 'XXL': xxl, 'XXXL': xxxl }\nallocation = ['' for _ in range(n)]\ndemands = { 'S,M': [], 'M,L': [], 'L,XL': [], 'XL,XXL': [], 'XXL,XXXL': [] }\n\nif not solve(n, sizes, allocation, demands):\n print('NO')\nelse:\n print('YES')\n for a in allocation:\n print(a)","repo_name":"JRobsonJr/Codeforces","sub_path":"0727D.py","file_name":"0727D.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"23023741677","text":"# -*- coding: utf-8 -*-\nfrom Acquisition import aq_chain\nfrom five import grok\n\nfrom genweb.serveistic.content.serveitic import IServeiTIC\nfrom zope.lifecycleevent.interfaces import IObjectModifiedEvent\nfrom Products.CMFCore.utils import getToolByName\n\n\ndef Added(content, event):\n \"\"\" MAX hooks main handler \"\"\"\n\n servei = findContainerServei(content)\n if not servei:\n # If file we are creating is not inside a servei folder\n return\n\n servei_tags = servei.subject\n addTagsToObject(servei_tags, content)\n\n\n@grok.subscribe(IServeiTIC, IObjectModifiedEvent)\ndef serveiModifyAddSubjects(content, event):\n \"\"\" Servei modified handler \"\"\"\n\n pc = getToolByName(content, \"portal_catalog\")\n servei_tags = content.subject\n path = \"/\".join(content.getPhysicalPath())\n r_results = pc.searchResults(portal_type=('Document', 'Link', 'File'),\n path=path)\n\n for brain in r_results:\n obj = brain.getObject()\n addTagsToObject(servei_tags, obj)\n\n content.es_faceta_1 = content.ca_faceta_1\n content.en_faceta_1 = content.ca_faceta_1\n\n content.es_faceta_2 = content.ca_faceta_2\n content.en_faceta_2 = content.ca_faceta_2\n\n content.es_faceta_3 = content.ca_faceta_3\n content.en_faceta_3 = content.ca_faceta_3\n\n content.es_faceta_4 = content.ca_faceta_4\n content.en_faceta_4 = content.ca_faceta_4\n\n content.es_faceta_5 = content.ca_faceta_5\n content.en_faceta_5 = content.ca_faceta_5\n\n content.es_faceta_6 = content.ca_faceta_6\n content.en_faceta_6 = content.ca_faceta_6\n\n content.es_faceta_7 = content.ca_faceta_7\n content.en_faceta_7 = content.ca_faceta_7\n\n content.es_faceta_8 = content.ca_faceta_8\n content.en_faceta_8 = content.ca_faceta_8\n\n content.reindexObject()\n\n\n# --------------- helpers ---------------\n\ndef addTagsToObject(servei_tags, obj):\n tags = []\n object_tags = list(obj.subject)\n [tags.append(tag) for tag in servei_tags if tag not in object_tags]\n obj.subject = tuple(sum([object_tags, tags], []))\n obj.reindexObject()\n\n\ndef findContainerServei(content):\n for parent in aq_chain(content):\n if IServeiTIC.providedBy(parent):\n return parent\n\n return None\n","repo_name":"UPCnet/genweb.serveistic","sub_path":"genweb/serveistic/hooks.py","file_name":"hooks.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"42928875493","text":"import os\nimport geopandas as gpd\nfrom sentinelhub import CRS, BBox\nfrom os import listdir\nfrom os.path import isdir, join\nfrom eolearn.core import EOPatch\nimport random\n\n\ndef chunkIt(seq, num):\n avg = len(seq) / float(num)\n out = []\n last = 0.0\n\n while last < len(seq):\n out.append(seq[int(last):int(last + avg)])\n last += avg\n\n return out\n\ndef get_year(date_string):\n \"\"\"Date input format: '2017-03-01' YYYY-MM-DD \"\"\"\n return str(date_string[:4])\n\ndef get_month(date_string):\n \"\"\"Date input format: '2017-03-01' YYYY-MM-DD \"\"\"\n return str(date_string[5:7])\n\ndef get_day(date_string):\n \"\"\"Date input format: '2017-03-01' YYYY-MM-DD \"\"\"\n return str(date_string[8:10])\n\ndef load_all_utm_zone_tiles(utm_zone, tile_size_in_km):\n \"\"\" This function loads all filed from a certain ymt zone \"\"\"\n data_dir = '../../data/utm_tile_division/{1}/all_tiles_{0:.0f}x{0:.0f}km.shp'.format(tile_size_in_km, utm_zone.name )\n return gpd.read_file(data_dir)\n\ndef get_selected_tiles(gdf, top_l_x, top_l_y, bot_r_x, bot_r_y, min_idx = 0, max_idx = 100000 ):\n \"\"\" This function returns list of indexes of tiles selected by a rectangle from provided tiles \"\"\"\n print('Original number of tiles:',len(gdf))\n \n selected_tiles_idxs_tmp = gdf[gdf['index_y'].between(bot_r_y, top_l_y, inclusive=True) ]\n print('After filtering all different Y indexes:',len(selected_tiles_idxs_tmp))\n selected_tiles_idxs_second_tmp = selected_tiles_idxs_tmp[selected_tiles_idxs_tmp['index_x'].between(top_l_x, bot_r_x, inclusive=True)]\n print('After filtering all different X indexes:',len(selected_tiles_idxs_second_tmp))\n selected_tiles_idxs_gdf = selected_tiles_idxs_second_tmp[selected_tiles_idxs_second_tmp['index'].between(min_idx, max_idx, inclusive=True)]\n print('After filtering all different utm indexes indexes:',len(selected_tiles_idxs_gdf))\n return selected_tiles_idxs_gdf\n\ndef save_selected_tiles_to_file(selected_tiles_gdf, tile_size_in_km, site_name, crs_zone ):\n \n selected_tiles_gdf.to_crs(crs={'init': CRS.ogc_string(crs_zone)}) # world.to_crs(epsg=3395) would also work\n directory_path = '../../data/selected_tiles/'+site_name+'/'+crs_zone.name\n if not os.path.isdir(directory_path):\n os.makedirs(directory_path)\n \n shapefile_filepath = directory_path+'/selected_tiles_{0:.0f}x{0:.0f}km.shp'.format(tile_size_in_km)\n selected_tiles_gdf.to_file(shapefile_filepath)\n print('File succesfully saved to:', shapefile_filepath ) \n return\n\ndef load_selected_tiles_from_file(site_name, crs_zone, tile_size_in_km=10 ):\n \"\"\"To produce a string and loads selected patches determined by site name tile size and crs zone if saved before\"\"\"\n directory_path = '../../data/selected_tiles/'+site_name+'/'+crs_zone.name\n shapefile_filepath = directory_path+'/selected_tiles_{0:.0f}x{0:.0f}km.shp'.format(tile_size_in_km)\n\n if os.path.isfile(shapefile_filepath):\n print (\"File exists\")\n else:\n print (\"Requested file does not exist\")\n print(shapefile_filepath)\n return \n return gpd.read_file(shapefile_filepath)\n\ndef get_eopatches_dir(data_product='LANDSAT_8', site_name='UPE_PROMICE', crs=CRS.UTM_22N, date_range=('2013-05-01', '2013-10-31') ):\n date_range_string = '{0}_{1}-{2}_{3}'.format(get_year(date_range[0]),get_month(date_range[0]),get_year(date_range[1]),get_month(date_range[1]))\n filepath = '../../data/EOPatches/{0}/{1}/{2}/{3}/'.format(data_product,site_name,crs.name, date_range_string)\n return filepath\n\ndef get_list_of_eopatches(filepath):\n \"\"\"Return list of folders names in requested directory\"\"\"\n onlyfiles = [f for f in listdir(filepath) if isdir(join(filepath, f))]\n return onlyfiles\n\ndef load_exemplary_eopatch(data_product='LANDSAT_8', date_range = ('2013-05-01', '2013-10-31'), patch_id = 5, random_choice=True ):\n eo_patch_dir = get_eopatches_dir(data_product=data_product, date_range=date_range)\n list_of_eo_patches = get_list_of_eopatches(eo_patch_dir)\n \n if list_of_eo_patches == 0:\n print('No patches found')\n return\n if random_choice == True:\n eo_patch_filename = random.choice(list_of_eo_patches)\n else:\n if patch_id < len(list_of_eo_patches):\n eo_patch_filename = list_of_eo_patches[patch_id]\n else:\n print('Index out of range')\n return\n final_eopatch_filepath = eo_patch_dir+eo_patch_filename\n print('Loaded from', final_eopatch_filepath)\n return EOPatch.load(final_eopatch_filepath)\n\n\n\ndef load_exemplary_MODIS_eopatch(data_product='MODIS', date_range = ('2013-04-26', '2013-11-05'), patch_id = 5, random_choice=True ):\n eo_patch_dir = get_eopatches_dir(data_product=data_product , date_range=date_range)\n list_of_eo_patches = get_list_of_eopatches(eo_patch_dir)\n \n if list_of_eo_patches == 0:\n print('No patches found')\n return\n if random_choice == True:\n eo_patch_filename = random.choice(list_of_eo_patches)\n else:\n if patch_id < len(list_of_eo_patches):\n eo_patch_filename = list_of_eo_patches[patch_id]\n else:\n print('Index out of range')\n return\n final_eopatch_filepath = eo_patch_dir+eo_patch_filename\n print('Loaded from', final_eopatch_filepath)\n return EOPatch.load(final_eopatch_filepath)\n\n\n\ndef load_exemplary_eopatch_from_file(file , patch_id=6, random_choice=True ):\n list_of_eo_patches = get_list_of_eopatches(file)\n \n if list_of_eo_patches == 0:\n print('No patches found')\n return\n if random_choice == True:\n eo_patch_filename = random.choice(list_of_eo_patches)\n else:\n if patch_id < len(list_of_eo_patches):\n eo_patch_filename = list_of_eo_patches[patch_id]\n else:\n print('Index out of range')\n return\n final_eopatch_filepath = file+eo_patch_filename\n print('Loaded from', final_eopatch_filepath)\n return EOPatch.load(final_eopatch_filepath) \n ","repo_name":"kakacper1/Greenland-water_features_mapping","sub_path":"utils/io_functions.py","file_name":"io_functions.py","file_ext":"py","file_size_in_byte":6030,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"1707595141","text":"import logging\nimport os\nimport time\n\nimport numpy as np\nimport numpy.ma as ma\nfrom tqdm import tqdm\n\nimport torch\nimport torch.nn as nn\nimport torch.distributed as dist\nfrom torch.nn import functional as F\n\nfrom utils.utils import AverageMeter\nfrom utils.utils import get_confusion_matrix_gpu\nfrom utils.utils import adjust_learning_rate\nfrom utils.utils import get_world_size, get_rank\nfrom utils.modelsummary import get_model_summary\n\nimport pdb\nfrom PIL import Image\nimport cv2\nimport time\n\ndef reduce_tensor(inp):\n world_size = get_world_size()\n if world_size < 2:\n return inp\n with torch.no_grad():\n reduced_inp = inp\n dist.reduce(reduced_inp, dst=0)\n return reduced_inp\n\n\ndef train_ee(config, epoch, num_epoch, epoch_iters, base_lr, num_iters,\n trainloader, optimizer, model, writer_dict, device):\n \n model.train()\n torch.manual_seed(get_rank() + epoch * 123)\n\n if config.TRAIN.EE_ONLY or config.TRAIN.ALLE_ONLY:\n model.eval()\n model.module.model.exit1.train()\n model.module.model.exit2.train()\n model.module.model.exit3.train()\n if config.TRAIN.ALLE_ONLY:\n model.module.model.last_layer.train()\n\n\n data_time = AverageMeter()\n batch_time = AverageMeter()\n ave_loss = AverageMeter()\n \n tic_data = time.time()\n tic = time.time()\n tic_total = time.time()\n cur_iters = epoch*epoch_iters\n writer = writer_dict['writer']\n global_steps = writer_dict['train_global_steps']\n rank = get_rank()\n world_size = get_world_size()\n\n for i_iter, batch in enumerate(trainloader):\n data_time.update(time.time() - tic_data)\n\n\n images, labels, _, _ = batch\n images = images.to(device)\n labels = labels.long().to(device)\n\n losses, _ = model(images, labels)\n\n loss = 0\n reduced_losses = []\n for i, l in enumerate(losses):\n loss += config.MODEL.EXTRA.EE_WEIGHTS[i] * losses[i]\n reduced_losses.append(reduce_tensor(losses[i]))\n reduced_loss = reduce_tensor(loss)\n\n model.zero_grad()\n loss.backward()\n optimizer.step()\n\n\n ave_loss.update(reduced_loss.item())\n\n lr = adjust_learning_rate(optimizer,\n base_lr,\n num_iters,\n i_iter+cur_iters)\n\n batch_time.update(time.time() - tic)\n tic = time.time()\n\n\n if i_iter % config.PRINT_FREQ == 0 and rank == 0:\n\n print_loss = reduced_loss / world_size\n msg = 'Epoch: [{: >3d}/{}] Iter:[{: >3d}/{}], Time: {:.2f}, Data Time: {:.2f} ' \\\n 'lr: {:.6f}, Loss: {:.6f}' .format(\n epoch, num_epoch, i_iter, epoch_iters, \n batch_time.average(), data_time.average(), lr, print_loss)\n logging.info(msg)\n \n global_steps = writer_dict['train_global_steps']\n writer.add_scalar('train_loss', print_loss, global_steps)\n\n writer.add_scalars('exit_train_loss', {\n 'exit1': reduced_losses[0].item() / world_size,\n 'exit2': reduced_losses[1].item() / world_size,\n 'exit3': reduced_losses[2].item() / world_size,\n 'exit4': reduced_losses[3].item() / world_size,\n }, \n global_steps)\n\n writer_dict['train_global_steps'] += 1\n\n tic_data = time.time()\n\n train_time = time.time() - tic_total\n\n if rank == 0:\n logging.info(f'Train time:{train_time}s')\n\ndef validate_ee(config, testloader, model, writer_dict, device):\n\n torch.manual_seed(get_rank())\n \n tic_data = time.time()\n tic = time.time()\n tic_total = time.time()\n rank = get_rank()\n world_size = get_world_size()\n model.eval()\n\n data_time = AverageMeter()\n batch_time = AverageMeter()\n ave_loss = AverageMeter()\n\n num_exits = len(config.MODEL.EXTRA.EE_WEIGHTS)\n\n ave_losses = [AverageMeter() for i in range(num_exits)]\n\n confusion_matrices = [np.zeros((config.DATASET.NUM_CLASSES, config.DATASET.NUM_CLASSES)) for i in range(num_exits)]\n\n\n with torch.no_grad():\n for i_iter, batch in enumerate(testloader):\n data_time.update(time.time() - tic_data)\n\n image, label, _, _ = batch\n size = label.size()\n image = image.to(device)\n label = label.long().to(device)\n\n losses, preds = model(image, label)\n \n for i, pred in enumerate(preds):\n if pred.size()[-2] != size[-2] or pred.size()[-1] != size[-1]:\n pred = F.upsample(pred, (size[-2], size[-1]), \n mode='bilinear')\n\n confusion_matrices[i] += get_confusion_matrix_gpu(\n label,\n pred,\n size,\n config.DATASET.NUM_CLASSES,\n config.TRAIN.IGNORE_LABEL)\n\n loss = 0\n reduced_losses = []\n for i, l in enumerate(losses):\n loss += config.MODEL.EXTRA.EE_WEIGHTS[i] * losses[i]\n reduced_losses.append(reduce_tensor(losses[i]))\n ave_losses[i].update(reduced_losses[i].item())\n\n reduced_loss = reduce_tensor(loss)\n ave_loss.update(reduced_loss.item())\n\n batch_time.update(time.time() - tic)\n tic = time.time()\n\n tic_data = time.time()\n\n if i_iter % config.PRINT_FREQ == 0 and rank == 0:\n print_loss = ave_loss.average() / world_size \n msg = 'Iter:[{: >3d}/{}], Time: {:.2f}, Data Time: {:.2f} ' \\\n 'Loss: {:.6f}' .format(\n i_iter, len(testloader), batch_time.average(), data_time.average(), print_loss)\n logging.info(msg)\n\n\n results = []\n for i, confusion_matrix in enumerate(confusion_matrices):\n \n confusion_matrix = torch.from_numpy(confusion_matrix).to(device)\n reduced_confusion_matrix = reduce_tensor(confusion_matrix)\n confusion_matrix = reduced_confusion_matrix.cpu().numpy()\n\n pos = confusion_matrix.sum(1)\n res = confusion_matrix.sum(0)\n tp = np.diag(confusion_matrix)\n pixel_acc = tp.sum()/pos.sum()\n mean_acc = (tp/np.maximum(1.0, pos)).mean()\n IoU_array = (tp / np.maximum(1.0, pos + res - tp))\n mean_IoU = IoU_array.mean()\n\n results.append((mean_IoU, IoU_array, pixel_acc, mean_acc))\n\n val_time = time.time() - tic_total\n\n if rank == 0:\n logging.info(f'Validation time:{val_time}s')\n mean_IoUs = [result[0] for result in results]\n mean_IoUs.append(np.mean(mean_IoUs))\n print_result = '\\t'.join(['{:.2f}'.format(m*100) for m in mean_IoUs])\n logging.info(f'mean_IoUs: {print_result}')\n\n writer = writer_dict['writer']\n global_steps = writer_dict['valid_global_steps']\n writer.add_scalar('valid_loss', print_loss, global_steps)\n\n writer.add_scalars('exit_valid_loss', {\n 'exit1': ave_losses[0].average() / world_size,\n 'exit2': ave_losses[1].average() / world_size,\n 'exit3': ave_losses[2].average() / world_size,\n 'exit4': ave_losses[3].average() / world_size,\n }, \n global_steps)\n\n writer.add_scalars('valid_mIoUs',\n {f'valid_mIoU{i+1}': results[i][0] for i in range(num_exits)}, \n global_steps\n )\n writer_dict['valid_global_steps'] += 1\n\n return results\n\n\nVIS_T = False\nVIS = False\nVIS_CONF = False\nTIMING = True\n\ndef testval_ee(config, test_dataset, testloader, model, \n sv_dir='', sv_pred=False):\n model.eval()\n torch.manual_seed(get_rank())\n num_exits = len(config.MODEL.EXTRA.EE_WEIGHTS)\n\n confusion_matrices = [np.zeros((config.DATASET.NUM_CLASSES, config.DATASET.NUM_CLASSES)) for i in range(num_exits)]\n\n total_time = 0\n\n with torch.no_grad():\n for index, batch in enumerate(tqdm(testloader)):\n image, label, _, name = batch\n if config.PYRAMID_TEST.USE:\n image = F.interpolate(image, (config.PYRAMID_TEST.SIZE//2, config.PYRAMID_TEST.SIZE), mode='bilinear')\n\n size = label.size()\n\n if TIMING:\n start = time.time()\n torch.cuda.synchronize()\n preds = model(image)\n\n if TIMING:\n torch.cuda.synchronize()\n total_time += time.time() - start\n \n for i, pred in enumerate(preds):\n if pred.size()[-2] != size[-2] or pred.size()[-1] != size[-1]:\n original_logits = pred\n pred = F.upsample(pred, (size[-2], size[-1]), \n mode='bilinear')\n\n confusion_matrices[i] += get_confusion_matrix_gpu(\n label,\n pred,\n size,\n config.DATASET.NUM_CLASSES,\n config.TRAIN.IGNORE_LABEL)\n\n if sv_pred and index % 20 == 0 and VIS:\n print(\"Saving ... \", name)\n sv_path = os.path.join(sv_dir, f'test_val_results/{i+1}')\n os.makedirs(sv_path, exist_ok=True)\n test_dataset.save_pred(pred, sv_path, name)\n\n if VIS_T or VIS_CONF:\n def save_float_img(t, sv_path, name, normalize=False):\n os.makedirs(sv_path, exist_ok=True)\n if normalize:\n t = t/t.max()\n torch.save(t, os.path.join(sv_path, name[0]+'.pth'))\n t = t[0][0]\n t = t.cpu().numpy().copy()\n np.save(os.path.join(sv_path, name[0]+'.npy'), t)\n cv2.imwrite(os.path.join(sv_path, name[0]+'.png'), t*255)\n\n def save_long_img(t, sv_path, name):\n os.makedirs(sv_path, exist_ok=True)\n t = t[0][0]\n t = t.cpu().numpy().copy()\n cv2.imwrite(os.path.join(sv_path, name[0]+'.png'), t)\n\n def save_tensor(t, sv_path, name):\n os.makedirs(sv_path, exist_ok=True)\n torch.save(t, os.path.join(sv_path, name[0]+'.pth'))\n\n\n if VIS_CONF:\n\n out = F.softmax(original_logits, dim=1)\n\n sv_path = os.path.join(sv_dir, f'test_val_original_conf/{i+1}')\n original_conf_map, _ = out.max(dim=1)\n save_float_img(original_conf_map.unsqueeze(0), sv_path, name, normalize=False)\n\n sv_path = os.path.join(sv_dir, f'test_val_original_pred/{i+1}')\n max_index = torch.max(out, dim=1)[1]\n save_long_img(max_index.unsqueeze(0), sv_path, name)\n\n sv_path = os.path.join(sv_dir, f'test_val_original_logits/{i+1}')\n save_tensor(original_logits, sv_path, name)\n\n sv_path = os.path.join(sv_dir, f'test_val_original_results/{i+1}')\n os.makedirs(sv_path, exist_ok=True)\n test_dataset.save_pred(original_logits, sv_path, name)\n\n if hasattr(model.module, 'mask_dict'):\n sv_path = os.path.join(sv_dir, f'test_val_masks/')\n os.makedirs(sv_path, exist_ok=True)\n torch.save(model.module.mask_dict, os.path.join(sv_path, name[0]+'.pth'))\n\n if i == 0:\n sv_path = os.path.join(sv_dir, f'test_val_gt/')\n save_long_img(label.unsqueeze(0), sv_path, name)\n if index % 100 == 0:\n logging.info(f'processing: {index} images with exit {i}')\n pos = confusion_matrices[i].sum(1)\n res = confusion_matrices[i].sum(0)\n tp = np.diag(confusion_matrices[i])\n IoU_array = (tp / np.maximum(1.0, pos + res - tp))\n mean_IoU = IoU_array.mean()\n logging.info('mIoU: %.4f' % (mean_IoU))\n\n results = []\n for i, confusion_matrix in enumerate(confusion_matrices):\n pos = confusion_matrix.sum(1)\n res = confusion_matrix.sum(0)\n tp = np.diag(confusion_matrix)\n pixel_acc = tp.sum()/pos.sum()\n mean_acc = (tp/np.maximum(1.0, pos)).mean()\n IoU_array = (tp / np.maximum(1.0, pos + res - tp))\n mean_IoU = IoU_array.mean()\n\n results.append((mean_IoU, IoU_array, pixel_acc, mean_acc))\n\n if TIMING:\n print(\"Total_time\", total_time)\n\n return results\n\n\ndef testval_ee_class(config, test_dataset, testloader, model, \n sv_dir='', sv_pred=False):\n model.eval()\n torch.manual_seed(get_rank())\n num_exits = len(config.MODEL.EXTRA.EE_WEIGHTS)\n\n confusion_matrices = [np.zeros((config.DATASET.NUM_CLASSES, config.DATASET.NUM_CLASSES)) for i in range(num_exits)]\n\n total_time = 0\n\n with torch.no_grad():\n for index, batch in enumerate(tqdm(testloader)):\n image, label, _, name = batch\n\n size = label.size()\n preds = model(image)\n \n for i, pred in enumerate(preds):\n if pred.size()[-2] != size[-2] or pred.size()[-1] != size[-1]:\n original_logits = pred\n pred = F.upsample(pred, (size[-2], size[-1]), \n mode='bilinear')\n\n confusion_matrices[i] += get_confusion_matrix_gpu(\n label,\n pred,\n size,\n config.DATASET.NUM_CLASSES,\n config.TRAIN.IGNORE_LABEL)\n\n if sv_pred and index % 20 == 0 and VIS:\n print(\"Saving ... \", name)\n sv_path = os.path.join(sv_dir, f'test_val_results/{i+1}')\n os.makedirs(sv_path, exist_ok=True)\n test_dataset.save_pred(pred, sv_path, name)\n\n if VIS_T or VIS_CONF:\n def save_float_img(t, sv_path, name, normalize=False):\n os.makedirs(sv_path, exist_ok=True)\n if normalize:\n t = t/t.max()\n torch.save(t, os.path.join(sv_path, name[0]+'.pth'))\n t = t[0][0]\n t = t.cpu().numpy().copy()\n np.save(os.path.join(sv_path, name[0]+'.npy'), t)\n cv2.imwrite(os.path.join(sv_path, name[0]+'.png'), t*255)\n\n def save_long_img(t, sv_path, name):\n os.makedirs(sv_path, exist_ok=True)\n t = t[0][0]\n t = t.cpu().numpy().copy()\n cv2.imwrite(os.path.join(sv_path, name[0]+'.png'), t)\n\n def save_tensor(t, sv_path, name):\n os.makedirs(sv_path, exist_ok=True)\n torch.save(t, os.path.join(sv_path, name[0]+'.pth'))\n if VIS_CONF:\n out = F.softmax(original_logits, dim=1)\n\n sv_path = os.path.join(sv_dir, f'test_val_original_conf/{i+1}')\n original_conf_map, _ = out.max(dim=1)\n save_float_img(original_conf_map.unsqueeze(0), sv_path, name, normalize=False)\n\n sv_path = os.path.join(sv_dir, f'test_val_original_pred/{i+1}')\n max_index = torch.max(out, dim=1)[1]\n save_long_img(max_index.unsqueeze(0), sv_path, name)\n\n sv_path = os.path.join(sv_dir, f'test_val_original_logits/{i+1}')\n save_tensor(original_logits, sv_path, name)\n\n sv_path = os.path.join(sv_dir, f'test_val_original_results/{i+1}')\n os.makedirs(sv_path, exist_ok=True)\n test_dataset.save_pred(original_logits, sv_path, name)\n\n if hasattr(model.module, 'mask_dict'):\n sv_path = os.path.join(sv_dir, f'test_val_masks/')\n os.makedirs(sv_path, exist_ok=True)\n torch.save(model.module.mask_dict, os.path.join(sv_path, name[0]+'.pth'))\n\n if i == 0:\n sv_path = os.path.join(sv_dir, f'test_val_gt/')\n save_long_img(label.unsqueeze(0), sv_path, name)\n\n if index % 100 == 0:\n logging.info(f'processing: {index} images with exit {i}')\n pos = confusion_matrices[i].sum(1)\n res = confusion_matrices[i].sum(0)\n tp = np.diag(confusion_matrices[i])\n IoU_array = (tp / np.maximum(1.0, pos + res - tp))\n mean_IoU = IoU_array.mean()\n logging.info('mIoU: %.4f' % (mean_IoU))\n\n results = []\n for i, confusion_matrix in enumerate(confusion_matrices):\n pos = confusion_matrix.sum(1)\n res = confusion_matrix.sum(0)\n tp = np.diag(confusion_matrix)\n pixel_acc = tp.sum()/pos.sum()\n mean_acc = (tp/np.maximum(1.0, pos)).mean()\n IoU_array = (tp / np.maximum(1.0, pos + res - tp))\n mean_IoU = IoU_array.mean()\n\n results.append((mean_IoU, IoU_array, pixel_acc, mean_acc))\n\n if TIMING:\n print(\"Total_time\", total_time)\n\n return results\ndef testval_ee_profiling(config, test_dataset, testloader, model, \n sv_dir='', sv_pred=False):\n model.eval()\n torch.manual_seed(get_rank())\n num_exits = len(config.MODEL.EXTRA.EE_WEIGHTS)\n total_time = 0\n\n gflops = []\n with torch.no_grad():\n for index, batch in enumerate(tqdm(testloader)):\n image, label, _, name = batch\n if config.PYRAMID_TEST.USE:\n image = F.interpolate(image, (config.PYRAMID_TEST.SIZE, config.PYRAMID_TEST.SIZE//2), mode='bilinear')\n stats = {}\n saved_stats = {}\n\n for i in range(4):\n setattr(model.module, f\"stop{i+1}\", \"anY_RanDOM_ThiNg\")\n summary, stats[i+1] = get_model_summary(model, image, verbose=False)\n delattr(model.module, f\"stop{i+1}\")\n\n saved_stats['params'] = [stats[i+1]['params'] for i in range(4)]\n saved_stats['flops'] = [stats[i+1]['flops'] for i in range(4)]\n saved_stats['counts'] = [stats[i+1]['counts'] for i in range(4)]\n saved_stats['Gflops'] = [f/(1024**3) for f in saved_stats['flops']]\n saved_stats['Mparams'] = [f/(10**6) for f in saved_stats['params']]\n gflops.append(saved_stats['Gflops'])\n\n final_stats = saved_stats\n final_stats['Gflops'] = []\n for i in range(4):\n final_stats['Gflops'].append(np.mean([x[i] for x in gflops]))\n final_stats['Gflops_mean'] = np.mean(final_stats['Gflops'])\n return final_stats\n\ndef testval_ee_profiling_actual(config, test_dataset, testloader, model, \n sv_dir='', sv_pred=False):\n model.eval()\n torch.manual_seed(get_rank())\n num_exits = len(config.MODEL.EXTRA.EE_WEIGHTS)\n total_time = 0\n\n stats = {}\n stats['time'] = {}\n times = []\n\n with torch.no_grad():\n for index, batch in enumerate(tqdm(testloader)):\n image, label, _, name = batch\n t = []\n for i in range(4):\n if isinstance(model, nn.DataParallel):\n setattr(model.module, f\"stop{i+1}\", \"anY_RanDOM_ThiNg\")\n else:\n setattr(model, f\"stop{i+1}\", \"anY_RanDOM_ThiNg\")\n\n torch.cuda.synchronize()\n start = time.time()\n out = model(image)\n torch.cuda.synchronize()\n t.append(time.time() - start)\n\n if isinstance(model, nn.DataParallel):\n delattr(model.module, f\"stop{i+1}\")\n else:\n delattr(model, f\"stop{i+1}\")\n\n if index > 5:\n times.append(t)\n if index > 20:\n break\n\n print(t)\n for i in range(4):\n stats['time'][i] = np.mean([t[i] for t in times])\n print(stats) \n return stats\n","repo_name":"liuzhuang13/anytime","sub_path":"lib/core/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":20755,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"77"}
+{"seq_id":"22301503573","text":"import pandas as pd\nimport os\n# import time\nfrom data_analysis.util.Util import Util\n\n\nclass SaveUtil(Util):\n # 存储以及恢复数据的时间频率\n MONTHLY = 1\n DAILY = 2\n # 该存储模式的意思是,由用户自己指定存储路径,上面MONTHLY和DAILY模式都是由系统指定的\n # 由用户指定的模式主要用在保存不同分析结果,由于分析结果的类型可以由config.json中配置\n # 所以为了保证系统的灵活性,这里就不直接使用if判断写死在系统中了\n SELF = 3\n\n # 恢复数据的类型\n CLEAN = 11\n LOW = 12\n HIGH = 13\n\n def __init__(self):\n super().__init__()\n\n def save_result(self, mode: int, file_name: str, data: pd.DataFrame, file_path: str = None):\n if mode == self.SELF and (not file_path == None):\n flag = os.path.exists(file_path)\n if not flag:\n os.makedirs(file_path)\n data.to_csv(file_path + file_name, encoding='utf_8_sig')\n elif mode == self.MONTHLY:\n flag = os.path.exists(self.monthly_result_path)\n if not flag:\n os.makedirs(self.monthly_result_path)\n data.to_csv(self.monthly_result_path + file_name, encoding='utf_8_sig')\n elif mode == self.DAILY:\n flag = os.path.exists(self.daily_result_path)\n if not flag:\n os.makedirs(self.daily_result_path)\n data.to_csv(self.daily_result_path + file_name, encoding='utf_8_sig')\n\n def restore_df(self, mode: int, data_type: int):\n df = pd.DataFrame\n if mode == self.MONTHLY:\n file_path = self.spider_monthly_result_path + \"user_info-\" + self.year + \"-\" + self.month + \".csv\"\n if not os.path.exists(file_path):\n print(\"not found monthly data\")\n else:\n df = pd.read_csv(file_path)\n elif mode == self.DAILY:\n if data_type == self.CLEAN:\n df = pd.read_csv(\n self.spider_daily_result_path + \"user_info-\" + self.year + \"-\" + self.month + \"-\" + self.day + \".csv\")\n elif data_type == self.LOW:\n df = pd.read_csv(\n self.spider_daily_result_path + \"user_info_low_cleaned.csv\")\n elif data_type == self.HIGH:\n df = pd.read_csv(\n self.spider_daily_result_path + \"user_info_high_cleaned.csv\")\n return df\n\n\nif __name__ == '__main__':\n s_u = SaveUtil()\n # print()\n","repo_name":"srx-2000/spider_collection","sub_path":"zhihu_user_info_spider/data_analysis/util/SaveUtil.py","file_name":"SaveUtil.py","file_ext":"py","file_size_in_byte":2516,"program_lang":"python","lang":"zh","doc_type":"code","stars":814,"dataset":"github-code","pt":"77"}
+{"seq_id":"31951967345","text":"from conan import ConanFile\nfrom conan.errors import ConanInvalidConfiguration\nfrom conan.tools.meson import Meson, MesonToolchain\nfrom conan.tools.gnu import PkgConfigDeps\nfrom conan.tools.scm import Version\nfrom conan.tools.env import VirtualBuildEnv\nfrom conan.tools.microsoft import is_msvc\nfrom conan.tools.files import apply_conandata_patches, copy, export_conandata_patches, rmdir, rename, get, rm, replace_in_file\nfrom conan.tools.build import cross_building, check_min_cppstd\nfrom conan.tools.layout import basic_layout\nimport shutil\nimport os\n\n\nrequired_conan_version = \">=1.53.0\"\n\n\nclass LibXMLPlusPlus(ConanFile):\n name = \"libxmlpp\"\n description = \"libxml++ (a.k.a. libxmlplusplus) provides a C++ interface to XML files\"\n license = \"LGPL-2.1\"\n url = \"https://github.com/conan-io/conan-center-index\"\n homepage = \"https://github.com/libxmlplusplus/libxmlplusplus\"\n topics = [\"xml\", \"parser\", \"wrapper\"]\n settings = \"os\", \"arch\", \"compiler\", \"build_type\"\n options = {\n \"shared\": [True, False],\n \"fPIC\": [True, False],\n }\n default_options = {\n \"shared\": False,\n \"fPIC\": True,\n }\n\n @property\n def _lib_version(self):\n return \"2.6\" if Version(self.version) <= \"2.42.1\" else \"5.0\"\n\n def export_sources(self):\n export_conandata_patches(self)\n\n def config_options(self):\n if self.settings.os == \"Windows\":\n del self.options.fPIC\n\n def configure(self):\n if self.options.shared:\n self.options.rm_safe(\"fPIC\")\n\n def layout(self):\n basic_layout(self, src_folder=\"src\")\n\n def requirements(self):\n self.requires(\"libxml2/2.11.4\")\n if Version(self.version) <= \"2.42.1\":\n self.requires(\"glibmm/2.66.4\", transitive_headers=True, transitive_libs=True)\n else:\n self.requires(\"glibmm/2.75.0\")\n\n def validate(self):\n if hasattr(self, \"settings_build\") and cross_building(self):\n raise ConanInvalidConfiguration(\"Cross-building not implemented\")\n if Version(self.version) < \"2.91.1\":\n from conan import conan_version\n import sys\n if conan_version.major == 2:\n # FIXME: linter complains, but function is there\n # https://docs.conan.io/2.0/reference/tools/build.html?highlight=check_min_cppstd#conan-tools-build-check-max-cppstd\n check_max_cppstd = getattr(sys.modules['conan.tools.build'], 'check_max_cppstd')\n # INFO: error: no template named 'auto_ptr' in namespace 'std'. Removed in C++17.\n check_max_cppstd(self, 14)\n if self.settings.compiler.get_safe(\"cppstd\"):\n check_min_cppstd(self, 11)\n\n def build_requirements(self):\n self.tool_requires(\"meson/1.2.1\")\n if not self.conf.get(\"tools.gnu:pkg_config\", check_type=str):\n self.tool_requires(\"pkgconf/2.0.3\")\n\n def source(self):\n get(self, **self.conan_data[\"sources\"][self.version],\n destination=self.source_folder, strip_root=True)\n\n def _patch_sources(self):\n apply_conandata_patches(self)\n\n if is_msvc(self):\n # when using cpp_std=c++NM the /permissive- flag is added which\n # attempts enforcing standard conformant c++ code. the problem is\n # that older versions of the Windows SDK isn't standard conformant!\n # see:\n # https://developercommunity.visualstudio.com/t/error-c2760-in-combaseapih-with-windows-sdk-81-and/185399\n replace_in_file(self,\n os.path.join(self.source_folder, \"meson.build\"),\n \"cpp_std=c++\", \"cpp_std=vc++\")\n\n def generate(self):\n virtual_build_env = VirtualBuildEnv(self)\n virtual_build_env.generate()\n tc = MesonToolchain(self)\n tc.project_options[\"build-examples\"] = \"false\"\n tc.project_options[\"build-tests\"] = \"false\"\n tc.project_options[\"build-documentation\"] = \"false\"\n tc.project_options[\"msvc14x-parallel-installable\"] = \"false\"\n tc.project_options[\"default_library\"] = \"shared\" if self.options.shared else \"static\"\n tc.generate()\n td = PkgConfigDeps(self)\n td.generate()\n\n def build(self):\n self._patch_sources()\n meson = Meson(self)\n meson.configure()\n meson.build()\n\n def package(self):\n copy(self, \"COPYING\", dst=os.path.join(self.package_folder, \"licenses\"), src=self.source_folder)\n meson = Meson(self)\n meson.install()\n\n shutil.move(\n os.path.join(self.package_folder, \"lib\", f\"libxml++-{self._lib_version}\", \"include\", \"libxml++config.h\"),\n os.path.join(self.package_folder, \"include\", f\"libxml++-{self._lib_version}\", \"libxml++config.h\"))\n\n rmdir(self, os.path.join(self.package_folder, \"lib\", \"pkgconfig\"))\n rmdir(self, os.path.join(self.package_folder, \"lib\", f\"libxml++-{self._lib_version}\"))\n\n if is_msvc(self):\n rm(self, \"*.pdb\", os.path.join(self.package_folder, \"bin\"))\n if not self.options.shared:\n rename(\n self,\n os.path.join(self.package_folder, \"lib\", f\"libxml++-{self._lib_version}.a\"),\n os.path.join(self.package_folder, \"lib\", f\"xml++-{self._lib_version}.lib\"))\n\n def package_info(self):\n self.cpp_info.set_property(\"cmake_module_file_name\", \"libxml++\")\n self.cpp_info.set_property(\"cmake_module_target_name\", \"libxml++::libxml++\")\n self.cpp_info.set_property(\"pkg_config_name\", \"libxml++\")\n self.cpp_info.components[f\"libxml++-{self._lib_version}\"].set_property(\"pkg_config_name\", f\"libxml++-{self._lib_version}\")\n self.cpp_info.components[f\"libxml++-{self._lib_version}\"].set_property(\"cmake_target_name\", f\"libxml++::libxml++-{self._lib_version}\")\n self.cpp_info.components[f\"libxml++-{self._lib_version}\"].libs = [f\"xml++-{self._lib_version}\"]\n self.cpp_info.components[f\"libxml++-{self._lib_version}\"].includedirs = [\n os.path.join(\"include\", f\"libxml++-{self._lib_version}\")\n ]\n self.cpp_info.components[f\"libxml++-{self._lib_version}\"].requires = [\n \"glibmm::glibmm\", \"libxml2::libxml2\"\n ]\n\n self.cpp_info.names[\"cmake_find_package\"] = \"libxml++\"\n self.cpp_info.names[\"cmake_find_package_multi\"] = \"libxml++\"\n","repo_name":"conan-io/conan-center-index","sub_path":"recipes/libxmlpp/2.x.x/conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":6407,"program_lang":"python","lang":"en","doc_type":"code","stars":835,"dataset":"github-code","pt":"77"}
+{"seq_id":"27653433429","text":"import sys\nimport sqlite3\nimport csv\n\n# GLOBALS\n# Program continues to run\nglobalFlag = True\n\n# Connects to database file\ndb = sqlite3.connect('SongsArtists.db')\n\n# Creates database cursor object\nc = db.cursor()\n\n\n# Main function\ndef main():\n # Tells user how to access commands for program\n sys.stdout.write(\"Welcome. Type 'help' for a full list of commands and correct syntax.\\n\")\n\n # Flag to end program\n global globalFlag\n while globalFlag:\n getInput()\n db.close()\n\n\n# Gets user input and passes to processInput()\ndef getInput():\n sys.stdout.write(\">>\")\n processInput(input())\n\n\n# Processes user input and looks for preset commands before sending to parser\ndef processInput(userInput):\n userInput = userInput.strip()\n if userInput.lower() == \"help\":\n help()\n elif userInput.lower() == \"exit\" or userInput.lower() == \"quit\":\n sys.stdout.write(\"Goodbye!\")\n global globalFlag\n globalFlag = False\n elif userInput.lower() == \"load data\":\n loadData()\n elif userInput.lower() == \"join data\":\n joinSql()\n else:\n parse(userInput)\n\n\n# Parse function will break user input into seperate pieces of data to pass to query function:\n# Parser will first split on \" \" to obtain strings.\ndef parse(userInput):\n try:\n # Split on Quotes\n splitOnQuotes = userInput.split('\"')\n\n # Split on Spaces\n divList1 = splitOnQuotes[0].split()\n column = divList1[0]\n\n # divList1[1] is \"of\" which will be disguarded\n key = divList1[2]\n value = splitOnQuotes[1]\n\n # Standardize capitalization of column and key.\n column = column.lower()\n column = column.capitalize()\n key = key.lower()\n key = key.capitalize()\n\n # Adjust for Possible synonyms in column string\n if column == \"Song\" or column == \"Track\":\n column = \"Title\"\n if column == \"Singer\" or column == \"Artists\" or column == \"Author\":\n column = \"Artist\"\n if column == \"Avgvalence\" or column == \"avgvalence\":\n column = \"AvgValence\"\n if column == \"Avgdanceability\":\n column = \"AvgDanceability\"\n\n # Adjust for Possible synonyms in key string\n if key == \"Song\" or key == \"Track\":\n key = \"Title\"\n if key == \"Singer\" or key == \"Artists\" or key == \"Author\":\n key = \"Artist\"\n\n # Validate that first two columns are valid inputs, then query, if not prompt user to input again\n # This makes user of short circuit evaluation\n if ((len(splitOnQuotes)==3) and (validateCol(column) and validateKey(key))):\n sqlQuery(column, key, value)\n\n # If this point is reached, input is invalid\n else:\n sys.stdout.write(\"Please enter a valid command. Type \\\"help\\\" for a complete list of commands.\\n\"\n \"The syntax of your argument may have been wrong.\\n\")\n getInput()\n except IndexError or UnboundLocalError:\n sys.stdout.write(\"Please enter a valid command. Type \\\"help\\\" for a complete list of commands.\\n\"\n \"The syntax of your argument may have been wrong.\\n\")\n getInput()\n\n\n# Function to validate Column as valid input\ndef validateCol(str):\n validInput = [\"AvgValence\", \"AvgDanceability\", \"Rank\", \"Title\", \"Artist\", \"Genre\", \"Danceability\", \"Valence\"]\n for i in range(len(validInput)):\n if (validInput[i] == str):\n return True\n return False\n\n\n# Function to validate Key as valid input\ndef validateKey(str):\n validInput = [\"Rank\", \"Title\", \"Artist\"]\n for i in range(len(validInput)):\n if (validInput[i] == str):\n return True\n return False\n\n\n# Help function to instruct user on operations and proper syntax\ndef help():\n print(\"Commands:\")\n sys.stdout.write(\"exit: To exit program\\n\"\n \"help: Full list of commands and correct syntax\\n\"\n \"load data: Create database and load data from csv\\n\"\n \"join data: Join data from the songs and artists table to view relevant information\\n\\n\"\n \"Syntax:\\nProper Syntax for Querying information about a Title or Artist: of \\n\"\n \"Ex: Rank of Title \\\"Randsom\\\" - will return the Rank of the song Titled 'Randsom'\\n\"\n \"Ex: AvgDanceability of Artist \\\"Ed Sheeran\\\" - will return the Average Danceability of Ed Sheeran's songs\\n\\n\")\n\n\n# loadData() function creates tables and then loads data from csv files into tables\ndef loadData():\n # Remove previously created tables if they exist\n try:\n c.execute('''DROP TABLE Songs''')\n c.execute('''DROP TABLE Artists''')\n db.commit()\n finally:\n # Creates tables\n c.execute('''CREATE TABLE Songs\n (Rank real PRIMARY KEY, Title text, Artist text, Genre text,\n Danceability real, Valence real)''')\n c.execute('''CREATE TABLE Artists\n (ArtistName text, AvgDanceability real, AvgValence real,\n FOREIGN KEY(ArtistName) REFERENCES Songs(Artist))''')\n db.commit()\n\n # Inserts csv file data into tables\n with open('Songs.csv') as songsDataFile:\n songsReader = csv.reader(songsDataFile)\n for songsRow in songsReader:\n print(songsRow)\n c.execute('''INSERT INTO Songs(Rank, Title, Artist, Genre,\n Danceability, Valence)\n VALUES(?,?,?,?,?,?)''', (songsRow[0], songsRow[1],\n songsRow[2], songsRow[3],\n songsRow[4], songsRow[5]))\n print(\"\")\n with open('Artists.csv') as artistsDataFile:\n artistsReader = csv.reader(artistsDataFile)\n for artistsRow in artistsReader:\n print(artistsRow)\n c.execute('''INSERT INTO Artists(ArtistName, AvgDanceability,\n AvgValence)\n VALUES (?,?,?)''', (artistsRow[0], artistsRow[1],\n artistsRow[2]))\n print(\"\")\n db.commit()\n\n\n# SQL functionality for joining the two tables, called by issuing \"join data\"\ndef joinSql():\n try:\n # Valid SQL statement to fetch correct information from database\n c.execute('''SELECT Songs.Rank, Songs.Artist, Songs.Title, Artists.AvgDanceability, \n Artists.AvgValence FROM Artists INNER JOIN Songs ON Artists.ArtistName=Songs.Artist ORDER BY Songs.Rank ASC''')\n\n # Stores and prints fetched results from query as list\n rows = c.fetchall()\n print(\"Joined data (Rank, Artist, Title, AvgDanceability of Artist, AvgValence of Artist)\")\n for row in rows:\n print(row) \n print(\"\")\n except sqlite3.OperationalError as e:\n print(\"Please load data with the \\\"load data\\\" before issuing querys.\")\n\n\n# sqlQuery() function takes 3 arguements of user input, converts to a valid SQL statement, \n# and returns correct data\ndef sqlQuery(column, key, val):\n songCols = ['Rank', 'Title', 'Artist', 'Genre', 'Danceability', 'Valence']\n artistCols = ['Artist', 'AvgDanceability', 'AvgValence']\n\n # Determine correct table to search in given user input\n if key in songCols and column in songCols:\n table = \"songs\"\n elif key in artistCols and column in artistCols:\n table = \"artists\"\n if column == \"Artist\":\n column = \"ArtistName\"\n if key == \"Artist\":\n key = \"ArtistName\"\n\n try:\n # Convert to valid SQL statement to fetch correct information from database\n c.execute(\"SELECT \"+column+\" FROM \"+table+\" WHERE upper(\"+key+\") = upper(\\'\"+val+\"\\')\")\n\n # Stores and prints fetched results from query as list\n rows = c.fetchall()\n for row in rows:\n print(row[0])\n print(\"\")\n if len(rows) == 0:\n print(\"Query returned no results, please try a different query.\")\n\n except sqlite3.OperationalError:\n print(\"Please load data with the \\\"load data\\\" before issuing querys.\")\n except Exception:\n print(\"Please select valid column. Type 'help' for a full list of commands.\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ChrisSwingle/CS225-warmup-CS-ZF-PD-MT","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"25541517115","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: igor\n\"\"\"\n#Imports OpenCV\nimport cv2\n\n#Loading the cascades used to recognize the haar features\nfaceCascade = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\neyeCascade = cv2.CascadeClassifier(\"haarcascade_eye.xml\")\nsmileCascade = cv2.CascadeClassifier(\"haarcascade_smile.xml\")\n\n#This function detects the features\n#Arguments:\n#\tgray: The converted gray image\n#\tframe: Original image\n#Return:\n#\tframe: The original image with the rectagles drawn around features detected\ndef detect(gray, frame):\n #Detects multiple faces with the cascade\n faces = faceCascade.detectMultiScale(gray, 1.3, 5)\n for (x,y,w,h) in faces:\n\t#For each face, a rectangle will be drawn around it and the region of the face\n\t#will be the region of interest for the other features\n cv2.rectangle(frame, (x,y) , (x+w,y+h), (255,0,0), 2)\n roi_gray = gray[y:y+h, x:x+w]\n roi_color = frame[y:y+h, x:x+w]\n\n\t#Detects multiple eyes with the cascade\n eyes = eyeCascade.detectMultiScale(roi_gray, 1.1, 22)\n for (ex,ey,ew,eh) in eyes:\n cv2.rectangle(roi_color, (ex,ey) , (ex+ew,ey+eh), (0,255,0), 2)\n\n\t#Detects multiple smiles with the cascade\n smiles = smileCascade.detectMultiScale(roi_gray, 1.7, 22)\n for (sx,sy,sw,sh) in smiles:\n cv2.rectangle(roi_color, (sx,sy) , (sx+sw,sy+sh), (0,0,255), 2)\n\n return frame\n\n#Turn on the webcam to capoture the video\nvideoCapture = cv2.VideoCapture(0)\n\nwhile True:\n #Select the last frame available\n _,frame = videoCapture.read()\n #Turn the frame into gray scale\n gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n #Call the function to detect the features\n canvas = detect(gray,frame)\n #Shows the frame in a window\n cv2.imshow('Video',canvas)\n\n #Press 'q' to stop the program\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n#Stop the webcam and close the video window\nvideoCapture.release()\ncv2.destroyAllWindows() \n","repo_name":"Igor-PR/Smile_Detection","sub_path":"Smile_recognition.py","file_name":"Smile_recognition.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"40216769073","text":"from __future__ import print_function\nfrom builtins import input\nimport os, re, sys, optparse, unittest\n\ndef genpath(somepath):\n\treturn os.path.sep.join(somepath.split('/'))\n\ndef print_header(text):\n\tprint('\\n')\n\tprint(80 * '=')\n\tprint(text)\n\tprint(80 * '-')\n\ndef resolve_test_progs(sconscript_filename):\n\t\"\"\" Get the names of all test programs by evaluating the SConscript file \"\"\"\n\treprg = re.compile(r\"\"\"^env.Program\\([\"'](.*?)['\"]\"\"\")\n\tprogs = []\n\tfor line in open(sconscript_filename):\n\t\tm = reprg.match(line.strip())\n\t\tif m:\n\t\t\tprogs.append(m.group(1))\n\treturn progs\n\ndef resolve_test_modules(directory):\n\tpythonfilenames = [p for p in os.listdir(directory) if len(p) > 3 and p[-3:] == '.py']\n\tmodname = directory.replace(os.path.sep, '.') + '.'\n\tmodules = []\n\tskipped_filenames = ('test_all.py',)\n\tfor p in pythonfilenames:\n\t\tskip = False\n\t\tfor s in skipped_filenames:\n\t\t\tif p.find(s) != -1:\n\t\t\t\tskip = True\n\t\tif p[0] == '_':\n\t\t\tskip = True\n\t\tif not skip:\n\t\t\tmodules.append(modname + p[:-3])\n\treturn modules\n\t\ndef run_core_tests(progs):\n\tprevdir = os.getcwd()\n\t\n\terrors, failures = [], []\n\tfor prog in progs:\n\t\tprint('\\n===== Running %s =====' % prog)\n\t\tif os.system(os.sep.join(('build','tests','debug', prog))):\n\t\t\terrors.append(prog)\n\tos.chdir(prevdir)\n\treturn errors, failures\n\ndef get_dynamic_imports(modules):\n\timported = []\n\tfor module in modules:\n\t\tm = __import__(module)\n\t\tfor part in module.split('.')[1:]:\n\t\t\tm = getattr(m, part)\n\t\timported.append(m)\n\treturn imported\n\t\t\ndef run_test_modules(modules):\n\timported = get_dynamic_imports(modules)\n\tsuites = []\n\tfor m in imported:\n\t\ttry:\n\t\t\tfor c in m.__dict__['TEST_CLASSES']:\n\t\t\t\tsuites.append(unittest.TestLoader().loadTestsFromTestCase(c))\n\t\texcept (AttributeError, KeyError):\n\t\t\tpass\n\tmastersuite = unittest.TestSuite(suites)\n\trunner = unittest.TextTestRunner(verbosity=2)\n\tresult = runner.run(mastersuite)\n\treturn [e[1] for e in result.errors], [f[1] for f in result.failures]\n\t\t\ndef run_all(tests):\n\tdef print_errors(txt, errs):\n\t\tif errs:\n\t\t\tprint(txt + ':')\n\t\t\tfor msg in errs:\n\t\t\t\tprint(' ' + msg)\n\t\t\n\tcore_errors, core_failures = run_core_tests(tests['core'])\n\tswig_errors, swig_failures = run_test_modules(tests['swig'])\n\text_errors, ext_failures = run_test_modules(tests['ext'])\n\t\n\tprint(80 * '=')\n\terrorsfound = False\n\t\n\tif core_errors or core_failures:\n\t\tprint_errors('Errors in core tests', core_errors)\n\t\tprint_errors('Failures in core tests', core_failures)\n\t\terrorsfound = True\n\telse:\n\t\tprint('No Core errors found')\n\t\n\tif swig_errors or swig_failures:\n\t\tprint_errors('Errors in SWIG tests', swig_errors)\n\t\tprint_errors('Failures in SWIG tests', swig_failures)\n\t\terrorsfound = True\n\telse:\n\t\tprint('No SWIG errors found')\n\t\n\tif swig_errors or swig_failures:\n\t\tprint_errors('Errors in extensions tests', ext_errors)\n\t\tprint_errors('Failures in extensions tests', ext_failures)\n\t\terrorsfound = True\n\telse:\n\t\tprint('No Extensions errors found')\n\n\tprint(80 * '=')\t\n\tif errorsfound:\n\t\tprint('ERROR. One or more tests failed!')\n\telse:\n\t\tprint('OK. All tests ran succesfully!')\n\tprint('')\n\t\ndef quit(dummy):\n\tsys.exit(0)\n\ndef run(automatic, selected_cases):\n\tindex = 0\n\ttests = {}\n\t\n\tcore_tests = resolve_test_progs(genpath('tests/core_tests/SConscript'))\n\tfor t in core_tests:\n\t\ttests[index] = ('Core tests', t, [t], run_core_tests)\n\t\tindex += 1\n\ttests[index] = ('Core tests', 'all', core_tests, run_core_tests)\t\n\tindex += 1\n\t\n\tswig_tests = resolve_test_modules(genpath('tests/swig_tests'))\n\tfor t in swig_tests:\n\t\ttests[index] = ('SWIG tests', t, [t], run_test_modules)\n\t\tindex += 1\n\ttests[index] = ('SWIG tests', 'all', swig_tests, run_test_modules)\t\n\tindex += 1\n\t\t\n\textension_tests = resolve_test_modules(genpath('tests/extension_tests'))\n\tfor t in extension_tests:\n\t\ttests[index] = ('Extension tests', t, [t], run_test_modules)\n\t\tindex += 1\n\ttests[index] = ('Extension tests', 'all', extension_tests, run_test_modules)\t\n\tindex += 1\n\n\talltests = {'core': core_tests, 'swig': swig_tests, 'ext': extension_tests}\n\ttests[index] = ('Other', 'Run all tests', alltests, run_all)\n\ttests[index+1] = ('Other', 'Cancel and quit', None, quit)\n\n\tif (not automatic) and (not selected_cases):\n\t\tselection = None\n\t\twhile True:\n\t\t\tprint('Select test module to run:')\n\t\t\tprevheader = ''\n\t\t\tfor ind in sorted(tests.keys()):\n\t\t\t\theader, name, params, fn = tests[ind]\n\t\t\t\tif header != prevheader:\n\t\t\t\t\tprint(header)\n\t\t\t\t\tprevheader = header\n\t\t\t\tprint(' %d) %s' % (ind, name))\n\t\t\tselection = input('-> : ')\n\t\t\t\n\t\t\ttry:\n\t\t\t\tselection = int(selection)\n\t\t\t\tif (selection < 0) or (selection > max(tests.keys())):\n\t\t\t\t\traise ValueError\n\t\t\t\tbreak\n\t\t\texcept ValueError:\n\t\t\t\tprint('Please enter number between 0-%d\\n' % max(tests.keys()))\n\t\t\t\tcontinue\n\t\theader, name, params, fn = tests[selection]\n\t\tfn(params)\n\telif (selected_cases):\n\t\tfor case in selected_cases:\n\t\t\ttry:\n\t\t\t\tcaseid = int(case)\n\t\t\t\tif (caseid < 0) or (caseid > max(tests.keys())):\n\t\t\t\t\traise ValueError\n\t\t\t\theader, name, params, fn = tests[caseid]\n\t\t\t\tfn(params)\n\t\t\texcept ValueError:\n\t\t\t\tprint('No test case with value %s found' % case)\n\telse:\n\t\trun_all(alltests)\n\ndef main():\n\tusage = 'usage: %prog [options] [args]\\n' + \\\n\t\t'This is a test runner.\\n' + \\\n\t\t'It enables you to test functionalities of fifengine core, extensions and the generated swig interface.\\n' + \\\n\t\t'You can give a list of test ids as arguments to the script.\\n' + \\\n\t\t'This is useful when running a test over and over again with little changes.\\n' + \\\n\t\t'Available test ids can be seen from interactive menu (run script without any parameters).\\n' + \\\n\t\t'You can also use \"-a\" to run all tests from the CLI.'\n\tparser = optparse.OptionParser(usage)\n\tparser.add_option(\"-a\", \"--automatic\",\n\t\t\taction=\"store_true\", dest=\"automatic\", default=False,\n\t\t\thelp=\"In case selected, runs all the tests automatically\")\n\toptions, args = parser.parse_args()\n\trun(options.automatic, args)\n\t\n\t\n\t\n\t\nif __name__ == '__main__':\n\tmain()\n","repo_name":"fifengine/fifengine","sub_path":"run_tests.py","file_name":"run_tests.py","file_ext":"py","file_size_in_byte":5911,"program_lang":"python","lang":"en","doc_type":"code","stars":531,"dataset":"github-code","pt":"77"}
+{"seq_id":"72811528569","text":"import django\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\nfrom codes.forms import CodeForm\nfrom users.models import CustomUser\nfrom . utils import send_msg\nfrom . forms import UserRegisterForm\n\n\n\n@login_required\ndef home(request):\n return render(request, 'home.html')\n\n\n\n\n\ndef fst_login(request):\n form = AuthenticationForm()\n if request.method == \"POST\":\n username = request.POST.get('username')\n password = request.POST.get('password')\n user = authenticate(request, username=username, password=password)\n if user is not None:\n request.session['pk'] = user.pk\n return redirect('verify-log')\n return render(request, 'fstLogin.html', {'form': form})\n\n\n\n\n\ndef scd_login(request):\n form = CodeForm(request.POST or None)\n pk = request.session.get('pk')\n if pk:\n user = CustomUser.objects.get(pk=pk)\n code= user.code\n code_user = f\"{user.username}: {user.code}\"\n if not request.POST:\n send_msg(code_user, user.phone_number)\n if form.is_valid():\n num = form.cleaned_data.get('number')\n\n if str(code) == num:\n code.save()\n login(request, user)\n return redirect('home')\n else:\n return redirect('fst-log')\n return render(request, 'scdLogin.html', {'form': form})\n\n\n\n\n\n\ndef register(request):\n if request.method == \"POST\": \n form = UserRegisterForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n messages.success(request, f'Hello {username}, your account has been created')\n return redirect('home')\n \n else:\n form = UserRegisterForm()\n\n \n \n return render(request, 'register.html', {'form':form} )\n","repo_name":"Muhaa11/TwoStepAuthen","sub_path":"authen/auth_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"29452354789","text":"import math\n\nclass Ciudad:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def camino(self, otra_ciudad):\n camino = []\n x1, y1 = self.x, self.y\n x2, y2 = otra_ciudad.x, otra_ciudad.y\n \n dx = abs(x2 - x1)\n dy = abs(y2 - y1)\n step_x = -1 if x1 > x2 else 1\n step_y = -1 if y1 > y2 else 1\n error = dx - dy\n\n while x1 != x2 or y1 != y2:\n camino.append([x1, y1])\n error2 = 2 * error\n\n if error2 > -dy:\n error -= dy\n x1 += step_x\n\n if error2 < dx:\n error += dx\n y1 += step_y\n\n camino.append([x1, y1])\n return camino\n\n def distancia(self, otra_ciudad):\n dx = otra_ciudad.x - self.x\n dy = otra_ciudad.y - self.y\n distancia = math.sqrt(dx ** 2 + dy ** 2)\n return (distancia)\n\np1 = Ciudad(1, 1)\np2 = Ciudad(3, 3)\ncamino_p1_p2 = p1.camino(p2)\ndistancia_p1_p2 = p1.distancia(p2)\n\nprint(\"Camino:\", camino_p1_p2)\nprint(\"Distancia:\", distancia_p1_p2)\n\n#CLASE AUTO\nclass Auto:\n def __init__(self, capacidad_estanque, rendimiento):\n self.kilometraje = 0\n self.cuenta_kilometros = 0\n self.capacidad_estanque = capacidad_estanque\n self.nivel_estanque = 0\n self.rendimiento = rendimiento\n def reiniciar_cuentakilometros(self):\n self.cuenta_kilometros = 0\n def andar(self, velocidad, tiempo):\n distancia_recorrida = velocidad * tiempo\n litros_consumidos = distancia_recorrida / self.rendimiento\n if litros_consumidos <= self.nivel_estanque:\n self.kilometraje += distancia_recorrida\n self.cuenta_kilometros += distancia_recorrida\n self.nivel_estanque -= litros_consumidos\n return 0\n else:\n distancia_faltante = (self.nivel_estanque * self.rendimiento) - distancia_recorrida\n self.kilometraje += (self.nivel_estanque * self.rendimiento)\n self.cuenta_kilometros += (self.nivel_estanque * self.rendimiento)\n self.nivel_estanque = 0\n return distancia_faltante\n def autonomia(self):\n return self.nivel_estanque * self.rendimiento\n\n def llenar_estanque(self, litros):\n if litros <= self.capacidad_estanque - self.nivel_estanque:\n self.nivel_estanque += litros\n return self.nivel_estanque, True\n else:\n litros_posibles = self.capacidad_estanque - self.nivel_estanque\n return litros_posibles, False\nauto = Auto(100, 12)\ndistancia_viaje = 500 \nvelocidad = 60 \ntiempo_viaje = distancia_viaje / velocidad \nnum_paradas = 0\ndistancia_restante = distancia_viaje\nwhile distancia_restante > 0:\n falta_combustible = auto.andar(velocidad, tiempo_viaje)\n if falta_combustible > 0:\n num_paradas += 1\n litros_a_cargar, _ = auto.llenar_estanque(falta_combustible)\n distancia_restante -= litros_a_cargar * auto.rendimiento\n else:\n distancia_restante = 0\nprint(\"Cantidad de paradas necesarias:\", num_paradas)\n\n ","repo_name":"pabloschwarzenberg/grader","sub_path":"tema3_ej5/tema3_ej5_b6fa01c2a4f9fe876247cec4ce22586b.py","file_name":"tema3_ej5_b6fa01c2a4f9fe876247cec4ce22586b.py","file_ext":"py","file_size_in_byte":3105,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"71321799928","text":"# -*- coding: utf-8 -*-\n# File: darknet_model.py\n\nimport tensorflow as tf\n\nfrom tensorpack.tfutils.argscope import argscope, get_arg_scope\nfrom tensorpack.models import (layer_register,\n Conv2D, GlobalAvgPooling, BatchNorm, FullyConnected)\n\nfrom imagenet_utils import ImageNetModel\n\n\n@layer_register(use_scope=None)\ndef BNLeakyReLU(x, name=None):\n \"\"\"\n A shorthand of BatchNormalization + LeakyReLU.\n \"\"\"\n x = BatchNorm('bn', x)\n x = tf.nn.leaky_relu(x, name=name)\n return x\n\n\ndef darknet_basicblock(l, ch_out):\n shortcut = l\n l = Conv2D('conv0', l, ch_out // 2, 1, activation=BNLeakyReLU)\n l = Conv2D('conv1', l, ch_out, 3, activation=BNLeakyReLU)\n return l + shortcut\n\n\ndef resnet_group(name, l, num_features, count):\n with tf.variable_scope(name):\n for i in range(0, count):\n with tf.variable_scope('block{}'.format(i)):\n l = darknet_basicblock(l, num_features)\n return l\n\n\ndef darknet(image, use_fp16):\n with argscope(Conv2D, use_bias=False,\n kernel_initializer=tf.variance_scaling_initializer(scale=2.0, mode='fan_out')):\n l = Conv2D('conv0', image, 32, 3, strides=1, activation=BNLeakyReLU)\n l = Conv2D('conv1', l, 64, 3, strides=2, activation=BNLeakyReLU)\n l = resnet_group('group0', l, 64, 1)\n l = Conv2D('conv2', l, 128, 3, strides=2, activation=BNLeakyReLU)\n l = resnet_group('group1', l, 128, 2)\n l = Conv2D('conv3', l, 256, 3, strides=2, activation=BNLeakyReLU)\n l = resnet_group('group2', l, 256, 8)\n l = Conv2D('conv4', l, 512, 3, strides=2, activation=BNLeakyReLU)\n l = resnet_group('group3', l, 512, 8)\n l = Conv2D('conv5', l, 1024, 3, strides=2, activation=BNLeakyReLU)\n l = resnet_group('group4', l, 1024, 4)\n l = GlobalAvgPooling('gap', l)\n logits = FullyConnected('linear', l, 1000,\n kernel_initializer=tf.random_normal_initializer(stddev=0.01))\n return logits\n\n\nclass Model(ImageNetModel):\n def __init__(self, use_fp16=False):\n self.use_fp16 = use_fp16\n\n def get_logits(self, image):\n return darknet(image, self.use_fp16)\n","repo_name":"ksellesk/darknet53-tensorpack","sub_path":"darknet_model.py","file_name":"darknet_model.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"23813151762","text":"#!/usr/bin/env python3\nfrom optparse import OptionParser\nfrom logging import DEBUG, StreamHandler\n\nfrom daemon import SimpleFactory, SimpleProtocol, catch\nfrom daemon_min import MINProtocol, MINFrame, min_logger\n\n\nclass DaemonProtocol(SimpleProtocol):\n\n @catch\n def processMessage(self, string):\n cmd = SimpleProtocol.processMessage(self, string)\n if cmd is None:\n return\n\n Sstring = (string.strip('\\n')).split(';')\n for sstring in Sstring:\n sstring = sstring.lower()\n payload = None\n while True:\n # managment commands\n if sstring == 'get_status':\n self.message(\n 'status hw_connected={hw_connected} temp01={temp01} humd01={humd01} temp02={temp02} humd02={humd02} sw01={sw01} sw02={sw02} sw03={sw03} sw04={sw04}'.format(**self.object))\n break\n if not obj['hw_connected']:\n break\n queue_frame = obj['hwprotocol'].queue_frame\n source=self.name\n if sstring == 'reset':\n obj['hwprotocol'].transport_reset()\n break\n if sstring == 'testcomm':\n from time import time\n payload = bytes(\"hello world {}\".format(time()), encoding='ascii')\n break\n if sstring in ['get_ardsta','get_temp01', 'get_humd01','get_temp02','get_humd02'\n ,'set_sw01on','set_sw01of','get_sw01st'\n ,'set_sw02on','set_sw02of','get_sw02st'\n ,'set_sw03on','set_sw03of','get_sw03st'\n ,'set_sw04on','set_sw04of','get_sw04st']:\n payload = bytes(sstring, encoding='ascii')\n if sstring in ['set_sw01on','set_sw01of','set_sw02on','set_sw02of',\n 'set_sw03on','set_sw03of','set_sw04on','set_sw04of']:\n source=None # these commands do not expect reply\n break\n break\n if payload:\n queue_frame(1, payload, source=source)\n\n\nclass Arduino_A_Protocol(MINProtocol):\n status_commands = ['get_ardsta']\n\n @catch\n def __init__(self, devname, obj, debug=False):\n super().__init__(devname=devname, obj=obj, refresh=1, baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=400, debug=debug)\n min_log_handler = StreamHandler()\n min_logger.addHandler(min_log_handler)\n if debug:\n min_logger.setLevel(level=DEBUG)\n\n @catch\n def connectionMade(self):\n super().connectionMade()\n self.object['hw_connected'] = 1\n\n @catch\n def connectionLost(self):\n super().connectionLost()\n self.object['hw_connected'] = 0\n self.object['temp01'] = 'nan'\n self.object['humd01'] = 'nan'\n self.object['temp02'] = 'nan'\n self.object['humd02'] = 'nan'\n self.object['sw01'] = 'nan'\n self.object['sw02'] = 'nan'\n self.object['sw03'] = 'nan'\n self.object['sw04'] = 'nan'\n\n @catch\n def processFrame(self, frame: MINFrame):\n # Process the device reply\n min_logger.debug(\"Received MIN frame, min_id={}, payload={}, seq={}, source={}, tr={}\".format(\n frame.min_id, frame.payload, frame.seq, frame.source, frame.is_transport))\n plString = frame.payload.decode('ascii').split(':')[1]\n r_str = ''\n while True:\n if plString.startswith('status='):\n statStr=plString.replace('status=','').split(';')\n self.object['temp01'] = statStr[0]\n self.object['temp02'] = statStr[1]\n self.object['humd01'] = statStr[2]\n self.object['humd02'] = statStr[3]\n self.object['sw01'] = statStr[4]\n self.object['sw02'] = statStr[5]\n self.object['sw03'] = statStr[6]\n self.object['sw04'] = statStr[7]\n break \n if plString.startswith('temp01='):\n self.object['temp01'] = plString.split('=')[1]\n break\n if plString.startswith('humd01='):\n self.object['humd01'] = plString.split('=')[1]\n break\n if plString.startswith('temp02='):\n self.object['temp02'] = plString.split('=')[1]\n break\n if plString.startswith('humd02='):\n self.object['humd02'] = plString.split('=')[1]\n break\n break\n if frame.source == 'itself':\n return\n if r_str == '':\n daemon.messageAll(plString, frame.source)\n else:\n daemon.messageAll(r_str, frame.source)\n\n @catch\n def update(self):\n if self.object['hw_connected'] == 0:\n return\n #min_logger.debug('updater')\n if (len(self._transport_fifo)==0):\n for ccmd in self.status_commands:\n payload = bytes(ccmd, encoding='ascii')\n self.queue_frame(1, payload, source='itself')\n self.poll()\n\n\nif __name__ == '__main__':\n parser = OptionParser(usage=\"usage: %prog [options] arg\")\n parser.add_option('-d', '--device', help='the device to connect to.', action='store', dest='devname', type='str', default='/dev/arduino_A')\n parser.add_option('-p', '--port', help='Daemon port', action='store', dest='port', type='int', default=7030)\n parser.add_option('-n', '--name', help='Daemon name', action='store', dest='name', default='arduino_A')\n parser.add_option(\"-D\", '--debug', help='Debug mode', action=\"store_true\", dest=\"debug\")\n\n (options, args) = parser.parse_args()\n\n # Object holding actual state and work logic.\n # May be anything that will be passed by reference - list, dict, object etc\n obj = {'hw_connected': 0, 'temp01': 'nan', 'humd01': 'nan', 'temp02': 'nan', 'humd02': 'nan', 'sw01':'nan', 'sw02':'nan', 'sw03':'nan', 'sw04':'nan'}\n\n daemon = SimpleFactory(DaemonProtocol, obj)\n daemon.name = options.name\n obj['daemon'] = daemon\n\n obj['hwprotocol'] = Arduino_A_Protocol(devname=options.devname, obj=obj, debug=options.debug)\n\n if options.debug:\n daemon._protocol._debug = True\n\n # Incoming connections\n daemon.listen(options.port)\n\n daemon._reactor.run()\n","repo_name":"karpov-sv/ccdlab","sub_path":"arduino_A.py","file_name":"arduino_A.py","file_ext":"py","file_size_in_byte":6451,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"39388964500","text":"import unittest\nfrom part1 import check_valid_numbers\nfrom part2 import find_encryption_weakness\n\n\ndata = [\n 35,\n 20,\n 15,\n 25,\n 47,\n 40,\n 62,\n 55,\n 65,\n 95,\n 102,\n 117,\n 150,\n 182,\n 127,\n 219,\n 299,\n 277,\n 309,\n 576\n ]\n\nclass TestFunctions(unittest.TestCase):\n\n def test_check_valid_numbers(self):\n self.assertEqual(check_valid_numbers(data, 5), 127)\n\n def test_find_encryption_weakness(self):\n self.assertEqual(find_encryption_weakness(data, 127), 62)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"eeviinkeri/adventofcode","sub_path":"2020/day9/test_day9.py","file_name":"test_day9.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"73675193848","text":"from Beam import *\r\n# Beam Class\r\n'Steel Beam Class'\r\n\r\nclass BeamStl(Beam):\r\n def __init__ (self):\r\n self.Lcomp=0 # meter\r\n self.M1=0 # 4 Design\r\n self.M2=0 # 4 Design M1 > M2\r\n self.Cm=0\r\n self.fbEqua=0 # 1 or 2\r\n","repo_name":"JJMoon/StructuralAdvice","sub_path":"BeamStl.py","file_name":"BeamStl.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"26544249474","text":"import numpy as np\nimport pandas as pd\nfrom scipy import signal\nfrom sklearn.metrics import mean_squared_error\n\n\ndef moving_average(y, N):\n y_final = np.empty(y.shape)\n for idx in np.arange(y.shape[1]):\n y_padded = np.pad(y[:,idx], (N//2, N-1-N//2), mode='edge')\n y_final[:,idx] = np.convolve(y_padded, np.ones((N,))/N, mode='valid')\n return y_final\n\ndef linear_detrend(input_vec, bin_size):\n output_vec = np.empty((input_vec.shape[0],))\n for ii in np.arange(input_vec.shape[1]):\n\n testing_vec = input_vec[:,ii]\n slices = np.linspace(0, len(testing_vec), int(len(testing_vec)/bin_size) + 1, True).astype(int)\n\n detrended_vec = []\n for ii, _ in enumerate(slices[:-1]):\n detrended_vec = np.append(detrended_vec, signal.detrend(testing_vec[slices[ii]:slices[ii+1]]))\n output_vec = np.column_stack((output_vec, detrended_vec))\n\n return output_vec[:,1:]\n\ndef low_pass_filter(input_vec):\n b, a = signal.butter(2, 0.02)\n output_vec = np.empty((input_vec.shape[0],))\n\n for ii in np.arange(input_vec.shape[1]):\n testing_vec = input_vec[:,ii]\n detrended_vec = signal.filtfilt(b, a, testing_vec, method=\"gust\")\n output_vec = np.column_stack((output_vec, detrended_vec))\n\n return output_vec[:,1:]\n\ndef list_to_array(input_vec):\n test_vec = np.empty((len(input_vec[0]),1))\n for ii in np.arange(len(input_vec)):\n vec = np.expand_dims(np.array(input_vec[ii]), axis=1)\n test_vec = np.concatenate((test_vec, vec), axis=1)\n new_vec = test_vec[:,1:]\n return new_vec\n\ndef rmse(actual, predict):\n rms = np.sqrt(mean_squared_error(actual, predict))\n return rms\n\ndef zscore(actual, predict, mean, std):\n error = actual - predict\n mean = np.expand_dims(np.ones(len(error))*mean, axis=1)\n score = ((actual - predict) - mean)/std\n score = np.mean(np.abs(score))\n return score\n\ndef zscore_raw(actual, predict, mean, std):\n error = actual - predict\n # mean = np.ones((len(error),1))*mean\n score = error - mean\n score = score/std\n # score = (error - mean)/std\n # score = np.mean(np.abs(score))\n return score\n\ndef filt_outlier(input_vec):\n test_vec_d = np.abs(np.diff(input_vec))\n for ii in np.arange(len(test_vec_d)):\n if test_vec_d[ii] > np.std(test_vec_d)*2 and ii > 3:\n input_vec[ii] = (input_vec[ii-1]+ input_vec[ii+1])/2\n return input_vec","repo_name":"inseungkang/learningalgos","sub_path":"Controller Inference/utilityFunc.py","file_name":"utilityFunc.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"1884825789","text":"# -*- coding: utf-8 -*-\r\n\r\n# PWZN Projekt 8\r\n# Paweł Dębowski\r\n\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport os\r\nimport time\r\nimport threading\r\n\r\n# odpalanie z terminala - python PDproj8.py \r\n\r\n# funkcja pobierania\r\ndef pobieranie(adres, kod):\r\n obrazek = link + '/' + adres\r\n print(obrazek)\r\n with open(file_path + '/' + kod + adres, 'wb') as handler:\r\n handler.write(requests.get(obrazek).content)\r\n\r\n# stałe\r\nfile_path = os.path.dirname(os.path.abspath(__file__))\r\nlink = 'http://www.if.pw.edu.pl/~mrow/dyd/wdprir' \r\nurl = requests.get(link)\r\nsoup = BeautifulSoup(url.text,\"html.parser\")\r\nadresy = []\r\n\r\n# adresy do obrazków\r\nfor a in soup.find_all('a', href=True):\r\n if a[\"href\"][a[\"href\"].rfind(\".\")+1:] in ['png']:\r\n adresy.append(a[\"href\"])\r\nprint(adresy)\r\n\r\n# (1) pobieranie klasycznie\r\nt = time.time()\r\nfor img in adresy:\r\n pobieranie(img,'1')\r\nprint('Zadanie klasycznie zajęło ' + str(time.time()-t))\r\n\r\n# (2) ppobieranie wielowątkowe\r\nt = time.time()\r\nthreads = []\r\nfor img in adresy:\r\n threads.append(threading.Thread(target=pobieranie, args=(img, '2')))\r\nfor p in threads:\r\n p.start()\r\nfor p in threads:\r\n p.join()\r\nprint('Zadanie wielowątkowo zajęło ' + str(time.time()-t))\r\n\r\n# średnio wychodzi trzy/cztery razy szybciej\r\n","repo_name":"pawdeb/PD-PWZN","sub_path":"Projekt8/PDproj8.py","file_name":"PDproj8.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"38114959095","text":"# -*- coding: utf-8 -*-\n\n# This Source Code Form is subject to the terms of the Mozilla Public License,\n# v. 2.0. If a copy of the MPL was not distributed with this file, You can\n# obtain one at http://mozilla.org/MPL/2.0/.\n\nfrom taskcluster.aio import Auth\n\nfrom ..resources import Client\nfrom ..util.sessions import aiohttp_session\nfrom ..util.taskcluster import tcClientOptions\n\n\nasync def fetch_clients(resources):\n auth = Auth(await tcClientOptions(), session=aiohttp_session())\n query = {}\n while True:\n res = await auth.listClients(query=query)\n for clients in res[\"clients\"]:\n client = Client.from_api(clients)\n if resources.is_managed(client.id):\n resources.add(client)\n\n if \"continuationToken\" in res:\n query[\"continuationToken\"] = res[\"continuationToken\"]\n else:\n break\n","repo_name":"taskcluster/tc-admin","sub_path":"tcadmin/current/clients.py","file_name":"clients.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"77"}
+{"seq_id":"39908395499","text":"import random\r\nimport urllib.request #enable us to get data from website\r\n\r\ndef download_web_image(url):\r\n name = random.randrange(1, 1000)\r\n full_name = str(name) + \".jpg\"\r\n urllib.request.urlretrieve(url, full_name)\r\n\r\ndownload_web_image(\"https://pmctvline2.files.wordpress.com/2016/05/person-of-interest-root-dies-amy-acker.jpg?w=621\")\r\n\r\n","repo_name":"Toha-K-M/Basic-problems-vault","sub_path":"Math Problems/Others/download image/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"4289338893","text":"import numpy as np\n\n'''\nthis module implements basic functions for transport coefficients, which are\ncomputed by integrating an arbitrary sigma_E function with the appropriate\nFermi-Dirac weighting functions\n\nModel variables:\n reduced chemical potential (cp) unitless (mu/kT)\n transport function exponent (s) unitless\n transport function prefactor (sigma_E_0) same units as conductivity (S/m)\n'''\n\nconstant = {'e': 1.60217662e-19, # physical constants\n 'k': 1.38064852e-23}\n\n\ndef numeric_conductivity(energy, sigma_E, mu, T):\n '''\n returns the electrical conductivity (S/m)\n\n Args:\n energy: (ndarray) The x-points for sigma_E v.s. energy (units of eV).\n sigma_E: (ndarray) The y-points for sigma_E v.s. energy (units of S/m).\n mu: (float) The electron chemical potential (units of eV).\n T: (float) The absolute temperature (units of K).\n\n Returns: (float)\n '''\n\n beta = 1. / constant['k'] / T * constant['e'] # units of eV\n derivative_of_fermi_dirac = -(\n beta * np.exp(beta * (energy - mu)) / (\n np.exp(beta * (energy - mu)) + 1.)**2.)\n return np.trapz(\n y=sigma_E * (-derivative_of_fermi_dirac),\n x=energy)\n\n\ndef numeric_nu(energy, sigma_E, mu, T):\n '''\n returns the transport coefficient for a temperature gradient\n\n Args:\n energy: (ndarray) The x-points for sigma_E v.s. energy (units of eV).\n sigma_E: (ndarray) The y-points for sigma_E v.s. energy (units of S/m).\n mu: (float) The electron chemical potential (units of eV).\n T: (float) The absolute temperature (units of K).\n\n Returns: (float)\n '''\n\n beta = 1. / constant['k'] / T * constant['e'] # units of eV\n derivative_of_fermi_dirac = -(\n beta * np.exp(beta * (energy - mu)) / (\n np.exp(beta * (energy - mu)) + 1.)**2.)\n return np.trapz(\n y=(constant['k'] / constant['e'] * sigma_E *\n (-derivative_of_fermi_dirac) * (energy - mu) * beta),\n x=energy)\n\n\ndef numeric_seebeck(energy, sigma_E, mu, T):\n '''\n returns the Seebeck coefficient (V/K)\n\n Args:\n energy: (ndarray) The x-points for sigma_E v.s. energy (units of eV).\n sigma_E: (ndarray) The y-points for sigma_E v.s. energy (units of S/m).\n mu: (float) The electron chemical potential (units of eV).\n T: (float) The absolute temperature (units of K).\n\n Returns: (float)\n '''\n\n return (numeric_nu(energy, sigma_E, mu, T) /\n numeric_conductivity(energy, sigma_E, mu, T))\n","repo_name":"dyllamt/semitransport","sub_path":"semitransport/base/models/numeric_model.py","file_name":"numeric_model.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"8947961482","text":"\nimport unittest\nimport json\nimport sys\nimport os\nfrom socket import socket, AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR\n\nsys.path.insert(0, os.path.join(os.getcwd(), '..'))\nfrom common.utils import get_message, send_message\nfrom common.settings import ENCODING, MAX_CONNECTIONS, \\\n DEFAULT_ADDRESS, DEFAULT_PORT, \\\n MAX_PACKAGE_LENGTH\n\n\nclass TestUtils(unittest.TestCase):\n test_message = {\n 'action': 'presence',\n 'time': 11.11,\n 'user': {\n 'account_name': 'Guest',\n },\n }\n\n response_ok = {'response': 200, \n 'alert': 'соединение успешно'}\n response_err = {'response': 400,\n 'error': 'ошибка соединения'}\n \n server_socket = None\n client_socket = None\n\n def setUp(self) -> None:\n # создаем тестовый сокет для сервера\n self.server_socket = socket(AF_INET, SOCK_STREAM)\n self.server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\n self.server_socket.bind((DEFAULT_ADDRESS, DEFAULT_PORT))\n self.server_socket.listen(MAX_CONNECTIONS)\n # создаем тестовый сокет для клиента\n self.client_socket = socket(AF_INET, SOCK_STREAM)\n self.client_socket.connect((DEFAULT_ADDRESS, DEFAULT_PORT))\n self.client, self.client_address = self.server_socket.accept()\n\n def tearDown(self) -> None:\n self.client.close()\n self.client_socket.close()\n self.server_socket.close()\n\n def test_send_wrong_message_from_client(self):\n self.assertRaises(TypeError, send_message, self.client_socket, 'not dict')\n\n def test_send_message_client_server(self):\n send_message(self.client_socket, self.test_message)\n test_response = self.client.recv(MAX_PACKAGE_LENGTH)\n test_response = json.loads(test_response.decode(ENCODING))\n self.client.close()\n self.assertEqual(self.test_message, test_response)\n\n def test_get_message_200(self):\n message = json.dumps(self.response_ok)\n self.client.send(message.encode(ENCODING))\n self.client.close()\n\n response = get_message(self.client_socket)\n self.assertEqual(self.response_ok, response)\n\n def test_get_message_400(self):\n message = json.dumps(self.response_err)\n self.client.send(message.encode(ENCODING))\n self.client.close()\n\n response = get_message(self.client_socket)\n self.assertEqual(self.response_err, response)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"Ignat-8/Python_client_server_PyQT","sub_path":"python_client_server/unit_tests/test_utils2.py","file_name":"test_utils2.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"30763431148","text":"import sys\r\n\r\ninput = sys.stdin.readline\r\n\r\n\r\nn, m = map(int, input().split())\r\nnumbers = list(map(int, input().split()))\r\n\r\nleft = [0]\r\nright = [0]\r\n\r\nfor num in numbers:\r\n if num < 0:\r\n left.append(-num)\r\n else:\r\n right.append(num)\r\n\r\nleft.sort(reverse=True)\r\nright.sort(reverse=True)\r\n\r\nanswer = 0\r\n\r\nfor i in range(len(left)):\r\n if i % m == 0:\r\n answer += left[i] * 2\r\n\r\nfor i in range(len(right)):\r\n if i % m == 0:\r\n answer += right[i] * 2\r\n\r\nprint(answer - max(left[0], right[0]))\r\n","repo_name":"ng-lee/ProblemSolving","sub_path":"백준/Gold/1461. 도서관/도서관.py","file_name":"도서관.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"69811921209","text":"import time, sys, os, platform, json, csv, requests, threading, queue\r\nfrom datetime import datetime\r\nfrom art import text2art\r\nfrom colorama import init, Fore, Style\r\nfrom dotenv import load_dotenv\r\n\r\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\ninit(convert=True) if platform.system() == \"Windows\" else init()\r\nprint(f\"{Fore.CYAN}{Style.BRIGHT}{text2art('Created by @ayyitsc9')}\\n\")\r\nload_dotenv()\r\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n\r\nlightblue = \"\\033[94m\"\r\norange = \"\\033[33m\"\r\n\r\nclass Logger:\r\n @staticmethod\r\n def timestamp():\r\n return str(datetime.now())[:-7]\r\n @staticmethod\r\n def normal(message):\r\n print(f\"{lightblue}[{Logger.timestamp()}] {message}\")\r\n @staticmethod\r\n def other(message):\r\n print(f\"{orange}[{Logger.timestamp()}] {message}\")\r\n @staticmethod\r\n def error(message):\r\n print(f\"{Fore.RED}[{Logger.timestamp()}] {message}\")\r\n @staticmethod\r\n def success(message):\r\n print(f\"{Fore.GREEN}[{Logger.timestamp()}] {message}\")\r\n\r\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n\r\ndef get_csv_labels():\r\n # Open CSV file and return a list containing each value of the first row. Each value is wrapped with curly braces {}\r\n with open(\"webhooks.csv\", newline='') as input_file:\r\n csv_file = csv.reader(input_file)\r\n return [f\"{{{label.strip()}}}\" for label in next(csv_file)]\r\n\r\ndef read_csv():\r\n # Open CSV file and return all of the content in a list (without the first row)\r\n with open(\"webhooks.csv\", newline='') as input_file:\r\n csv_file = csv.reader(input_file)\r\n next(csv_file)\r\n csv_content = []\r\n try:\r\n for row in csv_file:\r\n csv_content.append(row)\r\n return csv_content\r\n except Exception as err:\r\n Logger.error(f\"Error : {err}\")\r\n\r\ndef send_test_webhook(webhook_message):\r\n # Get test webhook url from env\r\n TEST_WEBHOOK_URL = os.getenv('TEST_WEBHOOK_URL')\r\n # Send webhook message to test webhook\r\n req = requests.post(TEST_WEBHOOK_URL, json=webhook_message)\r\n if req.status_code == 204:\r\n Logger.success(\"Successfully sent message to test webhook. Make sure to check it before sending to all webhooks!\")\r\n else:\r\n Logger.error(f\"Failed to send test webhook. Error : {req.status_code} | {req.json()}\")\r\n while True:\r\n print(Style.RESET_ALL)\r\n # Verify if user would like to send the message to all of the webhooks in the csv file\r\n res = input(\"Send message to all webhooks? (Y/ N) \")\r\n print(\"\\n\")\r\n if res.lower() == \"y\" or res.lower() == \"yes\":\r\n return True\r\n break\r\n elif res.lower() == \"n\" or res.lower() == \"no\":\r\n Logger.other(\"Successfully cancelled webhook execution!\")\r\n break\r\n else:\r\n print(\"Invalid input. Try again!\")\r\n\r\ndef run(row):\r\n # Run WebhookSender\r\n WebhookSender(row)\r\n\r\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n\r\nclass WebhookSender:\r\n def __init__(self, row_values):\r\n self.row_values = row_values\r\n # Webhook message template\r\n self.webhook_message = json.load(open(\"message.json\", encoding='utf-8'))\r\n # Format webhook message\r\n self.formatted_message = self.format_message()\r\n # Send formatted webhook\r\n self.send_webhook()\r\n \r\n # \r\n def format_message(self):\r\n def format_value(value):\r\n # Check if the argument passed in is a string and if { and } are present\r\n if type(value) is str and \"{\" in value and \"}\" in value:\r\n # Loop through the csv labels. This is the first row of the csv\r\n for label in csv_labels:\r\n # Check if csv label is in value\r\n if label in value:\r\n # Replace the reference with the coressponding row value in the same index as the csv label that was referenced\r\n value = value.replace(label, self.row_values[csv_labels.index(label)])\r\n return value\r\n\r\n # For better visualization of what is being done here, I recommend viewing multi-level json data.\r\n # It's also important to understand these data types : str, list, dict\r\n # I personally visualize a level for each step I have to take to access the keys' value\r\n\r\n # First level, get the keys with a \"str\" value type\r\n outer_values_str = list(filter((lambda x: type(self.webhook_message[x]) is str), self.webhook_message))\r\n # Loop through the first level keys with \"str\" value type\r\n for outer_value_str in outer_values_str:\r\n # Run the value of the key through the format_value function and set its new value to the value returned\r\n self.webhook_message[outer_value_str] = format_value(self.webhook_message[outer_value_str])\r\n # Checks if \"embeds\" is present in the first level\r\n if 'embeds' in self.webhook_message:\r\n # Loop through the \"embeds\" list which are dict (this list is second level)\r\n for embed_count, embed in enumerate(self.webhook_message['embeds'], 0):\r\n # Third level, we're now filtering the content inside an individual embed\r\n # Third level, get the keys with a \"str\" value type\r\n embed_outer_values_str = list(filter((lambda x: type(self.webhook_message['embeds'][embed_count][x]) is str), self.webhook_message['embeds'][embed_count]))\r\n # Third level, get the keys with a dict value type\r\n embed_outer_values_dict = list(filter((lambda x: type(self.webhook_message['embeds'][embed_count][x]) is dict), self.webhook_message['embeds'][embed_count]))\r\n # Loop through the third level keys with \"str\" value type\r\n for embed_outer_value_str in embed_outer_values_str:\r\n # Run the value of the key through the format_value function and set its new value to the value returned\r\n self.webhook_message['embeds'][embed_count][embed_outer_value_str] = format_value(self.webhook_message['embeds'][embed_count][embed_outer_value_str])\r\n # Loop through the third level keys with dict value type\r\n for embed_inner_value_dict in embed_outer_values_dict:\r\n # Loop through the third level keys with \"str\" value type\r\n # There is no check here to see if it is a string. From what I have seen, there can only be str value types in this level\r\n for embed_inner_value_str in self.webhook_message['embeds'][embed_count][embed_inner_value_dict]:\r\n # Run the value of the key through the format_value function and set its new value to the value returned\r\n self.webhook_message['embeds'][embed_count][embed_inner_value_dict][embed_inner_value_str] = format_value(self.webhook_message['embeds'][embed_count][embed_inner_value_dict][embed_inner_value_str])\r\n # Checks if \"fields\" is present in the third level ('embeds' > [embed_index] > 'fields')\r\n if 'fields' in self.webhook_message['embeds'][embed_count]:\r\n # Loop through the \"fields\" list which are dict (this list is fourth level)\r\n for field_count, field in enumerate(self.webhook_message['embeds'][embed_count]['fields'], 0):\r\n # Fifth level, get the keys with a \"str\" value type\r\n field_inner_values_str = list(filter((lambda x: type(self.webhook_message['embeds'][embed_count]['fields'][field_count][x]) is str), self.webhook_message['embeds'][embed_count]['fields'][field_count]))\r\n # Loop through the fifth level keys with \"str\" value type ('embeds' > [embed_index] > 'fields'> [field_index] > key)\r\n for field_inner_value_str in field_inner_values_str:\r\n # Run the value of the key through the format_value function and set its new value to the value returned\r\n self.webhook_message['embeds'][embed_count]['fields'][field_count][field_inner_value_str] = format_value(self.webhook_message['embeds'][embed_count]['fields'][field_count][field_inner_value_str])\r\n # Return formatted webhook message. This should have replaced value strings with a {} value referring to data from the csv file. Example : {Name} would be replaced with the rows' unique Name value\r\n return self.webhook_message\r\n\r\n def send_webhook(self):\r\n # Send webhook message to the webhook from self.row_values\r\n req = requests.post(self.row_values[csv_labels.index(\"{Webhook}\")], json=self.formatted_message)\r\n if req.status_code == 204:\r\n queue_.put(self)\r\n Logger.success(\"[{}] Successfully sent message to webhook!\".format(self.row_values[csv_labels.index(\"{Name}\")]))\r\n queue_.get()\r\n queue_.task_done()\r\n elif req.status_code == 500:\r\n queue_.put(self)\r\n Logger.success(\"[{}] Sleeping for 5 seconds and retrying...\".format(self.row_values[csv_labels.index(\"{Name}\")]))\r\n queue_.get()\r\n queue_.task_done()\r\n time.sleep(5)\r\n req2 = requests.post(self.row_values[csv_labels.index(\"{Webhook}\")], json=self.formatted_message)\r\n if req2.status_code == 204:\r\n queue_.put(self)\r\n Logger.success(\"[{}] Successfully sent message to webhook!\".format(self.row_values[csv_labels.index(\"{Name}\")]))\r\n queue_.get()\r\n queue_.task_done()\r\n else:\r\n queue_.put(self)\r\n Logger.error(f\"[{self.row_values}] Failed to send message to webhook on retry! Error : {req.status_code} | {req.json()}\")\r\n queue_.get()\r\n queue_.task_done()\r\n else:\r\n queue_.put(self)\r\n Logger.error(f\"[{self.row_values}] Failed to send message to webhook! Error : {req.status_code} | {req.json()}\")\r\n queue_.get()\r\n queue_.task_done()\r\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n\r\nwhile True:\r\n print(Style.RESET_ALL)\r\n print(\"What would you like to do?\\n\")\r\n print(\"######################################\\n\")\r\n print(\"[1] Webhook Sender\\t\\t[2]Exit\\n\")\r\n print(\"######################################\\n\")\r\n task = input(\"Enter Option : \")\r\n print(\"\\n\")\r\n if task == \"1\":\r\n # Queue Handling | Initialize Queue\r\n global queue_\r\n queue_ = queue.Queue(maxsize=1)\r\n csv_labels = get_csv_labels()\r\n res = send_test_webhook(json.load(open(\"message.json\", encoding='utf-8')))\r\n if res:\r\n csv_content = read_csv()\r\n threads = []\r\n try:\r\n # Loop through csv_content and create/ start a Thread for each row\r\n for row in csv_content:\r\n thread = threading.Thread(target=run, args=(row,))\r\n queue_.put(row)\r\n Logger.normal(\"[{}] Sending webhook message...\".format(row[csv_labels.index(\"{Name}\")]))\r\n queue_.get()\r\n queue_.task_done()\r\n thread.start()\r\n threads.append(thread)\r\n # Wait for all threads to finish\r\n for x in threads:\r\n x.join()\r\n except Exception as err:\r\n Logger.error(f\"Error occured while running #1 Webhook Sender : {err}\")\r\n Logger.other(\"Finished Webhook Sender Execution!\")\r\n elif task == \"2\":\r\n Logger.other(\"Comment on my legit check @ https://twitter.com/ayyitsc9\")\r\n Logger.other(\"Star the repository @ https://github.com/ayyitsc9/mass-discord-webhook-sender\")\r\n Logger.error(\"Exiting in 5 seconds...\")\r\n time.sleep(5)\r\n sys.exit()\r\n else:\r\n print(\"Invalid input. Try again!\")\r\n\r\n# Here is a great resource for visualizing your webhook post before sending it! (Not created by me, credits to the creator)\r\n# https://leovoel.github.io/embed-visualizer/\r\n# Make sure to enable webhook mode if you use the tool above\r\n","repo_name":"ayyitsc9/mass-discord-webhook-sender","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"41539060047","text":"from pathlib import Path\nimport pandas as pd\nimport torch.utils.data as Data\nfrom PIL import Image\nimport numpy as np\nimport torch\nimport random\nfrom torchvision import transforms\n\nclasses = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\n\n\nclass CifarDataset(Data.Dataset):\n \"\"\"初始化数据集\"\"\"\n\n @staticmethod\n def get_label(label_path):\n if label_path is not None:\n df = pd.read_csv(label_path)\n class_dict = {label: i for i, label in enumerate(classes)}\n df['label'] = df['label'].apply(lambda x: class_dict[x])\n return list(df['label'].values)\n else:\n return None\n\n def __init__(self, img_dir='dataset/trainImages/', train=True, img_label=None, transform=None):\n self.img_path = list(Path(img_dir).glob('*.png'))\n self.img_path.sort(key=lambda x: int(x.name.split('.')[0]))\n self.img_label = self.get_label(img_label)\n if img_label is not None:\n num_train = int(0.8 * len(self.img_path))\n index_list = list(range(len(self.img_path)))\n random.seed(42)\n indexes = random.sample(index_list, num_train)\n if not train:\n indexes = list(set(index_list) - set(indexes))\n # [index for index in index_list if index not in indexes]\n self.img_path = [self.img_path[index] for index in indexes]\n self.img_label = [self.img_label[index] for index in indexes]\n self.transform = transform\n\n '''根据下标返回数据(img和label)'''\n\n def __getitem__(self, index):\n if self.img_label is not None:\n img = Image.open(self.img_path[index]).convert('RGB')\n label = np.array(self.img_label[index], dtype=int)\n if self.transform is not None:\n img = self.transform(img)\n return img, torch.from_numpy(label)\n else:\n img = Image.open(self.img_path[index]).convert('RGB')\n if self.transform is not None:\n img = self.transform(img)\n return img, torch.from_numpy(np.array([]))\n\n '''返回数据集长度'''\n\n def __len__(self):\n return len(self.img_path)\n\n# if __name__ == '__main__':\n# # 加载数据集\n# transform_train = transforms.Compose([\n# transforms.RandomCrop(32, padding=4),\n# transforms.RandomHorizontalFlip(), # 图像一半的概率翻转,一半的概率不翻转\n# transforms.ToTensor(),\n# transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), # R,G,B每层的归一化用到的均值和方差\n# ])\n#\n# transform_test = transforms.Compose([\n# transforms.ToTensor(),\n# transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n# ])\n#\n# train_dataset = CifarDataset(img_dir='dataset/trainImages/', img_label='dataset/trainLabels.csv', train=True,\n# transform=transform_train)\n# val_dataset = CifarDataset(img_dir='dataset/trainImages/', img_label='dataset/trainLabels.csv', train=False,\n# transform=transform_test)\n","repo_name":"li554/resnet18-cifar10-classification","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"77"}
+{"seq_id":"29429667329","text":"__version__ = \"1.0\"\r\nimport analizador.util\r\n\r\nclass Analizador(analizador.util.AnalizadorBase):\r\n def __init__(self):\r\n analizador.util.AnalizadorBase.__init__(self)\r\n\r\n def analizar(self):\r\n r1=self.modulo.es_primo(1)\r\n if r1!=False:\r\n self.errores.append(\"El 1 no es primo y tu función retorna {0}\".format(r1))\r\n\r\n r1=self.modulo.es_primo(24)\r\n if r1!=False:\r\n self.errores.append(\"El 24 no es primo y tu función retorna {0}\".format(r1))\r\n\r\n r1=self.modulo.es_primo(3)\r\n if r1!=True:\r\n self.errores.append(\"El 3 es primo y tu función retorna {0}\".format(r1))\r\n\r\n r1=self.modulo.es_primo(11)\r\n if r1!=True:\r\n self.errores.append(\"El 11 es primo y tu función retorna {0}\".format(r1))\r\n","repo_name":"pabloschwarzenberg/grader","sub_path":"tema2_p1/grader.py","file_name":"grader.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"23009866607","text":"import pickle\n\nimport yfinance as yf\nimport pandas as pd\nimport os\nfrom yahoo_fin.stock_info import *\n\n\ndef predict(data,symb):\n\n if os.path.exists(f\"models/{symb}.sav\"):\n predictors = [\"Close\", \"Volume\", \"Open\", \"High\", \"Low\"]\n df = pd.DataFrame(data, columns=predictors)\n print(\"1\",df)\n print(\"HEleeeeeee\")\n\n loaded_model = pickle.load(open(f\"models/{symb}.sav\", 'rb'))\n result = loaded_model.predict(df)\n print(result)\n return result\n else:\n print(2)\n\n if os.path.exists(f\"{symb}.csv\"):\n sp500 = pd.read_csv(f\"{symb}.csv\", index_col=0)\n else:\n sp500 = yf.Ticker(symb)\n sp500 = sp500.history(period=\"max\")\n sp500.to_csv(f\"{symb}.csv\")\n\n sp500.index = pd.to_datetime(sp500.index)\n print(sp500)\n print(3)\n print(\"HEleeeeeee\")\n sp500.plot.line(y=\"Close\", use_index=True)\n del sp500[\"Dividends\"]\n del sp500[\"Stock Splits\"]\n sp500[\"Tomorrow\"] = sp500[\"Close\"].shift(-1)\n sp500[\"Target\"] = (sp500[\"Tomorrow\"] > sp500[\"Close\"]).astype(int)\n sp500 = sp500[50:].copy()\n from sklearn.ensemble import RandomForestClassifier\n\n model = RandomForestClassifier(n_estimators=100, min_samples_split=100, random_state=1)\n\n train = sp500.iloc[:-100]\n test = sp500.iloc[-100:]\n\n predictors = [\"Close\", \"Volume\", \"Open\", \"High\", \"Low\"]\n model.fit(train[predictors], train[\"Target\"])\n from sklearn.metrics import precision_score\n print(4)\n print(type(test[predictors]))\n filename = f\"models/{symb}.sav\"\n pickle.dump(model, open(filename, 'wb'))\n df = pd.DataFrame(data, columns=predictors)\n print(df)\n\n return model.predict(df)\n\n # predict\n\ndef get_data(symbol,period):\n ticker = yf.Ticker(symbol)\n todays_data = ticker.history(period=period)\n print(todays_data)\n data = [todays_data['Close'][0],todays_data['Volume'][0],todays_data[\"Open\"][0],todays_data[\"High\"][0],todays_data['Low'][0]]\n return [data]\n# return todays_data['Close'][0]\n#\n# print(get_current_price('TSLA'))\n\ndata = get_data('ADANIENT.NS','1d')\n# print(data)\nprint(predict(data,'ADANIENT.NS'))\n# d = get_quote_table('GOOG')\n# data = [d[\"Previous Close\"],d[\"Volume\"],d['Open'],d[]]\n# data = [[3951.570068359375, 5347140000, 3917.469970703125, 3956.6201171875, 3916.889892578125]]\n# #\n# print(predict(data, 'AAPL'))\n\n# 2023-03-20 00:00:00-04:00,3917.469970703125,3956.6201171875,3916.889892578125,3951.570068359375,5347140000,0.0,0.0\n# Date,Open,High,Low,Close,Volume,Dividends,Stock Splits\n\n# def predict(train, test, predictors, model):\n# model.fit(train[predictors], train[\"Target\"])\n# preds = model.predict(test[predictors])\n# preds = pd.Series(preds, index=test.index, name=\"Predictions\")\n# combined = pd.concat([test[\"Target\"], preds], axis=1)\n# return combined\n#\n#\n# def backtest(data, model, predictors, start=2500, step=250):\n# all_predictions = []\n#\n# for i in range(start, data.shape[0], step):\n# train = data.iloc[0:i].copy()\n# test = data.iloc[i:(i + step)].copy()\n# predictions = predict(train, test, predictors, model)\n# all_predictions.append(predictions)\n#\n# return pd.concat(all_predictions)\n#\n#\n# predictions = backtest(sp500, model, predictors)\n# predictions[\"Predictions\"].value_counts()\n#\n# precision_score(predictions[\"Target\"], predictions[\"Predictions\"])\n# predictions[\"Target\"].value_counts() / predictions.shape[0]\n# horizons = [2, 5, 60, 250, 1000]\n# new_predictors = []\n#\n# for horizon in horizons:\n# rolling_averages = sp500.rolling(horizon).mean()\n#\n# ratio_column = f\"Close_Ratio_{horizon}\"\n# sp500[ratio_column] = sp500[\"Close\"] / rolling_averages[\"Close\"]\n#\n# trend_column = f\"Trend_{horizon}\"\n# sp500[trend_column] = sp500.shift(1).rolling(horizon).sum()[\"Target\"]\n#\n# new_predictors += [ratio_column, trend_column]\n#\n# sp500 = sp500.dropna(subset=sp500.columns[sp500.columns != \"Tomorrow\"])\n# model = RandomForestClassifier(n_estimators=200, min_samples_split=50, random_state=1)\n# def predict(train, test, predictors, model):\n# model.fit(train[predictors], train[\"Target\"])\n# preds = model.predict_proba(test[predictors])[:,1]\n# preds[preds >=.6] = 1\n# preds[preds <.6] = 0\n# preds = pd.Series(preds, index=test.index, name=\"Predictions\")\n# combined = pd.concat([test[\"Target\"], preds], axis=1)\n# return combined\n# predictions = backtest(sp500, model, new_predictors)\n","repo_name":"niyatisrivastava/project-7-new","sub_path":"paper_trading/prediction/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":4583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"19851252401","text":"#The answer will be the coefficient of the middle term of the binomial expansion of the maze size * 2\n#I would have done it in java but sympy takes care of the binomial expansion for me\nimport sympy\nimport re\ndef getBinomial(mazeSize):\n binomSize = mazeSize*2\n x, y = sympy.symbols(\"x y\")\n formula = (x+y) ** binomSize\n return formula.expand().__repr__()\ndef cleanString(s, mazeSize):\n s = re.search(r\"\\d*[*]x[*][*]\"+str(mazeSize)+\"[*]y[*][*]\"+str(mazeSize), s).group()\n s = s.replace(\"*x**\"+str(mazeSize)+\"*y**\"+str(mazeSize), \"\")\n return s\ndef main():\n mazeSize = 20\n print(\"Answer:\", cleanString(getBinomial(mazeSize), mazeSize))\nmain()","repo_name":"2016rshah/Project-Euler","sub_path":"Python/ProjE15.py","file_name":"ProjE15.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"28374208116","text":"import dataclasses\nimport warnings\nfrom typing import Any, Dict, Iterable, Sequence, Tuple, Union, cast\n\nimport numpy as np\n\nfrom . import _xarray, constants\nfrom ._boundary_utils import bound_default_slice, shift_boundary_slice_tuple\nfrom ._optional_imports import cupy, dace, gt4py\nfrom .types import NumpyModule\n\n\nif cupy is None:\n import numpy as cupy\n\n__all__ = [\"Quantity\", \"QuantityMetadata\"]\n\n\n@dataclasses.dataclass\nclass QuantityMetadata:\n origin: Tuple[int, ...]\n \"the start of the computational domain\"\n extent: Tuple[int, ...]\n \"the shape of the computational domain\"\n dims: Tuple[str, ...]\n \"names of each dimension\"\n units: str\n \"units of the quantity\"\n data_type: type\n \"ndarray-like type used to store the data\"\n dtype: type\n \"dtype of the data in the ndarray-like object\"\n gt4py_backend: Union[str, None] = None\n \"backend to use for gt4py storages\"\n\n @property\n def dim_lengths(self) -> Dict[str, int]:\n \"\"\"mapping of dimension names to their lengths\"\"\"\n return dict(zip(self.dims, self.extent))\n\n @property\n def np(self) -> NumpyModule:\n \"\"\"numpy-like module used to interact with the data\"\"\"\n if issubclass(self.data_type, cupy.ndarray):\n return cupy\n elif issubclass(self.data_type, np.ndarray):\n return np\n else:\n raise TypeError(\n f\"quantity underlying data is of unexpected type {self.data_type}\"\n )\n\n\n@dataclasses.dataclass\nclass QuantityHaloSpec:\n \"\"\"Describe the memory to be exchanged, including size of the halo.\"\"\"\n\n n_points: int\n strides: Tuple[int]\n itemsize: int\n shape: Tuple[int]\n origin: Tuple[int, ...]\n extent: Tuple[int, ...]\n dims: Tuple[str, ...]\n numpy_module: NumpyModule\n dtype: Any\n\n\nclass BoundaryArrayView:\n def __init__(self, data, boundary_type, dims, origin, extent):\n self._data = data\n self._boundary_type = boundary_type\n self._dims = dims\n self._origin = origin\n self._extent = extent\n\n def __getitem__(self, index):\n if len(self._origin) == 0:\n if isinstance(index, tuple) and len(index) > 0:\n raise IndexError(\"more than one index given for a zero-dimension array\")\n elif isinstance(index, slice) and index != slice(None, None, None):\n raise IndexError(\"cannot slice a zero-dimension array\")\n else:\n return self._data # array[()] does not return an ndarray\n else:\n return self._data[self._get_array_index(index)]\n\n def __setitem__(self, index, value):\n self._data[self._get_array_index(index)] = value\n\n def _get_array_index(self, index):\n if isinstance(index, list):\n index = tuple(index)\n if not isinstance(index, tuple):\n index = (index,)\n if len(index) > len(self._dims):\n raise IndexError(\n f\"{len(index)} is too many indices for a \"\n f\"{len(self._dims)}-dimensional quantity\"\n )\n if len(index) < len(self._dims):\n index = index + (slice(None, None),) * (len(self._dims) - len(index))\n return shift_boundary_slice_tuple(\n self._dims, self._origin, self._extent, self._boundary_type, index\n )\n\n def sel(self, **kwargs: Union[slice, int]) -> np.ndarray:\n \"\"\"Convenience method to perform indexing using dimension names\n without knowing dimension order.\n\n Args:\n **kwargs: slice/index to retrieve for a given dimension name\n\n Returns:\n view_selection: an ndarray-like selection of the given indices\n on `self.view`\n \"\"\"\n return self[tuple(kwargs.get(dim, slice(None, None)) for dim in self._dims)]\n\n\nclass BoundedArrayView:\n \"\"\"\n A container of objects which provide indexing relative to corners and edges\n of the computational domain for convenience.\n\n Default start and end indices for all dimensions are modified to be the\n start and end of the compute domain. When using edge and corner attributes, it is\n recommended to explicitly write start and end offsets to avoid confusion.\n\n Indexing on the object itself (view[:]) is offset by the origin, and default\n start and end indices are modified to be the start and end of the compute domain.\n\n For corner attributes e.g. `northwest`, modified indexing is done for the two\n axes according to the edges which make up the corner. In other words, indexing\n is offset relative to the intersection of the two edges which make the corner.\n\n For `interior`, start indices of the horizontal dimensions are relative to the\n origin, and end indices are relative to the origin + extent. For example,\n view.interior[0:0, 0:0, :] would retrieve the entire compute domain for an x/y/z\n array, while view.interior[-1:1, -1:1, :] would also include one halo point.\n \"\"\"\n\n def __init__(\n self, array, dims: Sequence[str], origin: Sequence[int], extent: Sequence[int]\n ):\n self._data = array\n self._dims = tuple(dims)\n self._origin = tuple(origin)\n self._extent = tuple(extent)\n self._northwest = BoundaryArrayView(\n array, constants.NORTHWEST, dims, origin, extent\n )\n self._northeast = BoundaryArrayView(\n array, constants.NORTHEAST, dims, origin, extent\n )\n self._southwest = BoundaryArrayView(\n array, constants.SOUTHWEST, dims, origin, extent\n )\n self._southeast = BoundaryArrayView(\n array, constants.SOUTHEAST, dims, origin, extent\n )\n self._interior = BoundaryArrayView(\n array, constants.INTERIOR, dims, origin, extent\n )\n\n @property\n def origin(self) -> Tuple[int, ...]:\n \"\"\"the start of the computational domain\"\"\"\n return self._origin\n\n @property\n def extent(self) -> Tuple[int, ...]:\n \"\"\"the shape of the computational domain\"\"\"\n return self._extent\n\n def __getitem__(self, index):\n if len(self.origin) == 0:\n if isinstance(index, tuple) and len(index) > 0:\n raise IndexError(\"more than one index given for a zero-dimension array\")\n elif isinstance(index, slice) and index != slice(None, None, None):\n raise IndexError(\"cannot slice a zero-dimension array\")\n else:\n return self._data # array[()] does not return an ndarray\n else:\n return self._data[self._get_compute_index(index)]\n\n def __setitem__(self, index, value):\n self._data[self._get_compute_index(index)] = value\n\n def _get_compute_index(self, index):\n if not isinstance(index, (tuple, list)):\n index = (index,)\n if len(index) > len(self._dims):\n raise IndexError(\n f\"{len(index)} is too many indices for a \"\n f\"{len(self._dims)}-dimensional quantity\"\n )\n index = fill_index(index, len(self._data.shape))\n shifted_index = []\n for entry, origin, extent in zip(index, self.origin, self.extent):\n if isinstance(entry, slice):\n shifted_slice = shift_slice(entry, origin, extent)\n shifted_index.append(\n bound_default_slice(shifted_slice, origin, origin + extent)\n )\n elif entry is None:\n shifted_index.append(entry)\n else:\n shifted_index.append(entry + origin)\n return tuple(shifted_index)\n\n @property\n def northwest(self) -> BoundaryArrayView:\n return self._northwest\n\n @property\n def northeast(self) -> BoundaryArrayView:\n return self._northeast\n\n @property\n def southwest(self) -> BoundaryArrayView:\n return self._southwest\n\n @property\n def southeast(self) -> BoundaryArrayView:\n return self._southeast\n\n @property\n def interior(self) -> BoundaryArrayView:\n return self._interior\n\n\ndef ensure_int_tuple(arg, arg_name):\n return_list = []\n for item in arg:\n try:\n return_list.append(int(item))\n except ValueError:\n raise TypeError(\n f\"tuple arg {arg_name}={arg} contains item {item} of \"\n f\"unexpected type {type(item)}\"\n )\n return tuple(return_list)\n\n\ndef _validate_quantity_property_lengths(shape, dims, origin, extent):\n n_dims = len(shape)\n for var, desc in (\n (dims, \"dimension names\"),\n (origin, \"origins\"),\n (extent, \"extents\"),\n ):\n if len(var) != n_dims:\n raise ValueError(\n f\"received {len(var)} {desc} for {n_dims} dimensions: {var}\"\n )\n\n\nclass Quantity:\n \"\"\"\n Data container for physical quantities.\n \"\"\"\n\n def __init__(\n self,\n data,\n dims: Sequence[str],\n units: str,\n origin: Sequence[int] = None,\n extent: Sequence[int] = None,\n gt4py_backend: Union[str, None] = None,\n ):\n \"\"\"\n Initialize a Quantity.\n\n Args:\n data: ndarray-like object containing the underlying data\n dims: dimension names for each axis\n units: units of the quantity\n origin: first point in data within the computational domain\n extent: number of points along each axis within the computational domain\n gt4py_backend: backend to use for gt4py storages, if not given this will\n be derived from a Storage if given as the data argument, otherwise the\n storage attribute is disabled and will raise an exception. Will raise\n a TypeError if this is given with a gt4py storage type as data\n \"\"\"\n if origin is None:\n origin = (0,) * len(dims) # default origin at origin of array\n else:\n origin = tuple(origin)\n\n if extent is None:\n extent = tuple(length - start for length, start in zip(data.shape, origin))\n else:\n extent = tuple(extent)\n\n if isinstance(data, (int, float, list)):\n # If converting basic data, use a numpy ndarray.\n data = np.asarray(data)\n\n if not isinstance(data, (np.ndarray, cupy.ndarray)):\n raise TypeError(\n f\"Only supports numpy.ndarray and cupy.ndarray, got {type(data)}\"\n )\n\n if gt4py_backend is not None:\n gt4py_backend_cls = gt4py.cartesian.backend.from_name(gt4py_backend)\n assert gt4py_backend_cls is not None\n is_optimal_layout = gt4py_backend_cls.storage_info[\"is_optimal_layout\"]\n\n dimensions: Tuple[Union[str, int], ...] = tuple(\n [\n axis\n if any(dim in axis_dims for axis_dims in constants.SPATIAL_DIMS)\n else str(data.shape[index])\n for index, (dim, axis) in enumerate(\n zip(dims, (\"I\", \"J\", \"K\", *([None] * (len(dims) - 3))))\n )\n ]\n )\n\n self._data = (\n data\n if is_optimal_layout(data, dimensions)\n else self._initialize_data(\n data,\n origin=origin,\n gt4py_backend=gt4py_backend,\n dimensions=dimensions,\n )\n )\n else:\n if data is None:\n raise TypeError(\"requires 'data' to be passed\")\n # We have no info about the gt4py_backend, so just assign it.\n self._data = data\n\n _validate_quantity_property_lengths(data.shape, dims, origin, extent)\n self._metadata = QuantityMetadata(\n origin=ensure_int_tuple(origin, \"origin\"),\n extent=ensure_int_tuple(extent, \"extent\"),\n dims=tuple(dims),\n units=units,\n data_type=type(self._data),\n dtype=data.dtype,\n gt4py_backend=gt4py_backend,\n )\n self._attrs = {} # type: ignore[var-annotated]\n self._compute_domain_view = BoundedArrayView(\n self.data, self.dims, self.origin, self.extent\n )\n\n @classmethod\n def from_data_array(\n cls,\n data_array: _xarray.DataArray,\n origin: Sequence[int] = None,\n extent: Sequence[int] = None,\n gt4py_backend: Union[str, None] = None,\n ) -> \"Quantity\":\n \"\"\"\n Initialize a Quantity from an xarray.DataArray.\n\n Args:\n data_array\n origin: first point in data within the computational domain\n extent: number of points along each axis within the computational domain\n gt4py_backend: backend to use for gt4py storages, if not given this will\n be derived from a Storage if given as the data argument, otherwise the\n storage attribute is disabled and will raise an exception\n \"\"\"\n if \"units\" not in data_array.attrs:\n raise ValueError(\"need units attribute to create Quantity from DataArray\")\n return cls(\n data_array.values,\n cast(Tuple[str], data_array.dims),\n data_array.attrs[\"units\"],\n origin=origin,\n extent=extent,\n gt4py_backend=gt4py_backend,\n )\n\n def halo_spec(self, n_halo: int) -> QuantityHaloSpec:\n return QuantityHaloSpec(\n n_halo,\n self.data.strides,\n self.data.itemsize,\n self.data.shape,\n self.metadata.origin,\n self.metadata.extent,\n self.metadata.dims,\n self.np,\n self.metadata.dtype,\n )\n\n def __repr__(self):\n return (\n f\"Quantity(\\n data=\\n{self.data},\\n dims={self.dims},\\n\"\n f\" units={self.units},\\n origin={self.origin},\\n\"\n f\" extent={self.extent}\\n)\"\n )\n\n def sel(self, **kwargs: Union[slice, int]) -> np.ndarray:\n \"\"\"Convenience method to perform indexing on `view` using dimension names\n without knowing dimension order.\n\n Args:\n **kwargs: slice/index to retrieve for a given dimension name\n\n Returns:\n view_selection: an ndarray-like selection of the given indices\n on `self.view`\n \"\"\"\n return self.view[tuple(kwargs.get(dim, slice(None, None)) for dim in self.dims)]\n\n def _initialize_data(self, data, origin, gt4py_backend: str, dimensions: Tuple):\n \"\"\"Allocates an ndarray with optimal memory layout, and copies the data over.\"\"\"\n storage = gt4py.storage.from_array(\n data,\n data.dtype,\n backend=gt4py_backend,\n aligned_index=origin,\n dimensions=dimensions,\n )\n return storage\n\n @property\n def metadata(self) -> QuantityMetadata:\n return self._metadata\n\n @property\n def units(self) -> str:\n \"\"\"units of the quantity\"\"\"\n return self.metadata.units\n\n @property\n def gt4py_backend(self) -> Union[str, None]:\n return self.metadata.gt4py_backend\n\n @property\n def attrs(self) -> dict:\n return dict(**self._attrs, units=self._metadata.units)\n\n @property\n def dims(self) -> Tuple[str, ...]:\n \"\"\"names of each dimension\"\"\"\n return self.metadata.dims\n\n @property\n def values(self) -> np.ndarray:\n warnings.warn(\n \"values exists only for backwards-compatibility with \"\n \"DataArray and will be removed, use .view[:] instead\",\n DeprecationWarning,\n )\n return_array = np.asarray(self.view[:])\n return_array.flags.writeable = False\n return return_array\n\n @property\n def view(self) -> BoundedArrayView:\n \"\"\"a view into the computational domain of the underlying data\"\"\"\n return self._compute_domain_view\n\n @property\n def data(self) -> Union[np.ndarray, cupy.ndarray]:\n \"\"\"the underlying array of data\"\"\"\n return self._data\n\n @property\n def origin(self) -> Tuple[int, ...]:\n \"\"\"the start of the computational domain\"\"\"\n return self.metadata.origin\n\n @property\n def extent(self) -> Tuple[int, ...]:\n \"\"\"the shape of the computational domain\"\"\"\n return self.metadata.extent\n\n @property\n def data_array(self) -> _xarray.DataArray:\n return _xarray.DataArray(self.view[:], dims=self.dims, attrs=self.attrs)\n\n @property\n def np(self) -> NumpyModule:\n return self.metadata.np\n\n @property\n def __array_interface__(self):\n return self.data.__array_interface__\n\n @property\n def __cuda_array_interface__(self):\n return self.data.__cuda_array_interface__\n\n @property\n def shape(self):\n return self.data.shape\n\n def __descriptor__(self) -> Any:\n \"\"\"The descriptor is a property that dace uses.\n This relies on `dace` capacity to read out data from the buffer protocol.\n If the internal data given doesn't follow the protocol it will most likely\n fail.\n \"\"\"\n if dace:\n return dace.data.create_datadescriptor(self.data)\n else:\n raise ImportError(\n \"Attempt to use DaCe orchestrated backend but \"\n \"DaCe module is not available.\"\n )\n\n def transpose(self, target_dims: Sequence[Union[str, Iterable[str]]]) -> \"Quantity\":\n \"\"\"Change the dimension order of this Quantity.\n\n Args:\n target_dims: a list of output dimensions. Instead of a single dimension\n name, an iterable of dimensions can be used instead for any entries.\n For example, you may want to use pace.util.X_DIMS to place an\n x-dimension without knowing whether it is on cell centers or interfaces.\n\n Returns:\n transposed: Quantity with the requested output dimension order\n\n Raises:\n ValueError: if any of the target dimensions do not exist on this Quantity,\n or if this Quantity contains multiple values from an iterable entry\n\n Examples:\n Let's say we have a cell-centered variable:\n\n >>> import pace.util\n >>> import numpy as np\n >>> quantity = pace.util.Quantity(\n ... data=np.zeros([2, 3, 4]),\n ... dims=[pace.util.X_DIM, pace.util.Y_DIM, pace.util.Z_DIM],\n ... units=\"m\",\n ... )\n\n If you know you are working with cell-centered variables, you can do:\n\n >>> from pace.util import X_DIM, Y_DIM, Z_DIM\n >>> transposed_quantity = quantity.transpose([X_DIM, Y_DIM, Z_DIM])\n\n To support re-ordering without checking whether quantities are on\n cell centers or interfaces, the API supports giving a list of dimension\n names for dimensions. For example, to re-order to X-Y-Z dimensions\n regardless of the grid the variable is on, one could do:\n\n >>> from pace.util import X_DIMS, Y_DIMS, Z_DIMS\n >>> transposed_quantity = quantity.transpose([X_DIMS, Y_DIMS, Z_DIMS])\n \"\"\"\n target_dims = _collapse_dims(target_dims, self.dims)\n transpose_order = [self.dims.index(dim) for dim in target_dims]\n transposed = Quantity(\n self.np.transpose(self.data, transpose_order), # type: ignore[attr-defined]\n dims=transpose_sequence(self.dims, transpose_order),\n units=self.units,\n origin=transpose_sequence(self.origin, transpose_order),\n extent=transpose_sequence(self.extent, transpose_order),\n gt4py_backend=self.gt4py_backend,\n )\n transposed._attrs = self._attrs\n return transposed\n\n\ndef transpose_sequence(sequence, order):\n return sequence.__class__(sequence[i] for i in order)\n\n\ndef _collapse_dims(target_dims, dims):\n return_list = []\n for target in target_dims:\n if isinstance(target, str):\n if target in dims:\n return_list.append(target)\n else:\n raise ValueError(\n f\"requested dimension {target} is not defined in \"\n f\"quantity dimensions {dims}\"\n )\n elif isinstance(target, Iterable):\n matches = [d for d in target if d in dims]\n if len(matches) > 1:\n raise ValueError(\n f\"multiple matches for {target} found in quantity dimensions {dims}\"\n )\n elif len(matches) == 0:\n raise ValueError(\n f\"no matches for {target} found in quantity dimensions {dims}\"\n )\n else:\n return_list.append(matches[0])\n return return_list\n\n\ndef fill_index(index, length):\n return tuple(index) + (slice(None, None, None),) * (length - len(index))\n\n\ndef shift_slice(slice_in, shift, extent):\n start = shift_index(slice_in.start, shift, extent)\n stop = shift_index(slice_in.stop, shift, extent)\n return slice(start, stop, slice_in.step)\n\n\ndef shift_index(current_value, shift, extent):\n if current_value is None:\n new_value = None\n else:\n new_value = current_value + shift\n if new_value < 0:\n new_value = extent + new_value\n return new_value\n","repo_name":"ai2cm/pace","sub_path":"util/pace/util/quantity.py","file_name":"quantity.py","file_ext":"py","file_size_in_byte":21498,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"77"}
+{"seq_id":"7522457917","text":"from django.urls import path,include\nfrom .views import LoginView,RagisterUserAPIView\nfrom .views import UserConsumer,loginPage,chatPage,video,logoutview\nurlpatterns = [\n path('LoginUser/',LoginView.as_view(),name=\"Login\"),\n path('ragister/',RagisterUserAPIView.as_view(),name=\"Ragister\"),\n path('usersLists/',UserConsumer.as_asgi(),name=\"Ragister\"),\n path('',loginPage,name=\"LoginPage\"),\n path('logoutview/',logoutview,name=\"logoutview\"),\n # path('login/',loginPage,name=\"LoginPage\"),\n path('chat/',chatPage,name=\"chatPage\"),\n path('video//',video,name='video'),\n path('',include('rest_framework.urls')),\n \n]","repo_name":"Akshay-Shingala/demo-Chat-App","sub_path":"demoChatApp/chatApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"23516407061","text":"#!/usr/bin/env python\n\n# Reads in a PDF file,\nimport os\nimport argparse\nfrom PyPDF2 import PdfReader, PdfWriter\n\ndef splitpdfs(args):\n if \"SplitPDFs\" not in args.outputdir:\n OutputPath = f\"SplitPDFs/{args.outputdir}\"\n else:\n OutputPath = f\"{args.outputdir}\"\n fname = os.path.splitext(os.path.basename(args.inputfile))[0]\n pdf = PdfReader(args.inputfile)\n numpages = len(pdf.pages)\n fillsize = len(str(numpages))\n for page in range(numpages):\n pdf_writer = PdfWriter()\n pdf_writer.add_page(pdf.pages[page])\n pgnum = f'{(page+1):0{fillsize}d}'\n output_filename = f'{OutputPath}/{fname}_page_{pgnum}.pdf'\n if os.path.exists(output_filename) and not args.overwrite:\n print(f'Will Not Overwrite: {output_filename}')\n continue\n if args.writefiles:\n # print(f'Created: {output_filename}')\n with open(output_filename, 'wb') as out:\n pdf_writer.write(out)\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Split a PDF into 1 page files\")\n parser.add_argument('inputfile', help=\"Input PDF\")\n parser.add_argument('outputdir', help=\"Output Directory (usually SplitPDFs/County)\")\n parser.add_argument('--writefiles', action='store_true', default=True, help=\"write files\")\n parser.add_argument('--overwrite', action='store_true', help=\"overwrite files\")\n parser.add_argument('--verbose', action='store_true', help=\"verbose\")\n args = parser.parse_args()\n splitpdfs(args)\n\nif __name__ == '__main__':\n main()\n","repo_name":"moonshiner/openelections-data-ottowa-mi","sub_path":"splitpdf.py","file_name":"splitpdf.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"22211939910","text":"import numpy as np\nimport cv2\n\n\ndef _pad_width_center(w, target_w):\n left = (target_w - w) // 2\n right = target_w - w - left\n return left, right\n\n\ndef _pad_width_right(w, target_w):\n return 0, target_w - w\n\n\ndef _pad_height_center(h, target_h):\n top = (target_h - h) // 2\n bottom = target_h - h - top\n return top, bottom\n\n\ndef _pad_height_bottom(h, target_h):\n return 0, target_h - h\n\n\ndef VStack(*imgs, align='center'):\n max_w = max([_.shape[1] for _ in imgs])\n imgs_padded = []\n\n if align == 'center':\n for img in imgs:\n left, right = _pad_width_center(img.shape[1], max_w)\n imgs_padded.append(cv2.copyMakeBorder(img, 0, 0, left, right, cv2.BORDER_CONSTANT))\n\n elif align == 'left':\n for img in imgs:\n left, right = _pad_width_right(img.shape[1], max_w)\n imgs_padded.append(cv2.copyMakeBorder(img, 0, 0, left, right, cv2.BORDER_CONSTANT))\n\n else:\n raise ValueError('Unsupported alignment %s' % align)\n\n return np.concatenate(imgs_padded, axis=0)\n\n\ndef HStack(*imgs, align='center'):\n max_h = max([_.shape[0] for _ in imgs])\n\n imgs_padded = []\n\n if align == 'center':\n for img in imgs:\n top, bottom = _pad_height_center(img.shape[0], max_h)\n imgs_padded.append(cv2.copyMakeBorder(img, top, bottom, 0, 0, cv2.BORDER_CONSTANT))\n\n elif align == 'top':\n for img in imgs:\n top, bottom = _pad_height_bottom(img.shape[0], max_h)\n imgs_padded.append(cv2.copyMakeBorder(img, top, bottom, 0, 0, cv2.BORDER_CONSTANT))\n\n else:\n raise ValueError('Unsupported alignment %s' % align)\n\n return np.concatenate(imgs_padded, axis=1)\n\n\ndef Grid(*imgs, n_col=1, align='center'):\n chunks = [imgs[i:i + n_col] for i in range(0, len(imgs), n_col)]\n row_imgs = [HStack(*_, align=align) for _ in chunks]\n return VStack(*row_imgs, align=align)\n","repo_name":"xymeng/rmp_nav","sub_path":"rmp_nav/common/image_combiner.py","file_name":"image_combiner.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"77"}
+{"seq_id":"33725129217","text":"import json\nfrom flask import Flask, request\nimport requests\napp = Flask(__name__)\napp.debug = True\n\n\ndef apiCall(AnimeShowName):\n #Connect to the API anf get the JSON file.\n api_url='https://animechan.vercel.app/api/quotes/anime?title=' + AnimeShowName\n headers = {'Content-Type': 'application/json'} #Set the HTTP header for the API request\n response = requests.get(api_url, headers=headers) #Connect to openweather and read the JSON response.\n r=response.json() #Conver the JSON string to a dict for easier parsing.\n if 'error' in r:\n return '{\"fulfillmentMessages\": [ {\"text\": {\"text\": [\" No quotes available for the given/empty Anime input. Some Anime suggestions are : Hyouka , Youjo Senki , Princess Mononoke, Mayoiga, SERVAMP, Gunbuster \"]} } ]}' \n else:\n return '{\"fulfillmentMessages\": [ {\"text\": {\"text\": [\\\" Quote from '+ AnimeShowName +' anime :' + r[0]['quote'] + ' \\\"]} } ]}'\n\n@app.route('/')\ndef hello():\n return ' {\"Student Number\": \"200530943\", \"Student Name\":\"Romana Hussain\"}'\n\n@app.route('/webhook',methods=['POST'])\ndef index():\n\n body = request.json\n\n if(len(body['queryResult']['parameters']['AnimeShowName'])!=0):\n return apiCall(body['queryResult']['parameters']['AnimeShowName'])\n\n elif (len(body['queryResult']['parameters']['AnimeShowName1'])!=0):\n return apiCall(body['queryResult']['parameters']['AnimeShowName1'])\n\n elif (len(body['queryResult']['parameters']['AnimeShowName2'])!=0):\n return apiCall(body['queryResult']['parameters']['AnimeShowName2'])\n\n elif (len(body['queryResult']['parameters']['AnimeShowName3'])!=0):\n return apiCall(body['queryResult']['parameters']['AnimeShowName3'])\n\n elif (len(body['queryResult']['parameters']['AnimeShowName4'])!=0):\n return apiCall(body['queryResult']['parameters']['AnimeShowName4'])\n \n else :\n return apiCall(\"\")","repo_name":"RomanaHussainAjmal/RomanaChatBot","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"22178185796","text":"r\"\"\"Gates for Qubitizing the Hubbard Model.\n\nThis follows section V. of the [Linear T Paper](https://arxiv.org/abs/1805.03662).\n\nThe 2D Hubbard model is a special case of the electronic structure Hamiltonian\nrestricted to spins on a planar grid.\n\n$$\nH = -t \\sum_{\\langle p,q \\rangle, \\sigma} a_{p,\\sigma}^\\dagger a_{q,\\sigma}\n + \\frac{u}{2} \\sum_{p,\\alpha\\ne\\beta} n_{p, \\alpha} n_{p, \\beta}\n$$\n\nUnder the Jordan-Wigner transformation, this is\n\n$$\n\\def\\Zvec{\\overrightarrow{Z}}\n\\def\\hop#1{#1_{p,\\sigma} \\Zvec #1_{q,\\sigma}}\nH = -\\frac{t}{2} \\sum_{\\langle p,q \\rangle, \\sigma} (\\hop{X} + \\hop{Y})\n + \\frac{u}{8} \\sum_{p,\\alpha\\ne\\beta} Z_{p,\\alpha}Z_{p,\\beta}\n - \\frac{u}{4} \\sum_{p,\\sigma} Z_{p,\\sigma} + \\frac{uN}{4}\\mathbb{1}\n$$\n\n\nThis model consists of a PREPARE and SELECT operation where our selection operation has indices\nfor $p$, $\\alpha$, $q$, and $\\beta$ as well as two indicator bits $U$ and $V$. There are four cases\nconsidered in both the PREPARE and SELECT operations corresponding to the terms in the Hamiltonian:\n\n - $U=1$, single-body Z\n - $V=1$, spin-spin ZZ term\n - $pq$, YZY term.\n\nSee the documentation for `PrepareHubbard` and `SelectHubbard` for details.\n\"\"\"\nfrom typing import Collection, Optional, Sequence, Tuple, Union\nfrom numpy.typing import NDArray\n\nimport attr\nimport cirq\nimport numpy as np\nfrom cirq._compat import cached_property\nfrom cirq_ft import infra\nfrom cirq_ft.algos import and_gate, apply_gate_to_lth_target, arithmetic_gates\nfrom cirq_ft.algos import prepare_uniform_superposition as prep_u\nfrom cirq_ft.algos import (\n qubitization_walk_operator,\n select_and_prepare,\n selected_majorana_fermion,\n swap_network,\n)\n\n\n@attr.frozen\nclass SelectHubbard(select_and_prepare.SelectOracle):\n r\"\"\"The SELECT operation optimized for the 2D Hubbard model.\n\n In contrast to the arbitrary chemistry Hamiltonian, we:\n - explicitly consider the two dimensions of indices to permit optimization of the circuits.\n - dispense with the `theta` parameter.\n\n If neither $U$ nor $V$ is set we apply the kinetic terms of the Hamiltonian:\n\n $$\n -\\hop{X} \\quad p < q \\\\\n -\\hop{Y} \\quad p > q\n $$\n\n If $U$ is set we know $(p,\\alpha)=(q,\\beta)$ and apply the single-body term: $-Z_{p,\\alpha}$.\n If $V$ is set we know $p=q, \\alpha=0$, and $\\beta=1$ and apply the spin term:\n $Z_{p,\\alpha}Z_{p,\\beta}$\n\n The circuit for implementing $\\textit{C-SELECT}_{Hubbard}$ has a T-cost of $10 * N + log(N)$\n and $0$ rotations.\n\n\n Args:\n x_dim: the number of sites along the x axis.\n y_dim: the number of sites along the y axis.\n control_val: Optional bit specifying the control value for constructing a controlled\n version of this gate. Defaults to None, which means no control.\n\n Signature:\n control: A control bit for the entire gate.\n U: Whether we're applying the single-site part of the potential.\n V: Whether we're applying the pairwise part of the potential.\n p_x: First set of site indices, x component.\n p_y: First set of site indices, y component.\n alpha: First set of sites' spin indicator.\n q_x: Second set of site indices, x component.\n q_y: Second set of site indices, y component.\n beta: Second set of sites' spin indicator.\n target: The system register to apply the select operation.\n\n References:\n Section V. and Fig. 19 of https://arxiv.org/abs/1805.03662.\n \"\"\"\n\n x_dim: int\n y_dim: int\n control_val: Optional[int] = None\n\n def __attrs_post_init__(self):\n if self.x_dim != self.y_dim:\n raise NotImplementedError(\"Currently only supports the case where x_dim=y_dim.\")\n\n @cached_property\n def control_registers(self) -> Tuple[infra.Register, ...]:\n return () if self.control_val is None else (infra.Register('control', 1),)\n\n @cached_property\n def selection_registers(self) -> Tuple[infra.SelectionRegister, ...]:\n return (\n infra.SelectionRegister('U', 1, 2),\n infra.SelectionRegister('V', 1, 2),\n infra.SelectionRegister('p_x', (self.x_dim - 1).bit_length(), self.x_dim),\n infra.SelectionRegister('p_y', (self.y_dim - 1).bit_length(), self.y_dim),\n infra.SelectionRegister('alpha', 1, 2),\n infra.SelectionRegister('q_x', (self.x_dim - 1).bit_length(), self.x_dim),\n infra.SelectionRegister('q_y', (self.y_dim - 1).bit_length(), self.y_dim),\n infra.SelectionRegister('beta', 1, 2),\n )\n\n @cached_property\n def target_registers(self) -> Tuple[infra.Register, ...]:\n return (infra.Register('target', self.x_dim * self.y_dim * 2),)\n\n @cached_property\n def signature(self) -> infra.Signature:\n return infra.Signature(\n [*self.control_registers, *self.selection_registers, *self.target_registers]\n )\n\n def decompose_from_registers(\n self,\n *,\n context: cirq.DecompositionContext,\n **quregs: NDArray[cirq.Qid], # type:ignore[type-var]\n ) -> cirq.OP_TREE:\n p_x, p_y, q_x, q_y = quregs['p_x'], quregs['p_y'], quregs['q_x'], quregs['q_y']\n U, V, alpha, beta = quregs['U'], quregs['V'], quregs['alpha'], quregs['beta']\n control, target = quregs.get('control', ()), quregs['target']\n\n yield selected_majorana_fermion.SelectedMajoranaFermionGate(\n selection_regs=(\n infra.SelectionRegister('alpha', 1, 2),\n infra.SelectionRegister(\n 'p_y', self.signature.get_left('p_y').total_bits(), self.y_dim\n ),\n infra.SelectionRegister(\n 'p_x', self.signature.get_left('p_x').total_bits(), self.x_dim\n ),\n ),\n control_regs=self.control_registers,\n target_gate=cirq.Y,\n ).on_registers(control=control, p_x=p_x, p_y=p_y, alpha=alpha, target=target)\n\n yield swap_network.MultiTargetCSwap.make_on(control=V, target_x=p_x, target_y=q_x)\n yield swap_network.MultiTargetCSwap.make_on(control=V, target_x=p_y, target_y=q_y)\n yield swap_network.MultiTargetCSwap.make_on(control=V, target_x=alpha, target_y=beta)\n\n q_selection_regs = (\n infra.SelectionRegister('beta', 1, 2),\n infra.SelectionRegister('q_y', self.signature.get_left('q_y').total_bits(), self.y_dim),\n infra.SelectionRegister('q_x', self.signature.get_left('q_x').total_bits(), self.x_dim),\n )\n yield selected_majorana_fermion.SelectedMajoranaFermionGate(\n selection_regs=q_selection_regs, control_regs=self.control_registers, target_gate=cirq.X\n ).on_registers(control=control, q_x=q_x, q_y=q_y, beta=beta, target=target)\n\n yield swap_network.MultiTargetCSwap.make_on(control=V, target_x=alpha, target_y=beta)\n yield swap_network.MultiTargetCSwap.make_on(control=V, target_x=p_y, target_y=q_y)\n yield swap_network.MultiTargetCSwap.make_on(control=V, target_x=p_x, target_y=q_x)\n\n yield cirq.S(*control) ** -1 if control else cirq.global_phase_operation(\n -1j\n ) # Fix errant i from XY=iZ\n yield cirq.Z(*U).controlled_by(*control) # Fix errant -1 from multiple pauli applications\n\n target_qubits_for_apply_to_lth_gate = [\n target[np.ravel_multi_index((1, qy, qx), (2, self.y_dim, self.x_dim))]\n for qx in range(self.x_dim)\n for qy in range(self.y_dim)\n ]\n\n yield apply_gate_to_lth_target.ApplyGateToLthQubit(\n selection_regs=(\n infra.SelectionRegister(\n 'q_y', self.signature.get_left('q_y').total_bits(), self.y_dim\n ),\n infra.SelectionRegister(\n 'q_x', self.signature.get_left('q_x').total_bits(), self.x_dim\n ),\n ),\n nth_gate=lambda *_: cirq.Z,\n control_regs=infra.Register('control', 1 + infra.total_bits(self.control_registers)),\n ).on_registers(\n q_x=q_x, q_y=q_y, control=[*V, *control], target=target_qubits_for_apply_to_lth_gate\n )\n\n def controlled(\n self,\n num_controls: Optional[int] = None,\n control_values: Optional[\n Union[cirq.ops.AbstractControlValues, Sequence[Union[int, Collection[int]]]]\n ] = None,\n control_qid_shape: Optional[Tuple[int, ...]] = None,\n ) -> 'SelectHubbard':\n if num_controls is None:\n num_controls = 1\n if control_values is None:\n control_values = [1] * num_controls\n if (\n isinstance(control_values, Sequence)\n and isinstance(control_values[0], int)\n and len(control_values) == 1\n and self.control_val is None\n ):\n return SelectHubbard(self.x_dim, self.y_dim, control_val=control_values[0])\n raise NotImplementedError(\n f'Cannot create a controlled version of {self} with control_values={control_values}.'\n )\n\n def _circuit_diagram_info_(self, args: cirq.CircuitDiagramInfoArgs) -> cirq.CircuitDiagramInfo:\n info = super(SelectHubbard, self)._circuit_diagram_info_(args)\n if self.control_val is None:\n return info\n ctrl = ('@' if self.control_val else '@(0)',)\n return info.with_wire_symbols(ctrl + info.wire_symbols[0:1] + info.wire_symbols[2:])\n\n def __repr__(self) -> str:\n return f'cirq_ft.SelectHubbard({self.x_dim}, {self.y_dim}, {self.control_val})'\n\n\n@attr.frozen\nclass PrepareHubbard(select_and_prepare.PrepareOracle):\n r\"\"\"The PREPARE operation optimized for the 2D Hubbard model.\n\n In contrast to the arbitrary chemistry Hamiltonian, we:\n - explicitly consider the two dimensions of indices to permit optimization of the circuits.\n - dispense with the `theta` parameter.\n\n The circuit for implementing $\\textit{PREPARE}_{Hubbard}$ has a T-cost of $O(log(N)$\n and uses $O(1)$ single qubit rotations.\n\n Args:\n x_dim: the number of sites along the x axis.\n y_dim: the number of sites along the y axis.\n t: coefficient for hopping terms in the Hubbard model hamiltonian.\n mu: coefficient for single body Z term and two-body ZZ terms in the Hubbard model\n hamiltonian.\n\n Signature:\n control: A control bit for the entire gate.\n U: Whether we're applying the single-site part of the potential.\n V: Whether we're applying the pairwise part of the potential.\n p_x: First set of site indices, x component.\n p_y: First set of site indices, y component.\n alpha: First set of sites' spin indicator.\n q_x: Second set of site indices, x component.\n q_y: Second set of site indices, y component.\n beta: Second set of sites' spin indicator.\n target: The system register to apply the select operation.\n junk: Temporary Work space.\n\n References:\n Section V. and Fig. 20 of https://arxiv.org/abs/1805.03662.\n \"\"\"\n\n x_dim: int\n y_dim: int\n t: int\n mu: int\n\n def __attrs_post_init__(self):\n if self.x_dim != self.y_dim:\n raise NotImplementedError(\"Currently only supports the case where x_dim=y_dim.\")\n\n @cached_property\n def selection_registers(self) -> Tuple[infra.SelectionRegister, ...]:\n return (\n infra.SelectionRegister('U', 1, 2),\n infra.SelectionRegister('V', 1, 2),\n infra.SelectionRegister('p_x', (self.x_dim - 1).bit_length(), self.x_dim),\n infra.SelectionRegister('p_y', (self.y_dim - 1).bit_length(), self.y_dim),\n infra.SelectionRegister('alpha', 1, 2),\n infra.SelectionRegister('q_x', (self.x_dim - 1).bit_length(), self.x_dim),\n infra.SelectionRegister('q_y', (self.y_dim - 1).bit_length(), self.y_dim),\n infra.SelectionRegister('beta', 1, 2),\n )\n\n @cached_property\n def junk_registers(self) -> Tuple[infra.Register, ...]:\n return (infra.Register('temp', 2),)\n\n @cached_property\n def signature(self) -> infra.Signature:\n return infra.Signature([*self.selection_registers, *self.junk_registers])\n\n def decompose_from_registers(\n self, *, context: cirq.DecompositionContext, **quregs: NDArray[cirq.Qid]\n ) -> cirq.OP_TREE:\n p_x, p_y, q_x, q_y = quregs['p_x'], quregs['p_y'], quregs['q_x'], quregs['q_y']\n U, V, alpha, beta = quregs['U'], quregs['V'], quregs['alpha'], quregs['beta']\n temp = quregs['temp']\n\n N = self.x_dim * self.y_dim * 2\n qlambda = 2 * N * self.t + (N * self.mu) // 2\n yield cirq.Ry(rads=2 * np.arccos(np.sqrt(self.t * N / qlambda))).on(*V)\n yield cirq.Ry(rads=2 * np.arccos(np.sqrt(1 / 5))).on(*U).controlled_by(*V)\n yield prep_u.PrepareUniformSuperposition(self.x_dim).on_registers(controls=[], target=p_x)\n yield prep_u.PrepareUniformSuperposition(self.y_dim).on_registers(controls=[], target=p_y)\n yield cirq.H.on_each(*temp)\n yield cirq.CNOT(*U, *V)\n yield cirq.X(*beta)\n yield from [cirq.X(*V), cirq.H(*alpha).controlled_by(*V), cirq.CX(*V, *beta), cirq.X(*V)]\n yield cirq.Circuit(cirq.CNOT.on_each([*zip([*p_x, *p_y, *alpha], [*q_x, *q_y, *beta])]))\n yield swap_network.MultiTargetCSwap.make_on(control=temp[:1], target_x=q_x, target_y=q_y)\n yield arithmetic_gates.AddMod(len(q_x), self.x_dim, add_val=1, cv=[0, 0]).on(*U, *V, *q_x)\n yield swap_network.MultiTargetCSwap.make_on(control=temp[:1], target_x=q_x, target_y=q_y)\n\n and_target = context.qubit_manager.qalloc(1)\n and_anc = context.qubit_manager.qalloc(1)\n yield and_gate.And(cv=(0, 0, 1)).on_registers(\n ctrl=np.array([U, V, temp[-1:]]), junk=np.array([and_anc]), target=and_target\n )\n yield swap_network.MultiTargetCSwap.make_on(\n control=and_target, target_x=[*p_x, *p_y, *alpha], target_y=[*q_x, *q_y, *beta]\n )\n yield and_gate.And(cv=(0, 0, 1), adjoint=True).on_registers(\n ctrl=np.array([U, V, temp[-1:]]), junk=np.array([and_anc]), target=and_target\n )\n context.qubit_manager.qfree([*and_anc, *and_target])\n\n def __repr__(self) -> str:\n return f'cirq_ft.PrepareHubbard({self.x_dim}, {self.y_dim}, {self.t}, {self.mu})'\n\n\ndef get_walk_operator_for_hubbard_model(\n x_dim: int, y_dim: int, t: int, mu: int\n) -> 'qubitization_walk_operator.QubitizationWalkOperator':\n select = SelectHubbard(x_dim, y_dim)\n prepare = PrepareHubbard(x_dim, y_dim, t, mu)\n return qubitization_walk_operator.QubitizationWalkOperator(select=select, prepare=prepare)\n","repo_name":"quantumlib/Cirq","sub_path":"cirq-ft/cirq_ft/algos/hubbard_model.py","file_name":"hubbard_model.py","file_ext":"py","file_size_in_byte":14727,"program_lang":"python","lang":"en","doc_type":"code","stars":3974,"dataset":"github-code","pt":"77"}
+{"seq_id":"40537398244","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport reportlab\nfrom reportlab.lib.units import mm\nfrom reportlab.pdfgen import canvas\nfrom pypdf import PdfWriter, PdfReader\nimport glob\nfrom datetime import datetime\n\n\ndef createPagePdf(tmp, from_page, to_page, username):\n c = canvas.Canvas(tmp)\n # c.setFontSize()\n c.setFont(\"Helvetica-Oblique\",10)\n \n now = datetime.now()\n now_formated = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n if len(username):\n username = username.upper() + ' - '\n\n for i in range(from_page+1,to_page+1): #para que comience de 1\n c.drawString((10)*mm, (4)*mm, \"Impreso desde SAP por \"+username+now_formated)\n c.drawString((165)*mm, (4)*mm, \"Página: \"+str(i))\n c.showPage()\n\n c.save()\n return\n\n\ndef filebrowser(word, folder):\n \"\"\"Returns a list with all files with the word/extension in it\"\"\"\n file = []\n for f in glob.glob1(folder, word):\n file.append(f)\n return file\n\n\ndef main(folder, username=''): \n tmpPdfFile = \"__tmp.pdf\"\n totPages = 0 # contador global de paginas \n \n # verificar si existe el path destino, sino lo crea \n destinationPath = path + 'pdfPaginado\\\\'\n if not os.path.isdir(destinationPath):\n os.mkdir(destinationPath)\n print('New folder created: \"pdfPaginado\"')\n\n # buscar archivos pdf en el directorio actual por orden alfabetico \n flist = filebrowser(\"*.pdf\", path)\n print('Input files: ',flist) \n\n # definir salida \n newFilename = destinationPath + 'numerado.pdf'\n mergedPdf = PdfWriter()\n\n # recorrer la lista de Nombres de archivos (orden alfabetico)\n for file in flist: \n print('--- Processing file: ', file) \n filename = path+file\n\n # abrir Archivo (path completo) para lectura \n originalPdfFile = PdfReader(filename) # ,strict=False)\n n = len(originalPdfFile.pages)\n fromPage = totPages\n toPage = n+totPages\n\n # crea pdf temporal en blanco, pero numerado. \n createPagePdf(tmpPdfFile,fromPage,toPage, username)\n numberedPdf = PdfReader(tmpPdfFile)\n \n # recorrer las paginas y hacer merge de original y numerada \n for p in range(n):\n originalPage = originalPdfFile.pages[p] \n numberedPage = numberedPdf.pages[p]\n originalPage.merge_page(numberedPage) \n mergedPdf.add_page(originalPage)\n\n totPages = totPages + n \n os.remove(tmpPdfFile)\n os.remove(filename)\n\n if len(mergedPdf.pages):\n print('- Output: ', newFilename)\n with open(newFilename, 'wb') as f:\n mergedPdf.write(f)\n\n\nif __name__ == \"__main__\":\n pass\n import sys,os\n path = 'C:\\tmp\\\\'\n username = ''\n if len(sys.argv) == 1:\n print(\"C:> python numeraPDF.py [carpeta] [username]\")\n if not os.path.isfile(path):\n sys.exit(1)\n else:\n path = sys.argv[1]\n if not os.path.isdir(path):\n print(\"Carpeta seleccionada no existe.\")\n if len(sys.argv) == 3:\n username = sys.argv[2]\n\n main(path,username)\n\n\"\"\" \nTO-DO :\n- incorporar algunos parametros a la ejecución. ej: help, destino, print, etc \n- manejo de errores: ejemplo carpeta no existe. \n\"\"\"\n","repo_name":"nicocastanio/numeraPDFs","sub_path":"numerarpdfs.py","file_name":"numerarpdfs.py","file_ext":"py","file_size_in_byte":3247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"36584284422","text":"from tkinter import *\nimport os\n\n# These function will tell the buttons what actually they want to do..\ndef restart():\n os.system(\"shutdown /r /t 1\") # Here 1 means 1 second before restart\n\ndef restart_with_time():\n os.system(\"shutdown /r /t 20\") # Here 20 means 20 second before restart.\n\ndef logout():\n os.system(\"shutdown -l\")\n\ndef shutdown():\n os.system(\"shutdown /s /t 1\")\n\n# Now first we create a class for calling Tk class of tkinter module.\nCommand = Tk()\nCommand.title(\"Command App\")\n\n# Here we create a menu bar\n\nmenubar = Menu(Command)\nCommand.config(menu=menubar)\nfile_menu = Menu(menubar)\nmenubar.add_cascade(\n label=\"Windows Command\",\n menu=file_menu\n)\n\nCommand.geometry(\"400x300\") # Geometry => width x height\nCommand.config(bg=\"#FFFDD0\") # Cream color code => #FFFDD0\n\n# Now we create buttons => 1. Restart 2. Log out 3.Shutdown 4. Restart with time\n# 1. Restart\n# Here we use relief to make our button a 3D look and we use cursor for what will happen when cursor will arraive to our button.\n\nRestart_Button = Button(Command, text=\"Restart\", font=(\n \"Time New Roman\", 10, \"bold\"), relief=RAISED, cursor=\"plus\",command=restart)\nRestart_Button.place(x=10, y=10, height=30, width=100)\n\n# 2. Logout\n\nLogout_Button = Button(Command, text=\"Logout\", font=(\n \"Time New Roman\", 10, \"bold\"), relief=RAISED, cursor=\"plus\",command=logout)\nLogout_Button.place(x=10, y=50, height=30, width=100)\n\n# 3. Restart with time\n\nRestart_with_time_button = Button(Command, text=\"Restart with Time\", font=(\n \"Time New Roman\", 10, \"bold\"), relief=RAISED, cursor=\"plus\",command=restart_with_time)\nRestart_with_time_button.place(x=10, y=90, height=30, width=150)\n\n# 4. ShutDown\n\nCommand_Button = Button(Command, text=\"ShutDown\", font=(\n \"Time New Roman\", 10, \"bold\"), relief=RAISED, cursor=\"plus\",command=shutdown)\nCommand_Button.place(x=10, y=130, height=30, width=100)\n\n# Now we created a Tk object we call a mainloop method which give us a tk titled screen.\nCommand.mainloop()\n","repo_name":"Abhay-Kanwasi/Project","sub_path":"Command app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"25344652156","text":"\"\"\"\nmethods for using the old bloomberg COM API from python\n\nWritten by Brian P. Smith (brian.p.smith@gmail.com)\n\"\"\"\nfrom datetime import datetime\nfrom win32com.client import Dispatch\nimport numpy as np\nimport pandas\nimport pywintypes\n\n\ndef _convert_value(v, replace_na=True):\n if isinstance(v, pywintypes.TimeType):\n return datetime(year=v.year, month=v.month, day=v.day)\n elif isinstance(v, float):\n return v\n elif isinstance(v, basestring):\n if v.startswith('#N/A'):\n return np.nan\n return str(v)\n else:\n return np.nan\n\n\ndef get_data_bbg_historical(symbol, flds, start=None, end=None):\n \"\"\"\n Get historical data from bloomberg. Retrieve the flds for the specified start to end date for the given symbol.\n\n symbol: Bloomberg identifier\n flds: list of bloomberg fields to retrieve\n \"\"\"\n bbg = Dispatch('Bloomberg.Data.1')\n\n from pandas.io.data import _sanitize_dates\n start, end = _sanitize_dates(start, end)\n\n data = bbg.BLPGetHistoricalData(symbol, flds, pywintypes.Time(start.timetuple()), pywintypes.Time(end.timetuple()))\n # Convert to datetime64 and ensure nan's for strings\n cdata = zip(*[map(_convert_value, r[0]) for r in data])\n flds = ['Date'] + list(flds)\n frame = pandas.DataFrame(dict((cname, cdata[i]) for i, cname in enumerate(flds)), columns=flds)\n return frame.set_index('Date')\n\n\ndef get_data_bbg_live(symbols, flds, replace_na=True):\n \"\"\"\n Get the live data for the specified fields from Bloomberg. if replace_na is true then convert all #N/As to numpy NaN's.\n\n symbols: Bloomberg identifier(s)\n flds: list of bloomberg fields to retrieve\n \"\"\"\n bbg = Dispatch('Bloomberg.Data.1')\n\n if isinstance(symbols, basestring):\n symbols = [symbols]\n elif not isinstance(symbols, (list, tuple)):\n raise TypeError('symbols must be list or tuple')\n\n if isinstance(flds, basestring):\n flds = [flds]\n\n frames = []\n for symbol in symbols:\n data = bbg.BLPSubscribe(symbol, flds)[0]\n data = [_convert_value(v, replace_na) for v in data]\n frame = pandas.DataFrame(dict((n, data[i]) for i, n in enumerate(flds)), columns=flds, index=[symbol])\n frames.append(frame)\n return pandas.concat(frames)\n","repo_name":"bpsmith/pybbg","sub_path":"bbg_legacy.py","file_name":"bbg_legacy.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"77"}
+{"seq_id":"29457363523","text":"#!/usr/bin/env python3\n\n# imports\nimport os\nimport sys\nimport csv\nfrom lxml import etree\nfrom library.management import Manager\nfrom library.support.utility import Utility\n\n\"\"\"\nClass: GameManager\n\nExtends class Manager.\nThe GameManager class uses XML to store and manage game elements.\nContents maybe created, parsed and destroyed.\nThe class also supports validation of the XML file given an XSD schema, so that\nit may be used independently.\n\"\"\"\nclass GameManager(Manager):\n \"\"\"\n Initializer\n \"\"\"\n def __init__(self, storageroot, libfile, schemafile):\n # Library type.\n libtype = \"game\"\n # Allow sorting element tags.\n sortingtags = [\"title\", \"shop\", \"finished\"]\n # Unique key.\n uniquekey = \"title\"\n # Call parent initializer.\n super().__init__(storageroot, libfile, schemafile, libtype, sortingtags, uniquekey)\n # End of initializer.\n\n # File import and export functionality.\n \"\"\"\n Method: import_csv\n\n Imports a CSV file as the XML library file.\n Only fields listed in sortingtags and installer element's system tag are supported.\n\n Character set: UTF-8\n Field delimiter: ,\n Text delimiter: \\\n\n Valid CSV header:\n Title,Shop,Finished,System\n\n :param str impfile: the file to import.\n :return int: 0 on success, 1 if CSV header is not valid and 2 in case of filesystem write error.\n \"\"\"\n def import_csv(self, impfile):\n try:\n # List of games.\n games = []\n with open(impfile, newline=\"\") as csvfile:\n filereader = csv.DictReader(csvfile, quotechar=\"\\\\\")\n for row in filereader:\n # Create new element from elementdict.\n element = etree.Element(self._libtype)\n # Add subelements.\n subelement = etree.SubElement(element, \"title\")\n subelement.text = row[\"Title\"]\n subelement = etree.SubElement(element, \"shop\")\n subelement.text = row[\"Shop\"]\n subelement = etree.SubElement(element, \"finished\")\n subelement.text = row[\"Finished\"]\n # Add installer subelements.\n if row[\"System\"] != \"\":\n systems = row[\"System\"].split(\" \")\n for system in systems:\n subelement = etree.SubElement(element, \"installer\")\n systemelement = etree.SubElement(subelement, \"system\")\n systemelement.text = system\n # Add new element to games list.\n games.append(element)\n # Write the elements to a new library file.\n wgames = self._write_tree(games)\n if wgames != 0:\n return wgames\n except OSError:\n return 2\n except KeyError:\n return 1\n # File import was successful.\n return 0\n # End of method import_csv.\n\n \"\"\"\n Method: export_csv\n\n Exports XML library file as a CSV file.\n Only fields listed in sortingtags and installer element's system tag are supported.\n\n Character set: UTF-8\n Field delimiter: ,\n Text delimiter: \\\n\n Valid CSV header:\n Title,Shop,Finished,System\n\n :param str expfile: the file to export.\n :return int: 0 on success, 1 if library file is not valid and 2 in case of error.\n \"\"\"\n def export_csv(self, expfile):\n try:\n # Open CSV file for writing.\n with open(expfile, \"w\", newline = \"\") as csvfile:\n filewriter = csv.writer(csvfile, quotechar = \"\\\\\", quoting = csv.QUOTE_MINIMAL)\n # Write header row.\n filewriter.writerow([self._sortingtags[0].title(), self._sortingtags[1].title(), self._sortingtags[2].title(), \"System\"])\n # Get all items\n items = self.get_all_elements()\n # Check for errors before proceed.\n if isinstance(items, int):\n return items\n # Check if library is empty.\n if items is None:\n return 0\n # Write items to CSV file.\n for item in items:\n system = []\n # Check if installer element exists.\n itemlength = len(item)\n if itemlength > 3:\n for i in range(3, itemlength):\n system.append(item[i][0].text)\n # Write row.\n filewriter.writerow([item[0].text, item[1].text, item[2].text, \" \".join(system)])\n except OSError:\n return 2\n # File export was successful.\n return 0\n # End of method export_csv.\n\n # Storage management methods.\n \"\"\"\n Method: restore_schema\n\n Restores the library schema file.\n\n :return int: 0 on success and 2 in case of error.\n \"\"\"\n def restore_schema(self):\n # Create the xsd tree.\n xsdroot = etree.XML(\"\"\"\n\n\n\n\n \n \n \n \n \n \n\n\n \n \n \n \n \n \n\n\n\n\n \n \n \n \n \n \n\n\n \n \n \n \n \n \n \n\n\n \n \n \n \n \n \n \n \n \n\n\n\n \n \n \n \n \n \n \n \n\n\n \n \n \n \n \n \n \n \n \n\n\n \n \n \n \n \n \n \n \n \n \n\n \n \"\"\")\n\n # Write xsd tree to file confschema\n xsdout = etree.ElementTree(xsdroot)\n try:\n xsdout.write(self._xsdfile, xml_declaration=True, encoding=\"UTF-8\", pretty_print=True)\n return 0\n except OSError:\n return 2\n # End of method restore_schema.\n\n # Element manipulation methods.\n \"\"\"\n Method: search_elements\n\n Search for elements containing a given value.\n\n :param str element: The element tag containing the value. Should be in _sortingtags list.\n :param str value: The value inside element tag to search for.\n :param bool ascending[=True]: The order to sort the results.\n :return int_or_list_or_None: Union[int, list, None].\n \"\"\"\n def search_elements(self, element, value, ascending = True):\n # Validate storage.\n validate = self.validate()\n if validate != 0:\n return validate\n\n if element not in self._sortingtags:\n return None\n\n # Create xml tree.\n tree = etree.parse(self._xmlfile)\n # Search for elements containing the value.\n tnodes = tree.xpath(\"/library/{0}/{1}[contains(translate(., '{3}', '{4}'), '{2}')]/ancestor::{0}\".format(self._libtype, element, value.lower(), self._uppercase, self._lowercase))\n\n # Return elements if exist or none if list is empty.\n if tnodes:\n # Sort the list.\n index = self._sortingtags.index(element)\n tnodes.sort(key = lambda element: element[index].text.title(), reverse = not ascending)\n return tnodes\n else:\n return None\n # End of method search_elements.\n\n \"\"\"\n Method: get_all_elements\n\n Gets all elements in the specified order.\n\n :param str element[=None]: The element tag on which get will be based. Should be in _sortingtags list.\n :param bool ascending[=True]: The order to sort the results.\n :return int_or_list_or_None: Union[int, list, None].\n \"\"\"\n def get_all_elements(self, element = None, ascending = True):\n # Validate storage.\n validate = self.validate()\n if validate != 0:\n return validate\n\n # Create xml tree.\n tree = etree.parse(self._xmlfile)\n # Get a list of all elements.\n tnodes = tree.xpath(\"/library/{}\".format(self._libtype))\n\n # Return elements if exist or none if list is empty.\n if tnodes:\n # If element is None, title is used.\n if element is None:\n element = \"title\"\n # Sort the list.\n index = self._sortingtags.index(element)\n tnodes.sort(key = lambda element: element[index].text.title(), reverse = not ascending)\n return tnodes\n else:\n return None\n # End of method get_all_elements.\n\n \"\"\"\n Method: get_element\n\n Gets an element by unique value.\n\n :param str element: The exact value in element title.\n :return int_or_etree.Element_or_None: Union[int, etree.Element, None].\n \"\"\"\n def get_element(self, element):\n # Validate storage.\n validate = self.validate()\n if validate != 0:\n return validate\n\n # Create xml tree.\n tree = etree.parse(self._xmlfile)\n # Find node.\n # Scheme validation garanties unique key value, so a list containing\n # only one element on an empty one will be returned.\n tnodes = tree.xpath(\"/library/{0}/title[text()='{1}']/ancestor::{0}\".format(self._libtype, element))\n\n # Return element if exists or none if list is empty\n if tnodes:\n return tnodes[0]\n else:\n return None\n # End of method get_element.\n\n \"\"\"\n Method: add_element\n\n Adds an element.\n\n Python dictionary form:\n {\n \"title\": \"\", \"shop\": \"\", \"finished\": \"Yes/No\",\n \"installer\": [\n {\"system\": \"\", \"lastupdated\": \"YYYY-MM-DD\", \"filename\": [\"\"]}\n ]\n }\n\n :param dict elementdict: The python dictionary containing the values of the element to be added to library.\n :return int: 0 on success, 1 on dictionary key error, 2 on write file error and 3 on validation error.\n \"\"\"\n def add_element(self, elementdict):\n # Create new element from elementdict.\n element = etree.Element(self._libtype)\n try:\n subelement = etree.SubElement(element, \"title\")\n subelement.text = elementdict[\"title\"]\n subelement = etree.SubElement(element, \"shop\")\n subelement.text = elementdict[\"shop\"]\n subelement = etree.SubElement(element, \"finished\")\n subelement.text = elementdict[\"finished\"]\n\n # Get installer list.\n if \"installer\" in elementdict:\n for installer in elementdict[\"installer\"]:\n installertag = etree.SubElement(element, \"installer\")\n subelement = etree.SubElement(installertag, \"system\")\n subelement.text = installer[\"system\"]\n if \"lastupdated\" in installer:\n subelement = etree.SubElement(installertag, \"lastupdated\")\n subelement.text = installer[\"lastupdated\"]\n # Get filename list\n if \"filename\" in installer:\n for filename in installer[\"filename\"]:\n subelement = etree.SubElement(installertag, \"filename\")\n subelement.text = filename\n # Write to file.\n return self._add_element_to_tree(element)\n except KeyError:\n return 1\n # End of method add_element.\n\n \"\"\"\n Method: remove_element\n\n Removes an element.\n\n :param str element: The exact value in element title.\n :return int: 0 on success, 1 in case no node found, 2 on write file error and 3 on validation error.\n \"\"\"\n def remove_element(self, element):\n # Create xml tree.\n tree = etree.parse(self._xmlfile)\n # Get a list of all elements.\n nodes = tree.xpath(\"/library/{}\".format(self._libtype))\n # Find the element to remove using exact match.\n node = tree.xpath(\"/library/{0}/title[text()='{1}']/ancestor::{0}\".format(self._libtype, element))\n if not node:\n return 1\n # Remove element's node.\n nodes.remove(node[0])\n # Write to file.\n return self._write_tree(nodes)\n # End of method remove_element.\n\n \"\"\"\n Method: show_table\n\n Shows table of elements.\n\n :param list elements: List of etree.Element to be shown.\n \"\"\"\n def show_table(self, elements):\n # Calculate max column widths.\n titlewidth = 5\n shopwidth = 4\n for item in elements:\n # Title width.\n width = len(item[0].text.strip())\n if titlewidth < width:\n titlewidth = width\n # Shop width.\n width = len(item[1].text.strip())\n if shopwidth < width:\n shopwidth = width\n # Display header.\n print(\"{:{}} | {:{}} | {:8} | {}\".format(self._sortingtags[0].title(), titlewidth, self._sortingtags[1].title(), shopwidth, self._sortingtags[2].title(), \"System\"))\n print(\"{}-|-{}-|-{}-|-{}\".format(\"-\" * titlewidth, \"-\" * shopwidth, \"-\" * 8, \"-\" * 6))\n # Iterate though result as needed and display game information.\n for item in elements:\n print(\"{:{}} | {:{}} | {:8} | \".format(item[0].text.strip(), titlewidth, item[1].text.strip(), shopwidth, item[2].text.strip()), end = \"\")\n for subitem in item:\n if subitem.tag == \"installer\":\n print(\"{} \".format(subitem[0].text.strip()), end = \"\")\n print()\n # End of method show_table.\n\n # Display methods.\n \"\"\"\n Method: show_element\n\n Shows an element.\n\n :param str value[=None]: The exact value in element title.\n \"\"\"\n def show_element(self, value = None):\n if value is None:\n # Get user input.\n print(\"Exact match will be made!\")\n title = input(\"Enter the title of the game: \")\n print()\n else:\n # set title using value parameter\n title = value\n # Get element.\n element = self.get_element(title)\n # Display result.\n if isinstance(element, int):\n print(\"Invalid storage file {}.\".format(self._xmlfile))\n elif element is None:\n print(\"No game with title {} found.\".format(title))\n else:\n # Iterate though result as needed and display game information.\n print(\"{}:\".format(element.tag.title()))\n for item in element.iterchildren():\n # Making sure installer tag has text, so that it will be iterated.\n if item.tag == \"installer\":\n item.text = \" \"\n\n if item.text is not None:\n depth = 4\n print(\"{}{}: {}\".format(\" \" * depth, item.tag.title(), item.text.strip()))\n for subitem in item.iterchildren():\n if subitem.text is not None:\n depth = 8\n print(\"{}{}: {}\".format(\" \" * depth, subitem.tag.title(), subitem.text.strip()))\n # Pause if the method has been called without a value.\n if value is None:\n print()\n input(\"Press 'Enter' to return to menu: \")\n # End of method show_element.\n\n \"\"\"\n Method: _xmlitem_to_dict\n\n Generates python dictionary from game xml element.\n\n :param etree.Element element: The game element node.\n :return dict: The python dictionary version of the XML node.\n \"\"\"\n def _xmlitem_to_dict(self, element):\n # Create python dictionary parsing element's values.\n gamedict = {}\n installer = []\n for item in element.iterchildren():\n # Making sure installer tag has text, so that it will be iterated.\n if item.tag == \"installer\":\n item.text = \" \"\n # Elements in game.\n if item.text is not None:\n gamedict[item.tag] = item.text.strip()\n if item.tag == \"installer\":\n installerdict = {}\n filename = []\n # Elements in installer.\n for subitem in item.iterchildren():\n if subitem.text is not None:\n if subitem.tag == \"filename\":\n filename.append(subitem.text.strip())\n else:\n installerdict[subitem.tag] = subitem.text.strip()\n if filename:\n installerdict[\"filename\"] = filename\n installer.append(installerdict)\n if installer:\n gamedict[\"installer\"] = installer\n\n return gamedict\n # End of method _xmlitem_to_dict.\n\n \"\"\"\n Method: _generate_libtype_element\n\n Generate game python dictionary.\n\n Python dictionary form:\n {\n \"title\": \"\", \"shop\": \"\", \"finished\": \"Yes/No\",\n \"installer\": [\n {\"system\": \"\", \"lastupdated\": \"YYYY-MM-DD\", \"filename\": [\"\"]}\n ]\n }\n\n :param dict element[=None]: The python dictionary containing the values of the element.\n :return dict: The python dictionary containing new values.\n \"\"\"\n def _generate_libtype_element(self, element = None):\n # Display header.\n if element is None:\n print(\"New\", end = \" \")\n element = {\"title\": None, \"shop\": None, \"finished\": None}\n print(\"Game Editor\")\n print()\n # Get game's elements.\n title = \"\"\n while title == \"\":\n title = input(\"Title{}: \".format(\"\" if element[\"title\"] is None else \"[\" + element[\"title\"] + \"]\"))\n if element[\"title\"] is not None and title == \"\":\n title = element[\"title\"]\n # Exit editor if the user is trying to create a game, which already exists.\n if element[\"title\"] is None and self.get_element(title) is not None:\n print(\"Game {} already exists.\".format(title))\n return None\n # Exit editor if new title already exists.\n if element[\"title\"] is not None:\n if title != element[\"title\"] and self.get_element(title) is not None:\n print(\"Title '{}' has already been used for a game.\".format(title))\n return None\n\n element[\"title\"] = title\n\n shop = \"\"\n while shop == \"\":\n shop = input(\"Shop{}: \".format(\"\" if element[\"shop\"] is None else \"[\" + element[\"shop\"] + \"]\"))\n if element[\"shop\"] is not None and shop == \"\":\n shop = element[\"shop\"]\n element[\"shop\"] = shop\n\n finished = Utility.get_answer_yn(\"Finished{}:\".format(\"\" if element[\"finished\"] is None else \"[\" + element[\"finished\"] + \"]\"))\n if finished == \"y\":\n element[\"finished\"] = \"Yes\"\n else:\n element[\"finished\"] = \"No\"\n\n # Get game's installer elements.\n if Utility.get_answer_yn(\"Open installer editor?\") == \"y\":\n element = self._generate_installer(element)\n # Return game dictionary.\n return element\n # End of method _generate_libtype_element.\n\n \"\"\"\n Method: _generate_installer\n\n Generate installer python dictionary.\n\n Python dictionary form:\n {\n \"title\": \"\", \"shop\": \"\", \"finished\": \"Yes/No\",\n \"installer\": [\n {\"system\": \"\", \"lastupdated\": \"YYYY-MM-DD\", \"filename\": [\"\"]}\n ]\n }\n\n :param dict game: The python dictionary containing the values of the element.\n :return dict: The python dictionary containing edited installer list or without installer key, if there is no istaller.\n \"\"\"\n def _generate_installer(self, game):\n Utility.clear()\n # Display header.\n print(\"Installer Editor\")\n print()\n if \"installer\" in game:\n removelist = []\n # Generate range of menu values once.\n choices = range(1, 4)\n for installer in game[\"installer\"]:\n print(\"Installer:\")\n print(\" System: {}\".format(installer[\"system\"]))\n if \"lastupdated\" in installer:\n print(\" Last updated: {}\".format(installer[\"lastupdated\"]))\n if \"filename\" in installer:\n print(\" File(s): {}\".format(installer[\"filename\"]))\n\n # Display menu\n print(\"1. Keep and continue\")\n print(\"2. Remove installer\")\n print(\"3. Edit installer\")\n # Get action from the user.\n choice = None\n # Generate menu\n while choice not in choices:\n # Get user choice.\n try:\n choice = int(input(\"Enter your choice: \"))\n except ValueError:\n choice = None\n\n # React to user choice.\n if choice == 1:\n # Pass for 1.\n # Alternatively break out of the loop.\n pass\n elif choice == 2:\n # Add elements to removal list.\n removelist.append(installer)\n print(\"Installer has been removed.\")\n elif choice == 3:\n self._get_installer_values(installer)\n else:\n choice = None\n # Remove marked installers permanently.\n for rvalue in removelist:\n game[\"installer\"].remove(rvalue)\n # If list is empty remove respective game dictionary key.\n if len(game[\"installer\"]) == 0:\n del game[\"installer\"]\n # Add new installer.\n game = self._generate_new_installer(game)\n\n return game\n # End of method _generate_installer.\n\n \"\"\"\n Method: _generate_new_installer\n\n Generate new installer python dictionary.\n\n Python dictionary form:\n {\n \"title\": \"\", \"shop\": \"\", \"finished\": \"Yes/No\",\n \"installer\": [\n {\"system\": \"\", \"lastupdated\": \"YYYY-MM-DD\", \"filename\": [\"\"]}\n ]\n }\n\n :param dict game: The python dictionary containing the values of the element.\n :return dict: The python dictionary containing new dictionaries into its installer list.\n \"\"\"\n def _generate_new_installer(self, game):\n # Add new installer.\n installers = []\n while Utility.get_answer_yn(\"Add new installer?\") == \"y\":\n newinst = self._get_installer_values()\n installers.append(newinst)\n # Add installers to game.\n if installers:\n if \"installer\" in game:\n game[\"installer\"] += installers\n else:\n game[\"installer\"] = installers\n return game\n # End of method _generate_new_installer.\n\n \"\"\"\n Method: _get_installer_values\n\n Gets game's installer values from the user.\n\n Python dictionary form:\n {\"system\": \"\", \"lastupdated\": \"YYYY-MM-DD\", \"filename\": [\"\"]}\n\n :param dict installer[=None]: The python dictionary containing the values of the element.\n :return dict: The python dictionary containing new installer values.\n \"\"\"\n def _get_installer_values(self, installer = None):\n Utility.clear()\n # Display header.\n if installer is None:\n print(\"New\", end = \" \")\n installer = {\"system\": None}\n print(\"Installer\")\n print()\n # Get installer's values.\n # Get system.\n systems = ['Windows', 'Mac', 'Linux', 'Other']\n schoices = range(1, 5)\n system = None\n while system not in systems:\n # Display menu\n print(\"System{}: \".format(\"\" if installer[\"system\"] is None else \"[\" + installer[\"system\"] + \"]\"))\n for s in systems:\n print(\"{}. {}\".format(systems.index(s) + 1, s))\n # Get user choice.\n try:\n choice = input(\"Enter your choice: \")\n if choice == \"\":\n system = installer[\"system\"]\n else:\n choice = int(choice)\n if choice in schoices:\n system = systems[choice - 1]\n except ValueError:\n choice = None\n installer[\"system\"] = system\n # Get lastupdated.\n lastupdated = None\n while lastupdated is None:\n print(\"Date should be written in form YYYY-MM-DD.\")\n lastupdated = input(\"Last updated at{}: \".format(\"[\" + installer[\"lastupdated\"] + \"]\" if \"lastupdated\" in installer else \"\"))\n # Check if value is a valid date.\n valid = Utility.validate_date(lastupdated)\n if valid is not None:\n installer[\"lastupdated\"] = valid\n elif lastupdated == \"\":\n # Pass for 1.\n # Alternatively break out of the loop.\n pass\n else:\n lastupdated = None\n # Get filenames.\n installer = self._generate_filename(installer)\n\n return installer\n # End of method _get_installer_values.\n\n \"\"\"\n Method: _generate_filename\n\n Asks about current filenames.\n Calls method to get new filename values from the user.\n\n Python dictionary form:\n {\"system\": \"\", \"lastupdated\": \"YYYY-MM-DD\", \"filename\": [\"\"]}\n\n :param dict installer: The python dictionary containing the values of the element.\n :return dict: The python dictionary containing edited filename list or without filename key, if there is no filename.\n \"\"\"\n def _generate_filename(self, installer):\n removelist = []\n # Get filename.\n if \"filename\" in installer:\n for filename in installer[\"filename\"]:\n # Get action from the user.\n choices = range(1, 3)\n choice = None\n # Generate menu\n # Display menu\n print(filename)\n print(\"1. Keep and continue\")\n print(\"2. Remove filename\")\n while choice not in choices:\n # Get user choice.\n try:\n choice = int(input(\"Enter your choice: \"))\n except ValueError:\n choice = None\n\n # React to user choice.\n if choice == 1:\n # Pass for 1.\n # Alternatively break out of the loop.\n pass\n elif choice == 2:\n removelist.append(filename)\n print(\"Filename has been removed.\")\n else:\n choice = None\n # Remove marked filenames permanently.\n for rvalue in removelist:\n installer[\"filename\"].remove(rvalue)\n # If list is empty remove respective installer dictionary key.\n if len(installer[\"filename\"]) == 0:\n del installer[\"filename\"]\n # Add new filenames.\n self._get_filename_values(installer)\n\n return installer\n # End of method _generate_filename.\n\n \"\"\"\n Method: _get_filename_values\n\n Gets new filename values from the user.\n\n Python dictionary form:\n {\"system\": \"\", \"lastupdated\": \"YYYY-MM-DD\", \"filename\": [\"\"]}\n\n :param dict installer: The python dictionary containing the values of the element.\n :return dict: The python dictionary containing new filenames into its filename list.\n \"\"\"\n def _get_filename_values(self, installer):\n # Add new filenames.\n fnames = []\n filename = \"Enter Loop\"\n while filename != \"\":\n filename = input(\"Add filename [leave empty to stop]: \")\n filename = filename.strip()\n if filename != \"\":\n fnames.append(filename)\n # Add filenames to installer.\n if fnames:\n if \"filename\" in installer:\n installer[\"filename\"] += fnames\n else:\n installer[\"filename\"] = fnames\n\n return installer\n # End of method _get_filename_values.\n# End of class GameManager.\n\n# The following section contains code to execute when script is run from the command line.\n\"\"\"\nFunction: main\n\nEntry point for the execution of the script.\n\"\"\"\ndef main():\n print(__file__)\n# End of function main.\n\n# Test running or loading.\nif __name__ == \"__main__\":\n main()\n","repo_name":"vanchann/library_application","sub_path":"library/game_management.py","file_name":"game_management.py","file_ext":"py","file_size_in_byte":30170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"23268149695","text":"import discord \nimport os\nfrom dotenv import load_dotenv, find_dotenv\nfrom pretty_help import PrettyHelp\nfrom discord.ext import commands\nclient = commands.Bot(command_prefix=\"!!\",help_command=PrettyHelp(no_category=\"none\",sort_commands=True,show_index=True))\nload_dotenv(find_dotenv())\n\nTOKEN = os.environ['TOKEN']\nCOLOR = 0xB0B0BF\n\n@client.command()\nasync def load(ctx,extension):\n client.load_extension(f\"cogs.{extension}\")\n\n@client.command()\nasync def unload(ctx,extension):\n client.unload_extension(f\"cogs.{extension}\")\n\nfor filename in os.listdir(\"./cogs\"):\n if filename.endswith('.py'):\n client.load_extension(f'cogs.{filename[:-3]}')\n \n\n@client.event\nasync def on_ready():\n print(\"Bot is ready\")\nclient.run(TOKEN)\n","repo_name":"sidhant-sriv/Discord-Bot","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"5247573270","text":"import socket\nimport time\nimport scapy.all as scapy\nimport struct\nimport select\n# import getch\nimport msvcrt\n\n\n# network ip\nclient_ip = '127.0.0.1' # localhost\n# client_ip = scapy.get_if_addr('eth1') # dev\n# client_ip = scapy.get_if_addr('eth2') # test\n\n# ports\nudp_port = 8081 # udp port on my localhost\nclient_tcp_port = 9090 # tcp port on my localhost\n# udp_port = 13117 # udp port for sending offers\n# client_tcp_port = 2063 # tcp port we get from the course\nserver_tcp_ip = None\nserver_tcp_port = None\n\n# our team name\nteam_name = \"Pink fluffy unicorns dancing on rainbow\\n\"\n\n\ndef create_udp_connection_client():\n # Create a UDP socket\n try:\n udp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n udp_client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # enable port reusage\n udp_client_socket.bind((client_ip, udp_port))\n except:\n return\n\n print(\"Client started, listening for offer requests...\")\n while True:\n try:\n # recieve data and address of the server\n data, server_address = udp_client_socket.recvfrom(1024)\n\n # get data from server in hex format\n server_data = struct.unpack('4s 1s 2s', data)\n \n magic_cookie = server_data[0].hex() # get magic cookie\n msg_type = int(server_data[1].hex()) # get type of the message\n \n # validate the offer from the server\n if magic_cookie == 'feedbeef' and msg_type == 2:\n # get ip and port for tcp\n global server_tcp_ip, server_tcp_port\n server_tcp_ip = server_address[0] # get server's ip for tcp\n server_tcp_port = int(server_data[2].hex()) # get server's port for tcp\n break\n \n except:\n pass\n\n # close the udp stream\n udp_client_socket.close()\n return\n\ndef create_tcp_connection_client():\n if server_tcp_port is None or server_tcp_port is None:\n return\n\n print(\"Received offer from {}, attempting to connect...\".format(server_tcp_ip))\n \n try:\n # config tcp\n tcp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # create tcp socket\n tcp_client_socket.connect((server_tcp_ip, server_tcp_port)) # connect the tcp socket to the server\n\n # send the team name to the server\n tcp_client_socket.sendall(team_name.encode())\n\n # Receive the data in small chunks and retransmit it forever...\n # Start Game: \n # spouse to get the message of starting the game from the server\n data = tcp_client_socket.recv(1024).decode()\n if data:\n print(data)\n # if got the welcome message - start \n data = None\n tcp_client_socket.setblocking(False)\n # tcp_client_socket.send(getch.getche().encode())\n tcp_client_socket.send(msvcrt.getch())\n while True:\n # check if client got message of game over: true - print the winners.\n # false keep sending keys to server.\n try:\n data = tcp_client_socket.recv(1024).decode()\n except:\n pass\n if data:\n print(data)\n break\n else:\n tcp_client_socket.send(msvcrt.getch())\n\n except Exception as e: \n print(e)\n \n finally:\n # close the tcp udp stream\n tcp_client_socket.close()\n \n global is_connected\n is_connected = False\n return\n\n# start the client\nwhile True:\n create_udp_connection_client()\n create_tcp_connection_client()","repo_name":"EvgenyUmansky/hackathon-network-2020","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"2790441308","text":"from keras.datasets import mnist\nfrom keras.utils import to_categorical\nimport numpy as np\nfrom keras.models import load_model\nimport keras.backend as K\n\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nx_train = x_train.reshape(-1, 28, 28, 1)\nx_test = x_test.reshape(-1, 28, 28, 1)\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train /= 255\nx_test /= 255\ny_train = to_categorical(y_train, 10)\ny_test = to_categorical(y_test, 10)\n\nmodel = load_model('model/lenet1.h5')\n\nindex = np.load('data/index_lenet1.npy')\ntest_index = np.load('data/index_lenet1_test.npy')\ntrain = x_train[index]\ntest = x_test[test_index]\n\ninput_tensor = model.input\nlayers = model.layers\n\nfor layer in layers:\n if layer.name in ['before_softmax']:\n output = layer.output\n fun = K.function([input_tensor], [output])\n for i in range(1):\n temp = fun([ test[ i*1000 : (i+1)*1000 ] ])[0]\n # temp = temp.T\n if i == 0:\n arr = temp\n else:\n arr = np.append(arr, temp, axis=0)\narr = np.array(arr)\nnp.savetxt('data/layer_test.csv', arr)\n\n\nfor layer in layers:\n if layer.name in ['before_softmax']:\n output = layer.output\n fun = K.function([input_tensor], [output])\n for i in range(10):\n temp = fun([ train[ i*1000 : (i+1)*1000 ] ])[0]\n # temp = temp.T\n if i == 0:\n arr = temp\n else:\n arr = np.append(arr, temp, axis=0)\narr = np.array(arr)\nnp.savetxt('data/layer_train.csv', arr)","repo_name":"wazxser/FRP","sub_path":"layer.py","file_name":"layer.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"38305303377","text":"# #--------------------------\n# #-- Mastering Python \n# #-- Eighth Assignment \n# #-- From Lessons 47 To 50\n# #--------------------------\n\n# # First assignmnet\n\n# num = input(\"Enter any number more than '0' : \")\n# num = int(num)\n# count = 0\n# if num <= 0:\n# print(\"The Number no longer than 'zero'\") \n\n# while num > 0 :\n# num -= 1 \n# if num == 0:\n# break\n# elif num == 6:\n# continue\n# count +=1\n# print(num)\n# print(f\"{'No' if count <= 0 else count} Numbers printed succesfully.\")\n \n# # Second assignment\n\n# myFriends = [\"bishoy\", \"maria\", \"Daniella\", \"Alessandra\", \"mariam\"]\n\n# count = 0\n# index = 0\n# while len(myFriends) > index:\n# if myFriends[index].islower():\n# index += 1\n# count += 1\n# continue\n# else:\n# print(myFriends[index])\n# index += 1\n# print(f\"Capitals names printed, and {count} names ignored\")\n\n# # Third assignment\n\n# skills = [\"HTML\", \"CSS\", \"JS\",\"PHP\", \"Python\"]\n# while skills:\n# print(skills.pop(0))\n# print(skills) # skills list become empty so the value for list now is 'False' so that loop is finish\n\n# # Fourth assignment\n\nmy_friends = list()\nmax_friends = 4\nwhile len(my_friends) < 4 :\n name = input(\"Add Name: \").strip()\n if name == name.upper():\n print(\"Invalid Name.\")\n elif name == name.lower():\n name_capitalize = name.capitalize()\n my_friends.append(name_capitalize)\n max_friends -= 1\n print(\"The name changed to be capitalized.\")\n print(f\"{name_capitalize} was added, {'Add the last' if max_friends == 1 else max_friends} name left\") \n elif name == name.capitalize():\n my_friends.append(name)\n max_friends -= 1\n print(f\"{name} was added, {'Add the last' if max_friends == 1 else max_friends} name left\")\nelse:\n print(\"Your List Is Full\")\n \nprint(my_friends)","repo_name":"BishoySamuel/Mastering-Python","sub_path":"Assignments/Assignment-010-Lessons-047-050.py","file_name":"Assignment-010-Lessons-047-050.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"26292287994","text":"import numpy as np\n\nmy_empty = np.empty\n\nimport logging\n\nfrom npstructures import npdataclass\n\nlogger = logging.getLogger(__name__)\nwrapper = lambda x: x\n\n\ndef repr_bytes(n):\n if n < 10 ** 4:\n return str(n) + \"b\"\n elif n < 10 ** 7:\n return str(n // 1000) + \"kb\"\n elif n < 10 ** 11:\n return str(n // 1000000) + \"Mb\"\n return str(n // 1000000000) + \"Gb\"\n\n\nclass NpBufferStream:\n \"\"\"\n Class that handles the main task of reading in chunks of data\n from file that corresponds to full entries.\n \"\"\"\n\n def __init__(self, file_obj, buffer_type, chunk_size=5000000, has_header=False):\n self._file_obj = file_obj\n self._chunk_size = chunk_size\n self._is_finished = False\n self._buffer_type = buffer_type\n self._has_header = has_header\n self._f_name = (\n self._file_obj.name\n if hasattr(self._file_obj, \"name\")\n else str(self._file_obj)\n )\n\n def __iter__(self):\n self._remove_initial_comments()\n self._remove_header()\n chunk = self.__get_buffer()\n total_bytes = 0\n\n while not self._is_finished:\n total_bytes += chunk.size\n logger.debug(\n f\"Read chunk of size {repr_bytes(chunk.size)} from {self._f_name}. (Total {repr_bytes(total_bytes)})\"\n )\n buff = self._buffer_type.from_raw_buffer(chunk)\n self._file_obj.seek(buff.size - self._chunk_size, 1)\n yield wrapper(buff)\n chunk = self.__get_buffer()\n if chunk is not None and chunk.size:\n yield self._buffer_type.from_raw_buffer(chunk)\n\n def __get_buffer(self):\n a, bytes_read = self.__read_raw_chunk()\n self._is_finished = bytes_read < self._chunk_size\n if bytes_read == 0:\n return None\n\n # Ensure that the last entry ends with newline. Makes logic easier later\n if self._is_finished and a[bytes_read - 1] != ord(\"\\n\"):\n a = np.append(a, ord(\"\\n\"))\n bytes_read += 1\n return a[:bytes_read]\n\n def __read_raw_chunk(self):\n b = np.frombuffer(self._file_obj.read(self._chunk_size), dtype=\"uint8\")\n return b, b.size\n # array = my_empty(self._chunk_size, dtype=\"uint8\")\n # bytes_read = self._file_obj.readinto(array)\n # return array, bytes_read\n\n def _remove_initial_comments(self):\n if self._buffer_type.COMMENT == 0:\n return\n for line in self._file_obj:\n if line[0] != self._buffer_type.COMMENT:\n self._file_obj.seek(-len(line), 1)\n break\n\n def _remove_header(self):\n if self._has_header:\n self._file_obj.readline()\n\n\nclass NpBufferedWriter:\n def __init__(self, file_obj, buffer_type):\n self._file_obj = file_obj\n self._buffer_type = buffer_type\n self._f_name = (\n self._file_obj.name\n if hasattr(self._file_obj, \"name\")\n else str(self._file_obj)\n )\n\n def close(self):\n self._file_obj.close()\n\n def write(self, data: npdataclass):\n \"\"\"Write the provided data to file\n\n Parameters\n ----------\n data : npdataclass\n Data set containing entries\n\n \"\"\"\n bytes_array = self._buffer_type.from_data(data)\n self._file_obj.write(bytes(bytes_array)) # .tofile(self._file_obj)\n self._file_obj.flush()\n logger.debug(\n f\"Wrote chunk of size {repr_bytes(bytes_array.size)} to {self._f_name}\"\n )\n\n\ndef chunk_lines(stream, n_lines):\n cur_buffers = []\n remaining_lines = n_lines\n for chunk in stream:\n n_lines_in_chunk = len(chunk)\n while n_lines_in_chunk >= remaining_lines:\n cur_buffers.append(chunk[:remaining_lines])\n yield np.concatenate(cur_buffers)\n cur_buffers = []\n chunk = chunk[remaining_lines:]\n remaining_lines = n_lines\n n_lines_in_chunk = len(chunk)\n cur_buffers.append(chunk)\n remaining_lines -= n_lines_in_chunk\n yield np.concatenate(cur_buffers)\n","repo_name":"jorgenwh/kmer-counting-experimentation","sub_path":"bionumpy/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":4136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"445084104","text":"from flask import Flask, request, render_template, jsonify\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom random import randint\n\napp = Flask(__name__)\n\nthings = []\ntraffic_val = []\ndataset = []\n\nfor i in range(0, 50):\n thing = [randint(1, 10), randint(0, 3), randint(0, 6), randint(0, 23)]\n val = (thing[0] + thing[1] + thing[2] + thing[3]) % 10\n things.append(thing)\n traffic_val.append(val)\n dataset.append([thing[0], thing[1], thing[2], thing[3], val])\n\nknn = KNeighborsClassifier()\n\n\n@app.route('/')\ndef static_page():\n return render_template(\"index.html\")\n\n\n@app.route('/predict', methods=['GET'])\ndef predict_thing():\n road_id = request.args.get('id')\n direction = request.args.get('dir')\n dayOfWeek = request.args.get('day')\n timeOfDay = request.args.get('time')\n this_thing = [int(road_id), int(direction), int(dayOfWeek), int(timeOfDay)]\n\n knn.fit(things, traffic_val)\n prediction = knn.predict(this_thing)[0]\n\n return str(prediction)\n\n\n@app.route('/insert', methods=['GET'])\ndef create_thing():\n road_id = request.args.get('id')\n direction = request.args.get('dir')\n dayOfWeek = request.args.get('day')\n timeOfDay = request.args.get('time')\n tval = request.args.get('tval')\n this_thing = [int(road_id), int(direction), int(dayOfWeek), int(timeOfDay)]\n traffic_val.append(int(tval))\n things.append(this_thing)\n dataset.append([this_thing[0], this_thing[1], this_thing[2], this_thing[3], int(tval)])\n temp = [\"format: road_id, direction, dayOfWeek, timeOfDay, traffic value\"]\n temp.append(dataset)\n return jsonify(results=temp)\n\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"nicholas-charles-brown/W17_CS499","sub_path":"H3/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"5559427665","text":"\"\"\"\nFor bond\n\"\"\"\nimport QuantLib as ql\n\nschedule = ql.Schedule(ql.Date(8, ql.February, 2017),\n ql.Date(8, ql.February, 2027),\n ql.Period(6, ql.Months),\n ql.TARGET(),\n ql.Following,\n ql.Following,\n ql.DateGeneration.Backward,\n False)\n\nsettlementDays = 3\nfaceAmount = 100\ncoupons = [0.02]\npaymentDayCounter = ql.Thirty360()\n\nbond = ql.FixedRateBond(settlementDays, faceAmount, schedule, coupons, paymentDayCounter)\n\ny = ql.SimpleQuote(0.02)\nyield_curve = ql.FlatForward(bond.settlementDate(), ql.QuoteHandle(y),\n ql.Actual360(), ql.Compounded, ql.Semiannual)\nbond.setPricingEngine(ql.DiscountingBondEngine(ql.YieldTermStructureHandle(yield_curve)))\n\nP = bond.dirtyPrice()\nh = 0.0001\ny0 = y.value()\ny.setValue(y0+h)\nP_plus = bond.dirtyPrice()\ny.setValue(y0-h)\nP_minus = bond.dirtyPrice()\nduration = - (P_plus - P_minus) / P / h / 2\nprint(f'Price = {P}, duration = {duration}')\nY = ql.InterestRate(y0, ql.Actual360(), ql.Compounded, ql.Semiannual)\nprint(ql.BondFunctions.duration(bond, Y, ql.Duration.Modified))","repo_name":"iEuler/quantlib_learn","sub_path":"test02.py","file_name":"test02.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"2885530066","text":"class Number():\n even=0 #Default value\n def check(self,num):\n if num%2==0:\n self.even=1\n\n def even_odd(self,num):\n self.check(num)\n if self.even==1:\n print('It is even8')\n\n else:\n print(\"It is odd\")\n\nn=Number()\nn.even_odd(20)\n","repo_name":"DSCTOCE/Algorithms","sub_path":"class.py","file_name":"class.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"73674878328","text":"from threading import Thread\nfrom flask import Flask, render_template, session\nfrom flask import request\nfrom flask.helpers import send_file\nfrom tornado.ioloop import IOLoop\nfrom flask_login import LoginManager, UserMixin\n\nfrom bokeh.server.server import Server\nfrom bokeh.embed import server_document\n\nfrom bokeh.models.widgets.tables import HTMLTemplateFormatter\nfrom bokeh.models import ColumnDataSource, DataTable, TableColumn, LinearColorMapper, ColorBar, Select\nfrom bokeh.models.widgets import Button, FileInput\nfrom bokeh.events import ButtonClick, DoubleTap\nfrom bokeh.layouts import Column, Row\nfrom bokeh.plotting import figure\nfrom bokeh.transform import transform, linear_cmap\nfrom bokeh.palettes import Viridis256\n\nfrom flask_sqlalchemy import SQLAlchemy\n\nimport pandas as pd\nfrom sklearn.metrics import confusion_matrix\n\nimport io\nimport base64\nimport uuid\n\nfrom torchvision import datasets\nfrom PIL import Image\n\n# flaskアプリケーション準備\napp = Flask(__name__)\napp.secret_key = 'mD6v2NsJ'\napp.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024 * 1024\n\n# flask_sqlalchemy準備\ndb = SQLAlchemy(app)\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\n# csv保存のためのユーザーオブジェクト定義(sqlite3)\nclass User(UserMixin, db.Model):\n id = db.Column(db.String(40), primary_key=True)\n csv_data = db.Column(db.PickleType())\ndb.create_all()\n\n# ログイン処理\n@login_manager.user_loader\ndef load_user(user_id):\n return User.query.get(user_id)\n\n# mnist画像ロード用datasetの用意\ntestset = datasets.MNIST(root='./data', train=False, download=True)\n\n# グローバル変数の準備\ntarget_data = pd.DataFrame()\nuser = None\n\n# mnist画像表示処理(indexで指定された画像をpng形式で返す)\n@app.route('/mnist', methods=['GET'])\ndef mnist():\n # index番号取得\n index = int(request.args.get('index', '-1'))\n if index == -1:\n return \"image not found\", 404\n \n # index番の画像の用意\n im = testset.data[index].detach().numpy()\n img = Image.fromarray(im)\n img_bin = io.BytesIO()\n img.save(img_bin, 'png')\n img_bin.seek(0)\n return send_file(img_bin, mimetype='image/png', as_attachment=False)\n\n# テーブルカラムの作成, indexフィールドがあればその画像のimgとリンクを表示する\ndef create_datatable_columns(df_columns):\n table_columns = []\n for column in df_columns:\n table_columns.append(TableColumn(field=column, title=column))\n # 画像のimgとリンクを表示\n if 'index' in df_columns:\n table_columns.append(TableColumn(field='index', title='image',\n formatter=HTMLTemplateFormatter(template='\" target=\"_blank\"> \"/> ')))\n return table_columns\n\ndef unvisible_other_plots(visible_plot, visible_plots):\n for plot in visible_plots:\n if plot != visible_plot:\n plot.visible = False\n return\n\ndef create_cm(column_change_functions, visible_plots, datatable_source):\n # 正解ラベル\n label_select = Select(title=\"正解ラベル:\", value=\"\", options=[\"\"])\n # 推論ラベル\n pred_select = Select(title=\"推論ラベル:\", value=\"\", options=[\"\"])\n\n # テーブルカラムが変わった時に呼ばれる関数\n def column_change(columns):\n label_select.options = columns\n pred_select.options = columns\n \n column_change_functions.append(column_change)\n\n # 混同行列ヒートマップ\n confusion_matrix_source = ColumnDataSource(data = {})\n\n tooltips=[\n ( 'count', '@count' ),\n ( 'label', '$y{0}' ),\n ( 'pred', '$x{0}' ),\n ]\n hm = figure(title=\"混同行列\", tools=\"hover\", toolbar_location=None, tooltips=tooltips)\n hm.y_range.flipped=True\n hm.visible = False\n visible_plots.append(hm)\n\n def cm_callback():\n global target_data\n cm = confusion_matrix(target_data[label_select.value], target_data[pred_select.value])\n cm = pd.DataFrame(cm)\n cm = cm.stack().reset_index().rename(columns={'level_0':label_select.value, 'level_1':pred_select.value,0:'count'})\n confusion_matrix_source.data = cm\n mapper = LinearColorMapper(palette=Viridis256, low=cm['count'].min(), high=cm['count'].max())\n hm.rect(x=pred_select.value, y=label_select.value, source=confusion_matrix_source, width=1, height=1, line_color=None, fill_color=transform('count', mapper))\n hm.text(x=pred_select.value, y=label_select.value, text=\"count\", text_font_style=\"bold\", source=confusion_matrix_source,\n text_align= \"left\", text_baseline=\"middle\")\n \n color_bar = ColorBar(color_mapper=mapper, label_standoff=12)\n hm.add_layout(color_bar, 'right')\n\n hm.visible = True\n unvisible_other_plots(hm ,visible_plots)\n\n def cm_click_callback(event):\n label = round(event.y)\n pred = round(event.x)\n data = target_data[(target_data[label_select.value]==label) & (target_data[pred_select.value]==pred)]\n datatable_source.data = data\n\n hm.on_event(DoubleTap, cm_click_callback)\n\n # 混同行列作成実行ボタン\n cm_button = Button(label=\"混同行列作成\", button_type=\"success\")\n cm_button.on_event(ButtonClick, cm_callback)\n\n # 混同行列オペレーションエリア\n cm_operation_area = Column(label_select, pred_select, cm_button)\n\n return cm_operation_area, hm\n\ndef create_scatter(column_change_functions, visible_plots, datatable_source):\n # 散布図x\n x_select = Select(title=\"散布図x:\", value=\"\", options=[\"\"])\n # 散布図y\n y_select = Select(title=\"散布図y:\", value=\"\", options=[\"\"])\n # 色カラム\n color_select = Select(title=\"色カラム:\", value=\"\", options=[\"\"])\n\n # テーブルカラムが変わった時に呼ばれる関数\n def column_change(columns):\n x_select.options = columns\n y_select.options = columns\n color_select.options = columns\n\n column_change_functions.append(column_change)\n\n scatter_plot = figure(title=\"特徴量空間\", tools=\"zoom_in,wheel_zoom,box_zoom,hover,box_select,poly_select,lasso_select,tap,reset\")\n scatter_plot.visible = False\n visible_plots.append(scatter_plot)\n\n scatter_source = ColumnDataSource()\n\n def on_scatter_change(self, attr, *callbacks):\n data = target_data.loc[scatter_source.selected.indices,:]\n datatable_source.data = data\n\n def scatter_callbacks():\n global target_data\n col = color_select.value\n scatter_source.data = {col: target_data[col], 'legend': [f'{col}_{x}' for x in target_data[col]], 'x':target_data[x_select.value], 'y': target_data[y_select.value]}\n mapper = linear_cmap(field_name=col, palette=Viridis256,\n low=target_data[col].min(), high=target_data[col].max())\n plot = scatter_plot.circle(x=\"x\", y=\"y\", source=scatter_source, line_color=mapper, color=mapper, legend_field='legend')\n plot.data_source.selected.on_change('indices', on_scatter_change)\n scatter_plot.legend.location = \"top_right\"\n scatter_plot.legend.click_policy = \"hide\"\n\n scatter_plot.visible = True\n unvisible_other_plots(scatter_plot, visible_plots)\n\n # 散布図作成実行ボタン\n scatter_button = Button(label=\"散布��作成\", button_type=\"success\")\n scatter_button.on_event(ButtonClick, scatter_callbacks)\n\n # 散布図オペレーションエリア\n scatter_operation_area = Column(x_select, y_select, color_select, scatter_button)\n\n return scatter_operation_area, scatter_plot\n\ndef call_column_change(column_change_functions, columns):\n for f in column_change_functions:\n f(columns)\n return\n\n# 画面要素の作成関数\ndef create_disp():\n ##### 各画面要素作成\n # テーブル作成\n df_columns = target_data.columns.tolist()\n datatable_source = ColumnDataSource(data = target_data)\n table_columns = create_datatable_columns(df_columns)\n data_table = DataTable(source=datatable_source,selectable = True, columns=table_columns,\n sortable = True)\n\n # カラムが変わった時に呼び出す関数リスト\n column_change_functions = []\n\n # 表示を切り替えるplotリスト\n visible_plots = []\n\n cm_operation_area, cm_plot_area = create_cm(column_change_functions, visible_plots, datatable_source)\n\n # upload button がクリックされた時の処理 \n def upload_button_callback(event):\n global target_data\n global user\n csv_str = base64.b64decode(csv_input.value)\n target_data = pd.read_csv(io.BytesIO(csv_str))\n df_columns = target_data.columns.tolist()\n call_column_change(column_change_functions, df_columns)\n table_columns = create_datatable_columns(df_columns)\n data_table.columns = table_columns\n datatable_source.data = target_data\n data_table.update()\n try:\n user.csv_data = target_data.to_json()\n db.session.commit()\n except Exception as e:\n warn = str(e)\n\n # csvアップロード実行ボタン\n upload_button = Button(label=\"Upload\", button_type=\"success\")\n upload_button.on_event(ButtonClick, upload_button_callback)\n\n # ファイル選択ボックス\n csv_input = FileInput()\n\n scatter_operation_area, scatter_plot_area = create_scatter(column_change_functions, visible_plots, datatable_source)\n\n # サブオペレーションエリア\n sub_operation_area = Row(cm_operation_area, scatter_operation_area)\n\n operation_area = Column(csv_input, upload_button, sub_operation_area, data_table)\n graph_area = Column(cm_plot_area, scatter_plot_area)\n layout_disp = Row(graph_area, operation_area)\n\n return layout_disp\n\ndef bkapp(doc):\n doc.add_root(create_disp())\n doc.title = \"mnist-viewer\"\n\n@app.route('/', methods=['GET'])\ndef bkapp_page():\n ##### セッションデータ読み込み開始\n user_id = session.get('user_id', str(uuid.uuid4()))\n session['user_id'] = user_id\n user = User.query.get(user_id)\n target_data = pd.DataFrame()\n if user is None:\n user = User(id=user_id, csv_data=pd.DataFrame().to_json())\n db.session.add(user)\n db.session.commit()\n\n try:\n target_data = pd.read_json(user.csv_data)\n except Exception as e:\n warn = str(e)\n\n script = server_document('http://localhost:5006/bkapp')\n return render_template(\"embed.html\", script=script, template=\"Flask\")\n\ndef bk_worker():\n server = Server({'/bkapp': bkapp}, io_loop=IOLoop(), allow_websocket_origin=[\"127.0.0.1:8080\"])\n server.start()\n server.io_loop.start()\n\nThread(target=bk_worker).start()\n\nif __name__ == '__main__':\n app.run(port=8080)\n","repo_name":"notfolder/mnist-viewer","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":10814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"40374736518","text":"import os\n\n### HUB CONFIGURATION ###\n# Tells the hub to listen on all IP since it's run in a docker container\nc.JupyterHub.hub_ip = '0.0.0.0'\n# Tells the users to connect back to the HUB ip\nc.JupyterHub.hub_connect_ip = os.environ[\"HUB_IP\"]\n# Defines the admins\nc.Authenticator.admin_users = {'jhadmin'}\n# Enables JupyterLab by default\nc.Spawner.default_url = '/lab'\n\n### AUTH CONFIGURATION ###\n\n# Tells the default authenticator to create new UNIX users (inside the docker) for managing user-passwords\nc.LocalAuthenticator.create_system_users = True\n\n\n### DOCKERSPAWNER CONFIGURATION ###\n# Select the Docker Spawner\nc.JupyterHub.spawner_class = \"docker\"\n# Tells the user containers to join the same network as the hub\nc.DockerSpawner.network_name = os.environ[\"DOCKER_NETWORK_NAME\"]\n# IMPORTANT: Tells the docker services to enable GPU on user containers\nc.DockerSpawner.extra_host_config = {'runtime': 'nvidia'}\n# Tells to clenup user containers when they are stopped\nc.DockerSpawner.remove = True\n\n#### DEFINE USER IMAGES ####\n# Dictionary of images that are proposed to the user. Image names should have already been built on the host machine\nc.DockerSpawner.allowed_images = {'Tensorflow Latest':'jupytergpu/tensorflow-notebook', 'SciPy Only': 'jupytergpu/base-notebook'}\n\n### USER CONTAINER CONFIGURATION ###\nnotebook_dir = os.environ.get('DOCKER_NOTEBOOK_DIR') or '/home/jovyan/'\n# Setup the notebook root folder for the user\nc.DockerSpawner.notebook_dir = notebook_dir\n\n### USER VOLUME CONFIGURATION ###\n# Mount the hub volumes to the user container\nmounted_user_workdir = os.path.join(notebook_dir, 'work')\nc.DockerSpawner.volumes = {\n '/home/jh_users/{username}/': {'bind': mounted_user_workdir, 'mode': 'rw'},\n '/mnt/sda2/': {'bind': os.path.join(notebook_dir, 'SHARED'), 'mode': 'ro'}\n}\n\n# FIX PERMISSION ON MOUNTED FOLDER\nc.DockerSpawner.post_start_cmd = f'fix-permissions {mounted_user_workdir}'\n\n","repo_name":"edoardogiacomello/JupyterHubGPU","sub_path":"jupyterhub/jupyterhub_config.py","file_name":"jupyterhub_config.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"74602613369","text":"import numpy\n\nh=numpy.loadtxt(fname='C:\\\\Users\\\\Amir Ali\\\\Google Drive\\\\Teaching-Health care operations management\\\\Python tutorial\\\\p_median-demand.txt', dtype=int, delimiter=',')\nd=numpy.loadtxt(fname='C:\\\\Users\\\\Amir Ali\\\\Google Drive\\\\Teaching-Health care operations management\\\\Python tutorial\\\\p_median-travel_time.txt', dtype=int, delimiter=' ')\n\nDemand_zone=range(0,5)\nFacility_zone=range(0,5)\n\nfrom gurobipy import *\n\nm=Model(\"p_median\")\n\nx=m.addVars(Facility_zone, vtype=GRB.BINARY)\ny=m.addVars(Demand_zone, Facility_zone, vtype=GRB.BINARY)\n\nm.setObjective(sum(h[i]*sum(d[i,j]*y[i,j] for j in Facility_zone) for i in Demand_zone), GRB.MINIMIZE)\n\nm.addConstr(sum(x[j] for j in Facility_zone)<=2, \"limited_facilities\")\nfor i in Demand_zone:\n for j in Facility_zone:\n m.addConstr(y[i,j]<=x[j], \"x_y_relationship[%d][%d] %i%j\")\n\nfor i in Demand_zone:\n m.addConstr(sum(y[i,j] for j in Facility_zone)==1, \"demand_assignment[%d] %i\")\n\nm.optimize()\n\nprint('the optimal objective value is: ', m.objVal)\n\nx_disp=m.getAttr('x', x)\ny_disp=m.getAttr('x', y)\n\nprint('the optimal solution is:\\n', x_disp)\nprint('the optimal assignemtn plan is:\\n',y_disp)\n\n\n","repo_name":"AmirAli-N/HealthCareOperations-Python","sub_path":"p_median.py","file_name":"p_median.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"2339013529","text":"\"\"\"\nDirty wrapping of the Mrtrix3 command necessary but not available in Nipype\n\nQuick and dirty wrappings using python function and nipype's Function interface of\nMrtrix3 commands\n\"\"\"\n# TO DO: implement clean wrappings by forking nipype\n\nimport nipype.pipeline.engine as pe\nfrom nipype.interfaces.utility import Function\n\n\ndef tcksift(input_tracks, wm_fod, act, filtered_tracks):\n \"\"\"Wrapping of the tcksift command\n\n Default options and stopping criteria with processing mask derived from act tissue file\n :param input_tracks: path of the tractogram to filter\n :param wm_fod: path of the white matter fiber orientation distribution volume\n used to filter the tractogram\n :param filtered_tracks: path of the filtered tractogram\n :return:\n \"\"\"\n import subprocess\n from distutils import spawn\n\n sift = spawn.find_executable(\"tcksift\")\n print(sift)\n cmd = [sift, \"-act\", act, input_tracks, wm_fod, filtered_tracks]\n subprocess.run(cmd)\n pass\n\n\ndef create_sift_filtering_node():\n \"\"\"\n\n :return:\n \"\"\"\n sift_filtering = pe.Node(\n name=\"sift_filtering\",\n interface=Function(\n input_names=[\"input_tracks\", \"wm_fod\", \"act\", \"filtered_tracks\"],\n output_names=[\"filtered_tracks\"],\n function=tcksift,\n ),\n )\n sift_filtering.inputs.filtered_tracks = \"filtered.tck\"\n return sift_filtering\n","repo_name":"alexpron/mrproc","sub_path":"mrproc/nodes/custom_nodes.py","file_name":"custom_nodes.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"21481814843","text":"def summa_tsifr(k):\r\n s = 0\r\n while k:\r\n s += k % 10\r\n k = k // 10\r\n return s\r\n\r\n\r\ndef main():\r\n n = int(input())\r\n arr1 = [int(i) for i in input().split()]\r\n arr2 = [0]*n\r\n for i in range(n):\r\n arr2[i] = summa_tsifr(arr1[i])\r\n arr3 = sorted(arr1, key=lambda i: (summa_tsifr(i), i))\r\n for i in range(n):\r\n print(arr3[i], end=' ')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"PNosikov/sphere-python","sub_path":"Homework1/dz1n2.py","file_name":"dz1n2.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"29953025545","text":"import numpy as np\nfrom offspect.cache.attrs import decode, encode\nfrom offspect.cache.file import TraceAttributes, TraceData\n\n# %%\ndef baseline(data, attrs):\n pre = decode(attrs[\"samples_pre_event\"])\n shift = decode(attrs[\"onset_shift\"]) or 0\n bl = data[: pre + shift].mean(0)\n data = data - bl\n return data\n\n\ndef detrend(data, attrs):\n slope = np.mean(np.diff(data), 0)\n correction = np.arange(0, len(data)) * slope\n data = data - correction\n return data\n\n\ndef linenoise(data, attrs):\n signal = data.copy()\n fs = decode(attrs[\"samplingrate\"])\n timestep = 1 / fs\n original_len = len(signal)\n filter_order = 100\n while len(signal) < fs:\n signal = np.pad(signal, (1, 0), \"constant\", constant_values=(0))\n fourier = np.fft.fft(signal)\n freq = np.fft.fftfreq(len(signal), d=timestep)\n fidx = int(np.where(freq == 50)[0][0])\n fourier[fidx] = 0\n signal = np.real(np.fft.ifft(fourier))\n signal = signal[-original_len:]\n data[:] = signal\n return data\n\n\ndef flipsign(data, attrs):\n return -data\n\n\nPreProcessor = {\n \"baseline\": baseline,\n \"detrend\": detrend,\n \"linenoise\": linenoise,\n \"flipsign\": flipsign,\n}\n\n\ndef process_data(\n data, attrs, key: str = \"_log\", delim: str = \" on \", verbose: bool = True\n) -> TraceData:\n \"\"\"return TraceData processed by the steps in the field indexed by key\n \n args\n ----\n data: TraceData\n the tracedata\n attrs:TraceAttributes\n the traceattributes\n key: str\n which field is used for logging the processing steps\n\n\n returns\n -------\n data: TraceData \n the date stored for this trace, but processed with the steps performed \n \"\"\"\n if key in attrs.keys():\n log = decode(attrs[key])\n for event in log:\n step, when = event.split(delim)\n if verbose:\n print(\"STEPS: Replaying\", step, \"from\", when)\n data = PreProcessor[step](data, attrs)\n else:\n if verbose:\n print(\"No processing steps cached\")\n return data\n\n","repo_name":"neuromti/tool-offspect","sub_path":"offspect/cache/steps.py","file_name":"steps.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"794181433","text":"import asyncio\nimport aiomysql\n\n\nasync def establish_connection(settings):\n connection = await aiomysql.connect(\n host=settings['host'],\n port=settings['port'],\n user=settings['user'],\n password=settings['password'],\n db=settings['db'])\n return connection\n\n\nasync def create_table(conn):\n async with conn.cursor() as cur:\n sql_query = '''CREATE TABLE IF NOT EXISTS users (\n id int(11) NOT NULL AUTO_INCREMENT,\n name varchar(100) DEFAULT NULL,\n lon float DEFAULT NULL,\n lat float DEFAULT NULL,\n PRIMARY KEY (id)\n ) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1'''\n await cur.execute(sql_query)\n\n\nasync def get_all_users(conn):\n async with conn.cursor() as cur:\n await cur.execute('SELECT * from users;')\n users_data = await cur.fetchall()\n return users_data\n\n\nasync def add_user_to_db(conn, name, lon, lat):\n async with conn.cursor() as cur:\n sql_query = '''INSERT INTO users (name, lon, lat)\n VALUES (%s, %s, %s)'''\n await cur.execute(sql_query, (name, lon, lat))\n await cur.execute('SELECT LAST_INSERT_ID();')\n user_id = await cur.fetchone()\n await conn.commit()\n return user_id[0]\n\n\nasync def get_neighbors_by_ids(conn, ids):\n async with conn.cursor() as cur:\n fmt_str = ','.join(['%s'] * len(ids))\n await cur.execute(f'SELECT id, name FROM users WHERE id IN ({fmt_str})',\n ids)\n users = await cur.fetchall()\n return users\n","repo_name":"gorban-lobs/find_neighbors","sub_path":"find_neighbors/db_logic.py","file_name":"db_logic.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"16732687097","text":"from random import randint\n\nfrom django.core.management.base import BaseCommand\n\nfrom images.factories import ImageFactory\n\n\nclass Command(BaseCommand):\n args = ' [quantity]'\n help = (\n 'Image types: book | cosmetic | food | garment | software | vehicle'\n )\n\n def handle(self, *args, **options):\n try:\n category = {\n 'book': 'business',\n 'cosmetic': 'people',\n 'food': 'food',\n 'garment': 'fashion',\n 'software': 'technics',\n 'vehicle': 'transport'\n }.get(args[0].lower())\n except IndexError:\n return (\n 'Please declare a type of image, read help for available '\n 'options.'\n )\n\n try:\n quantity = int(args[1])\n except IndexError:\n quantity = randint(20, 30)\n\n print('Creating Images')\n\n for i in range(quantity):\n url = 'http://lorempixel.com/{width}/{height}/{category}'.format(\n width=randint(100, 500),\n height=randint(100, 500),\n category=category\n\n )\n ImageFactory(url=url)\n print(url)\n","repo_name":"commoncode/images","sub_path":"images/management/commands/create_images.py","file_name":"create_images.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"16152128559","text":"import ray\nfrom ray.rllib.algorithms import alpha_zero\nfrom ray.rllib.utils.test_utils import check_train_results\nfrom ray.tune.registry import register_env\n\nfrom env import BPP\nfrom model import Agent\n\nregister_env('Bpp-v1', BPP)\n\n\ndef train():\n ray.init(num_gpus=1)\n\n mcts_config = {\n \"puct_coefficient\": 1.0,\n \"num_simulations\": 300,\n \"temperature\": 1.5,\n \"dirichlet_epsilon\": 0.25,\n \"dirichlet_noise\": 0.03,\n \"argmax_tree_policy\": True,\n \"add_dirichlet_noise\": True,\n }\n\n env_config = {'bin_size': [10, 10], 'max_bin_size': [10, 10], 'num_items': 10}\n\n ranked_rewards = {\n \"enable\": True,\n \"percentile\": 75,\n \"buffer_max_length\": 1000,\n \"initialize_buffer\": True,\n \"num_init_rewards\": 100,\n }\n\n config = (\n alpha_zero.AlphaZeroConfig()\n .environment(env='Bpp-v1', env_config=env_config)\n .training(model={\"custom_model\": Agent},\n mcts_config=mcts_config,\n num_sgd_iter=10,\n ranked_rewards=ranked_rewards)\n .rollouts(num_rollout_workers=16)\n )\n\n num_iterations = 50\n\n algo = config.build()\n\n for i in range(num_iterations):\n print(f'Training iteration: {i + 1}')\n results = algo.train()\n\n path = algo.save()\n\n print(f'Model saved to {path}')\n algo.stop()\n\n ray.shutdown()\n\n\nif __name__ == '__main__':\n train()","repo_name":"shiveshkhaitan/ranked_reward_rl","sub_path":"ranked_reward/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"6958889468","text":"# count(start,step): iteration starts from the start number and prints in the steps mentioned \n\nimport itertools\n\nfor i in itertools.count(5,5):\n if i == 105:\n break\n else:\n print(i,end=\" \")\nprint(\"\\n\")\n# cycle(iterable): This iterator prints all values in order from the passed container. It restarts printing from the beginning again when all elements are printed in a cyclic manner.\n\ncount = 0\n\nfor i in itertools.cycle(\"AM \"):\n if count > 11:\n break\n else:\n print(i)\n count +=1\nprint (\"\\n\")\n\n# Python program to demonstrate\n# infinite iterators\n\nimport itertools\n\nl = ['Geeks', 'for', 'Geeks']\n\n# defining iterator\niterators = itertools.cycle(l)\n\n# for in loop\nfor i in range(6):\n\t\n\t# Using next function\n\tprint(next(iterators), end = \" \")\nprint(\"\\n\") \n\n\n\n# repeat(val, num): This iterator repeatedly prints the passed value an infinite number of times. If the optional keyword num is mentioned, then it repeatedly prints num number of times.\n\nprint(\"Printing the numbers repeatedly \")\nprint(tuple(itertools.repeat(5,6)))\n","repo_name":"Amruth56/Python","sub_path":"control flow/06_itertools.py","file_name":"06_itertools.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"37939536082","text":"class Parser:\n\n def __init__(self):\n grammar_text = open('grammar', 'r').read()\n self.non_terminals = []\n self.terminals = ['(', ')', '+', '-', '*', '/', 'id', 'num', '$']\n self.start_symbol = 'E'\n self.grammar = self.structure_grammar(grammar_text.replace(' ', ''))\n self.first_sets = {}\n self.follow_sets = {}\n for non_terminal in self.grammar:\n self.first_sets[non_terminal] = self.get_first_set(non_terminal)\n self.follow_sets[non_terminal] = self.get_follow_set(non_terminal)\n\n def get_first_of_production(self, production):\n first_of_production = set()\n for symbol in production:\n if symbol in self.non_terminals:\n first = self.get_first_set(symbol)\n first_of_production = first_of_production.union(first)\n if 'ε' in first:\n continue\n else:\n break\n else:\n first_of_production.add(symbol)\n break\n\n return first_of_production\n\n def get_first_set(self, non_terminal):\n if non_terminal in self.first_sets:\n return self.first_sets[non_terminal]\n\n first_set = set()\n for production in self.grammar[non_terminal]:\n first_set = first_set.union(self.get_first_of_production(production))\n\n return first_set\n\n def get_follow_set(self, non_terminal):\n if non_terminal in self.follow_sets:\n return self.follow_sets[non_terminal]\n\n follow_set = {'ε'}\n if non_terminal == self.start_symbol:\n follow_set.add('$')\n\n for symbol, productions in self.grammar.items():\n for production in productions:\n for i in range(len(production)):\n if production[i] == non_terminal:\n for next_symbol in production[i + 1:]:\n if 'ε' in follow_set:\n follow_set.remove('ε')\n if next_symbol in self.non_terminals:\n follow_set = follow_set.union(self.get_first_set(next_symbol))\n if 'ε' in follow_set:\n continue\n else:\n break\n else:\n follow_set.add(next_symbol)\n break\n\n if 'ε' in follow_set:\n follow_set.remove('ε')\n if symbol != non_terminal:\n follow_set = follow_set.union(self.get_follow_set(symbol))\n\n return follow_set\n\n def is_nullable(self, non_terminal):\n for productions in self.grammar[non_terminal]:\n for production in productions:\n for symbol in production:\n if symbol == 'ε':\n return 'Yes'\n return 'No'\n\n def get_parse_table(self, non_terminal):\n parse_row = ['\\t '] * len(self.terminals)\n for production in self.grammar[non_terminal]:\n first_of_production = self.get_first_of_production(production)\n if 'ε' in first_of_production:\n first_of_production.remove('ε')\n first_of_production = first_of_production.union(self.get_follow_set(non_terminal))\n indices = [self.terminals.index(terminal) for terminal in first_of_production]\n for i in indices:\n parse_row[i] = non_terminal + ' → ' + ''.join(production)\n for k in range(7 - len(parse_row[i])):\n parse_row[i] += ' '\n\n return parse_row\n\n def structure_grammar(self, grammar_text):\n grammar = {}\n grammar_text = grammar_text.split('\\n')[:-1]\n grammar_text = [line + \"\\n\" for line in grammar_text]\n\n separate_grammar_text = []\n for line in grammar_text:\n separate_grammar_text.append(line.split('→'))\n\n self.non_terminals = [item[0] for item in separate_grammar_text]\n\n for non_terminal, productions in separate_grammar_text:\n accumulator = ['']\n grammar[non_terminal] = []\n for character in productions:\n if character == '|' or character == '\\n':\n grammar[non_terminal].append(accumulator[:-1])\n accumulator = ['']\n else:\n accumulator[-1] += character\n if accumulator[-1] in self.terminals + self.non_terminals + ['ε']:\n accumulator += ['']\n\n return grammar\n\n def print_tables(self):\n\n alt_3_2 = 2\n\n\n print('\\n\\nFIRST FOLLOW SETS:\\n')\n print('Non-terminal| Nullable |\\t\\tFIRST\\t\\t|\\tFOLLOW')\n for non_terminal in self.grammar:\n print('------------|-----------|-------------------|----------------')\n print('\\t' + non_terminal + '\\t\\t|\\t ' + self.is_nullable(non_terminal), end='\\t|\\t ')\n print(*self.first_sets[non_terminal], sep=' ', end='')\n for i in range(alt_3_2):\n print('\\t', end='')\n\n print('|\\t', end='')\n print(*self.follow_sets[non_terminal], sep=' ')\n alt_3_2 = int(6 / alt_3_2)\n\n print('\\n\\nPARSE TABLE:\\n\\n\\t|\\t', end='')\n print(*self.terminals, sep='\\t|\\t', end='\\n')\n for non_terminal in self.grammar:\n print('----|-------|-------|-------|-------|-------|-------|-------|-------|-------')\n print(non_terminal, end='\\t|')\n print(*self.get_parse_table(non_terminal), sep='|')\n\n\nif __name__ == '__main__':\n Parser().print_tables()\n","repo_name":"usamakh20/Compiler_Construction_Labs","sub_path":"Lab_9/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":5819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"1125775109","text":"import pickle\nimport os\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nimport joblib\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import StrMethodFormatter\nimport streamlit as st\nfrom PIL import Image\nimport yaml\nfrom src.pipeline.predict_pipeline import PredictPipeline\nfrom src.utils import load_object\n\ntransformer_path = os.path.join(\"artifacts\", \"proprocessor.pkl\")\nmodel_path = os.path.join(\"artifacts\", \"model.pkl\")\n# Load model a\n\nmodel = joblib.load(model_path)\npreprocessor = joblib.load(transformer_path)\n\ndef visualize_confidence_level(prediction_proba):\n \"\"\"\n this function uses matplotlib to create inference bar chart rendered with streamlit in real-time\n return type : matplotlib bar chart\n \"\"\"\n data = (prediction_proba[0]*100).round(2)\n grad_percentage = pd.DataFrame(data = data,columns = ['Percentage'],index = ['Low','Ave','High'])\n ax = grad_percentage.plot(kind='barh', figsize=(7, 4), color='#722f37', zorder=10, width=0.5)\n ax.legend().set_visible(False)\n ax.set_xlim(xmin=0, xmax=100)\n\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.spines['left'].set_visible(True)\n ax.spines['bottom'].set_visible(True)\n\n ax.tick_params(axis=\"both\", which=\"both\", bottom=\"off\", top=\"off\", labelbottom=\"on\", left=\"off\", right=\"off\", labelleft=\"on\")\n\n vals = ax.get_xticks()\n for tick in vals:\n ax.axvline(x=tick, linestyle='dashed', alpha=0.4, color='#eeeeee', zorder=1)\n\n ax.set_xlabel(\" Percentage(%) Confidence Level\", labelpad=2, weight='bold', size=12)\n ax.set_ylabel(\"Wine Quality\", labelpad=10, weight='bold', size=12)\n ax.set_title('Prediction Confidence Level ', fontdict=None, loc='center', pad=None, weight='bold')\n\n st.pyplot()\n return\n\nst.title('POC Early Warning System')\n\nst.markdown(\"\"\"\nCurrently, we employ a one-size-fits-all system for identifying at-risk students, using indicators such as attendance below 90%, the number of D's and F's in grades, and the frequency of suspensions in discipline records. However, this approach lacks specificity regarding what students are at risk of, be it graduation, college admission, or success on college placement tests.\n\nThe primary purpose of project is to leverage client data to create individualized indicators of students at-risk of not graduating. This versatile framework which can serve as a template for predicting various outcomes whether they are continuous, binary, or multiclass.\n\n## Instructions\n1. Select the features from the sidebar\n2. Model will provide a prediction at the bottom of the page\n\n\n## Dataset Source :\n\n\nYou can also :\n* Check the **GitHub Project Repository**\n [](https://github.com/rjwdata/poc-early-warning)\n\"\"\")\ndf = pd.read_csv(os.path.join('data','raw','train','train.csv'))\n\nst.header('Student Data Overview')\nst.write('Data Dimension: ' + str(df.shape[0]) + ' rows and ' + str(df.shape[1]) + ' columns.')\nst.dataframe(df)\n\n#read in wine image and render with streamlit\n#image = Image.open('wine_image.png')\n#st.image(image, caption='wine company',use_column_width=True)\n\nst.sidebar.header('User Input Parameters') #user input parameter collection with streamlit side bar\n\n\ndef get_user_input():\n \"\"\"\n this function is used to get user input using sidebar slider and selectbox\n return type : pandas dataframe\n\n \"\"\"\n male = st.sidebar.selectbox(\"Select Male\",(\"yes\", \"no\"))\n race_ethnicity = st.sidebar.selectbox(\"Select Race/Ethnicity\",('African-American', 'Asian/Pacific Islander', 'Hispanic', 'Multiple/Native American', 'Other'))\n iep = st.sidebar.selectbox(\"Select IEP Services\",('yes', 'no'))\n frpl = st.sidebar.selectbox(\"Select FRPL Services\",('yes', 'no'))\n ell = st.sidebar.selectbox(\"Select ELL Services\",('yes', 'no'))\n ap_ever_take_class = st.sidebar.selectbox(\"Select AP Ever\",('yes', 'no'))\n ever_alternative = st.sidebar.selectbox(\"Select Alternate Ever\",('yes', 'no'))\n gpa = st.sidebar.slider('Select GPA', 0.0, 4.0, 2.80)\n math_ss = st.sidebar.slider('Select Math SS', 0, 200, 50)\n read_ss = st.sidebar.slider('Select Read SS', 0, 200, 50)\n pct_days_absent = st.sidebar.slider('Select Percentage of Days Missed', 0.0, 100.0, 8.5)\n scale_score_11_comp = st.sidebar.slider('Select ACT Composite Score', 0.0, 36.0, 19.0)\n scale_score_11_eng = st.sidebar.slider('Select ACT English Score', 0.0, 36.0, 19.0)\n scale_score_11_math = st.sidebar.slider('Select ACT Math Score', 0.0, 36.0, 19.0)\n scale_score_11_read = st.sidebar.slider('Select ACT Reading Score', 0.0, 36.0, 20.0)\n\n features = {\n 'male': male,\n 'race_ethnicity':race_ethnicity,\n 'iep':iep,\n 'frpl':frpl,\n 'ell':ell,\n 'ap_ever_take_class':ap_ever_take_class,\n 'ever_alternative':ever_alternative,\n 'gpa':gpa,\n 'pct_days_absent':pct_days_absent,\n 'math_ss':math_ss,\n 'read_ss':read_ss,\n 'scale_score_11_comp':scale_score_11_comp,\n 'scale_score_11_eng':scale_score_11_eng,\n 'scale_score_11_math':scale_score_11_math,\n 'scale_score_11_read':scale_score_11_read\n }\n data = pd.DataFrame(features,index=[0])\n\n return data\n\n\nuser_input_df = get_user_input()\n\npredict_pipeline = PredictPipeline()\nprediction = predict_pipeline.predict(user_input_df)\n# params_path = \"params.yaml\"\n\n# def read_params(config_path = params_path):\n # with open(config_path) as yaml_file:\n # config = yaml.safe_load(yaml_file)\n # return config\n\n# def predict(data):\n # config = read_params(params_path)\n # model_dir_path = config[\"webapp_model_dir\"]\n # model = joblib.load(model_dir_path)\n # prediction = model.predict(data)\n # return prediction\n\nst.subheader('User Input parameters')\nst.write(user_input_df)\n\nif prediction[0] == 1:\n grad = 'Diploma'\nelse:\n grad = 'No Diploma'\n\nhs_grad = prediction[1]*100\nno_hs_grad = 1 - prediction[1]*100\n\ncol1, col2, col3 = st.columns(3)\ncol1.metric(\"Diploma Prediction\", grad)\ncol2.metric('Probability of HS Diploma', hs_grad)\ncol3.metric('Prbability of no HS Diploma', no_hs_grad)\n\n#prediction_proba = model.predict_prob(user_input_df)\n\n#visualize_confidence_level(prediction_proba)\n","repo_name":"rjwdata/poc-early-warning","sub_path":"app_pred.py","file_name":"app_pred.py","file_ext":"py","file_size_in_byte":6419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"27321933919","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def addOneRow(self, root: Optional[TreeNode], val: int, target_depth: int) -> Optional[TreeNode]: \n if target_depth == 1:\n return TreeNode(val, left=root)\n \n queue = deque([(root, 1)])\n \n visited = set([root])\n \n nodes = []\n \n \n while queue:\n current, depth = queue.popleft()\n \n if depth == target_depth - 1:\n nodes.append(current)\n \n if current.left:\n queue.append((current.left, depth + 1))\n visited.add(current.left)\n \n if current.right:\n queue.append((current.right, depth + 1))\n visited.add(current.right)\n \n \n for node in nodes:\n prev_left = node.left\n prev_right = node.right\n \n node.left = TreeNode(val, left=prev_left)\n node.right = TreeNode(val, right=prev_right)\n \n return root","repo_name":"meraf00/Competitive-Programming","sub_path":"0623-add-one-row-to-tree/0623-add-one-row-to-tree.py","file_name":"0623-add-one-row-to-tree.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"73794682168","text":"from scapy.all import *\nimport time\nimport optparse\nimport os\n\nconf.verb = 0\n\nap = optparse.args.ap\nsta = optparse.args.sta\nssid = optparse.args.ssid\nch = optparse.args.ch\niface = optparse.args.iface\n \nALGO_OPEN_AUTH = 0 # OPN\nSTART_SEQNUM = 1 # sequence number\nSYSTEM_STR = \"[\\x1b[36m*\\x1b[0m]\"\nWARN_STR = \"[\\x1b[31m!\\x1b[0m]\"\nINFO_STR = \"\\x1b[33m-\\x1b[0m\"\n\ndef auth_attack():\n os.system('clear')\n # Channel Switching\n channel_switch(iface, ch)\n show_info()\n\n # Authentication\n auth_frame = RadioTap()\\\n /Dot11(type=0, subtype=11, addr1=ap, addr2=sta, addr3=ap)\\\n /Dot11Auth(algo=ALGO_OPEN_AUTH, seqnum=START_SEQNUM)\n \n # Association\n assoc_frame = RadioTap()\\\n /Dot11(type=0, subtype=0, addr1=ap, addr2=sta, addr3=ap)\\\n /Dot11AssoReq()\\\n /Dot11Elt(ID='SSID', info=ssid)\n \n print(WARN_STR+\" Attack\")\n for i in range(0,4):\n sendp(auth_frame, iface=iface,count=4)\n sendp(assoc_frame, iface=iface,count=4)\n printProgressBar()\n for i in range(0,300):\n sendp(auth_frame, iface=iface,count=4)\n sendp(assoc_frame, iface=iface,count=4)\n printProgressBar()\n\n\ndef printProgressBar():\n print(\"\\x1b[36m->\\x1b[0m\",end=\"\",flush=True)\n \n\ndef channel_switch(iface,ch):\n print(WARN_STR+\" Channel Switching : Ch.\"+str(ch))\n os.system('iwconfig ' + iface + ' channel ' + str(ch))\n\ndef show_info():\n print(SYSTEM_STR+\" Information\")\n print(\"\\t\"+INFO_STR+\" Access Point MAC Address (BSSID) : %s\" % ap)\n print(\"\\t\"+INFO_STR+\" Station MAC Address : %s\" % sta)\n print(\"\\t\"+INFO_STR+\" SSID Information : %s\" % ssid)\n print(\"\\t\"+INFO_STR+\" Channel : Ch.%s\" % ch)\n print(\"\\t\"+INFO_STR+\" Interface : %s\" % iface)\n\nif __name__=='__main__':\n auth_attack()\n\n","repo_name":"netduck/duck-tools","sub_path":"python/auth_attack/auth_attack.py","file_name":"auth_attack.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"77"}
+{"seq_id":"20863932494","text":"# A constructor in Python is a special method within a class that is automatically called when you create an\n# object of that class. It typically initializes the object's attributes or performs any setup needed for the\n# object to function properly. In Python, the constructor method is named `__init__`.\nclass Person():\n def __init__(self, name, occ):\n self.name = name\n self.occupation = occ\n\n def intro(self):\n print(f\"Hey my name is {self.name} and I am a {self.occupation}.\")\n\n\n# a,b,c are objects\na = Person(\"Mohammad Arsalan Rather\", \"Python Developer\")\nb = Person(\"Victor\", \"Camper\")\nc = Person(\"Sara\", \"PUBG Character\")\n\na.intro()\nb.intro()\nc.intro()\n","repo_name":"Arslanamin404/Python","sub_path":"Introduction-to-OOP/constuctor.py","file_name":"constuctor.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"17183175973","text":"\"\"\"This module was used for the mypy anylysis in the thesis.\"\"\"\nimport ast\nimport json\nimport mypy.api\nimport os\nimport typing\n# Own module\nfrom scripts.sql.db_fill_repos import DBHelper\n\n\nbasic_types = [\"int\", \"float\", \"complex\", \"str\", \"bool\"]\n\n\nclass FunctionFinder(ast.NodeVisitor):\n def __init__(self, function_name: str):\n self.function_name = function_name\n self.fount_function = None\n\n def visit_FunctionDef(self, node):\n if self.fount_function:\n return\n if node.name == self.function_name:\n self.fount_function = node\n return\n self.generic_visit(node)\n\n\ndef get_annotation_name(node):\n if isinstance(node, ast.Name):\n if node.id in basic_types:\n return node.id\n return \"ERROR\"\n # Check if it is a literal\n elif isinstance(node, ast.Subscript) and isinstance(node.value, ast.Name) and node.value.id == \"Literal\" and \\\n isinstance(node.slice, ast.Constant):\n return node.slice.value\n # Check if it is Optional\n elif isinstance(node, ast.Subscript) and isinstance(node.value, ast.Name) and node.value.id == \"Optional\":\n return get_annotation_name(node.slice)\n # Check if it is a Union\n elif isinstance(node, ast.Subscript) and isinstance(node.value, ast.Name) and node.value.id == \"Union\":\n if isinstance(node.slice, ast.Tuple):\n for element in node.slice.elts:\n ret_for_el = get_annotation_name(element)\n if ret_for_el != \"ERROR\":\n return ret_for_el\n elif isinstance(node, ast.Constant):\n try:\n if node.value and 'dict' in node.value: # Faulty type annotation\n return \"ERROR\"\n except TypeError:\n return \"ERROR\"\n return node.value\n else:\n return \"ERROR\"\n\n\ndef get_function_ast(file_path: str, function_name: str) -> ast.FunctionDef:\n finder = FunctionFinder(function_name)\n try:\n with open(file_path, \"r\") as f:\n code = f.read()\n except FileNotFoundError:\n return\n try:\n tree = ast.parse(code)\n finder.visit(tree)\n return finder.fount_function\n except (SyntaxError, ValueError, RuntimeError, UnboundLocalError):\n return\n\n\ndef get_function_info(function_ast: ast.FunctionDef) -> (dict, str):\n # Get arguments and their type annotations\n args = {arg.arg: get_annotation_name(arg.annotation)\n for arg in function_ast.args.args if arg.annotation is not None}\n\n # Get return type annotation\n returns = get_annotation_name(function_ast.returns) if function_ast.returns else None\n\n return args, returns\n\n\ndef create_argument_dict(args: dict) -> typing.Optional[dict]:\n for arg in args:\n if args[arg] == \"ERROR\":\n return None\n elif isinstance(args[arg], str):\n if args[arg] == \"int\":\n args[arg] = 10\n elif args[arg] == \"float\":\n args[arg] = 2.0\n elif args[arg] == \"complex\":\n args[arg] = 1j\n elif args[arg] == \"str\":\n args[arg] = \"something\"\n elif args[arg] == \"bool\":\n args[arg] = True\n elif args[arg] == \"None\":\n args[arg] = None\n else:\n return None\n return args\n\n\ndef run_function(function_ast, args):\n # Convert AST to code\n code = compile(ast.Module(body=[function_ast], type_ignores=[]), filename=\"\", mode=\"exec\")\n\n # Create a new namespace and execute the function\n namespace = {\"Literal\": typing.Literal}\n exec(code, namespace)\n\n # Run the function with the provided arguments\n return namespace[function_ast.name](**args)\n\n\ndef my_type_check_function(function_ast: ast.FunctionDef):\n # Get the function arguments and return type\n args, returns = get_function_info(function_ast)\n\n # Create a dictionary with the arguments and their values\n args = create_argument_dict(args)\n\n # If the arguments could not be created, skip the function\n if args is None:\n return \"Arguments could not be created\", args\n\n # Run the function with the arguments\n try:\n res = run_function(function_ast, args)\n except TypeError as e:\n if \"missing\" in str(e) and (\"required positional argument\" in str(e),\n \"required keyword-only argument\" in str(e)):\n return \"Missing\", e.args\n else:\n return \"MeinTypeError!\", e.args\n except (NameError, NotImplementedError, ImportError, AttributeError, ValueError, RuntimeError, UnboundLocalError,\n SyntaxError, FileNotFoundError, IndexError, KeyError, ZeroDivisionError, AssertionError) as e:\n return \"BadError!\", e.args\n\n # Check return has the correct type\n if returns == \"ERROR\":\n return \"ERROR!\", \"No trivial return type\"\n elif not isinstance(returns, str):\n return res == returns, (res, returns)\n else:\n return isinstance(res, eval(returns)), (res, returns)\n\n\ndef load_from_json(file_name: str) -> typing.Union[dict, list]:\n with open(file_name, 'r') as f:\n return json.load(f)\n\n\ndef store_to_json(file_name: str, data: dict):\n with open(file_name, 'w') as f:\n json.dump(data, f)\n\n\ndef get_repo_from_file_path(file_path: str) -> str:\n directories = file_path.split(os.sep)\n # Get parent directory:\n return os.sep.join(directories[:12])\n\n\ndef get_repos_to_check(full_list: list, last_repo_checked: int):\n repos_to_check = []\n for repo_id, file_path, _, _, _ in full_list:\n repo_path = get_repo_from_file_path(file_path)\n if repos_to_check and repos_to_check[-1][0] == repo_id:\n continue\n repos_to_check.append((repo_id, repo_path))\n return repos_to_check\n\n\ndef handle_mypy_file(repo_path: str) -> bool:\n result = mypy.api.run([repo_path,\n \"--show-error-codes\", \"--namespace-packages\",\n \"--ignore-missing-imports\", \"--show-column-numbers\"])\n if result[0]: # Mypy found TypeError\n return False\n else: # Mypy did not find TypeError\n return True\n\n\ndef handle_mypy_file_with_return(repo_path: str) -> typing.Optional:\n result = mypy.api.run([repo_path,\n \"--show-error-codes\", \"--namespace-packages\",\n \"--ignore-missing-imports\", \"--show-column-numbers\"])\n return result[0]\n\n\ndef main_mypy(full_list, verbose: bool = False):\n handled_repo_json_file_path = \"mypy_progress.json\"\n handled_repos: dict[int, bool] = load_from_json(handled_repo_json_file_path)\n # Get highest number already checked\n current_repo_id = 7066\n repos_to_check = get_repos_to_check(full_list, 0)\n total_repos = len(full_list)\n for repo in repos_to_check:\n if repo[0] <= current_repo_id:\n continue\n if verbose:\n current_repo_id = repo[0]\n print(\"{}% Checking repo: {}/{}\".format(round(current_repo_id / 100, 2),\n current_repo_id, 10000))\n all_fine = handle_mypy_file(repo[1])\n handled_repos[repo[0]] = all_fine\n store_to_json(handled_repo_json_file_path, handled_repos)\n\n\ndef main():\n verbose: bool = True\n # Get fully annotated functions from database\n if verbose:\n print(\"Getting fully annotated functions from database...\", end=\"\")\n db = DBHelper()\n full_list = db.get_full_annotated_functions()\n exit(len(full_list))\n # Check all functions with my checker\n if verbose:\n print(\"Done.\")\n # Get mypy to check all files\n # mypy checks already done\n handled_repo_json_file_path = \"mypy_progress.json\"\n handled_repos: dict[str, bool] = load_from_json(handled_repo_json_file_path)\n # main_mypy(full_list, verbose=True)\n last_progress = .0\n important_repo_stuff = []\n # Go through each function\n for i, func in enumerate(full_list):\n if func[0] in [191, 2158, 2023, 5075, 5312]:\n continue\n if func[0] == 6005 and func[2] == \"_resource_arn\":\n pass\n else:\n continue\n # Look for repositories that were type correct according to mypy\n try:\n mypy_fine = handled_repos[repr(func[0])]\n except KeyError:\n mypy_fine = False\n if not mypy_fine:\n continue\n if verbose:\n progress = round(i / len(full_list) * 100, 1)\n # if progress > last_progress:\n last_progress = progress\n print(\"{}%: Checking id: {}/{}: {}\".format(progress, func[0], 10000, func[2]))\n # Get the function AST\n function_ast = get_function_ast(func[1], func[2])\n if function_ast is None:\n continue\n # Check the function with random arguments\n my_check = my_type_check_function(function_ast)\n if my_check is False or (isinstance(my_check[0], str) and \"MeinTypeError!\" in my_check[0]): # or True:\n try:\n important_repo_stuff.append((func[0], func[1], func[2], my_check))\n except TypeError:\n pass\n # try:\n # store_to_json(\"D:\\\\Chris\\\\Documents\\\\Uni\\\\23_SoSe\\\\Bachelorarbeit\\\\github\\\\data\\\\scripts\\\\important_repo_stuff.json\",\n # important_repo_stuff)\n # except TypeError:\n # important_repo_stuff.pop()\n\n\ndef manual_type_check():\n # Import files greenlight by mypy\n file_list = load_from_json(\"mypy_no_error_repos.json\")\n # Get repositories\n file_set = set()\n for file in file_list:\n file_set.add(get_repo_from_file_path(file[1]))\n repo_list = list(file_set)\n # Double check mypy results\n for repo in repo_list:\n mypy_result = handle_mypy_file_with_return(repo)\n print(\"{}: {}\".format(repo, mypy_result))\n # Check function with default types\n for file in file_list:\n function_ast = get_function_ast(file[1], file[2])\n if function_ast is None:\n continue\n my_check = my_type_check_function(function_ast)\n if not my_check:\n print(\"{}: {}\".format(file[2], my_check))\n input()\n\n\ndef trying_functions():\n def _resource_arn(name: str, pattern: str, account_id: str = None, region_name: str = None) -> str:\n if \":\" in name:\n return name\n account_id = account_id\n region_name = region_name\n if len(pattern.split(\"%s\")) == 3:\n return pattern % (account_id, name)\n return pattern % (region_name, account_id, name)\n arguments = {\"int\": 10, \"float\": 2.0, \"complex\": 1j, \"str\": \"something\", \"bool\": True, \"None\": None}\n name = arguments[\"str\"]\n pattern = arguments[\"str\"]\n account_id = arguments[\"str\"]\n region_name = arguments[\"str\"]\n print(_resource_arn(name, pattern, account_id, region_name))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Proglang-Uni-Freiburg/PythonAnnotations","sub_path":"scripts/analyzer/slim_analyzer.py","file_name":"slim_analyzer.py","file_ext":"py","file_size_in_byte":10980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"19802654861","text":"import threading\nimport time\n\nclock_is_work = True\n\ndef clock(interval):\n while clock_is_work:\n print('The time is ' + str(time.localtime()) + ' s')\n time.sleep(interval)\n\n\nif __name__ == '__main__':\n print('Threading...')\n\n thread_1 = threading.Thread(target=clock, args=(1,))\n thread_1.daemon = True\n thread_1.start()\n\n\n # time.sleep(20)\n\n # thread_1.join(3)\n print(threading.active_count())\n\n time.sleep(20)\n\n clock_is_work = False\n\n time.sleep(1)\n\n print(threading.active_count())\n\n\n","repo_name":"casin-dir/cellnet","sub_path":"src/threads.py","file_name":"threads.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"2766527206","text":"#!/usr/bin/python\n# Create our Ingress and Egress rule chains\n\nfrom MaltegoTransform import *\nimport boto.ec2\nimport sys\nfrom init import load_credentials\n\ncreds = load_credentials()\nREGION = creds[2]\n\nm = MaltegoTransform()\nm.parseArguments(sys.argv)\nsec_group = m.getVar(\"GroupID\")\n\ntry:\n conn = boto.ec2.connect_to_region(REGION, aws_access_key_id=creds[0], aws_secret_access_key=creds[1])\n\n reservations = conn.get_all_instances()\n for i in reservations:\n group_nums = len(i.instances[0].groups)\n for z in range(group_nums):\n group_id = i.instances[0].groups[z].id\n sg_name = conn.get_all_security_groups(group_ids=group_id)[0]\n if str(group_id) == str(sec_group):\n ingress= m.addEntity(\"matterasmus.AmazonEC2IngressRules\", \"Ingress Rules\")\n ingress.addAdditionalFields(\"GroupID\", \"Group ID\", \"strict\", str(group_id))\n ingress.addAdditionalFields(\"SecurityGroup\", \"Group Name\", \"strict\", str(sg_name).split(\":\")[1])\n egress = m.addEntity(\"matterasmus.AmazonEC2EgressRules\", \"Egress Rules\")\n egress.addAdditionalFields(\"GroupID\", \"Group ID\", \"strict\", str(group_id))\n egress.addAdditionalFields(\"SecurityGroup\", \"Group Name\", \"strict\", str(sg_name).split(\":\")[1])\n\n m.addUIMessage(\"Completed.\")\n\nexcept Exception as e:\n m.addUIMessage(str(e))\n\nm.returnOutput()\n","repo_name":"znb/Elastic-Elephant","sub_path":"Transforms/GetSecurityGroupRules.py","file_name":"GetSecurityGroupRules.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"77"}
+{"seq_id":"29327129909","text":"#Aprobación de créditosing=float(input(\"Ingresos en pesos: \"))\nsoltero=\"S\"\ncasado=\"C\"\nurbano=\"U\"\nrural=\"R\"\n\ning=int(input(\"Ingresos en pesos: \"))\na_nac=int(input(\"Ano de Nacimiento: \"))\nnum_h=int(input(\"Numero de hijos: \"))\nanos_banc=int(input(\"Anos perteneciendo al banco: \"))\nest_civl=input(\"Estado Civil, (S,'Soltero' / C, 'Casado': \")\nhog=input(\"Lugar donde vive: 'U', Urbano / 'R', Rural: \")\n\nif anos_banc>10 and num_h>=2:\n print(\"APROBADO\")\n\nelif est_civl==casado and num_h>3 and a_nac>=1962 and a_nac<=1972 :\n print(\"APROBADO\")\n\nelif ing>2500000 and est_civl==soltero and hog==urbano :\n print(\"APROBADO\")\n\nelif ing>3500000 and anos_banc>5:\n print(\"APROBADO\")\n\nelif hog==rural and est_civl==casado and num_h<2 :\n print(\"APROBADO\")\nelse:\n print(\"RECHAZADO\")\n","repo_name":"pabloschwarzenberg/grader","sub_path":"hito1_ej3/hito1_ej3_3ee047b6120c5a4e765e9e2f8d498421.py","file_name":"hito1_ej3_3ee047b6120c5a4e765e9e2f8d498421.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"39256317981","text":"# This Python file uses the following encoding: utf-8\nimport logging\nimport threading\nimport select\nfrom ..command_dispatcher import Event\nfrom mopidy_rstation.config.settings import Config\nimport tempfile\n\nlogger = logging.getLogger('mopidy_Rstation')\nLIRC_PROG_NAME = \"mopidyRstation\"\nurl = u'rstation:' + Config.get_config()['media_dir']\n\n\nclass LircThread(threading.Thread):\n def __init__(self, config):\n try:\n import pylirc\n except Exception:\n logger.error('No pylirc!!!')\n threading.Thread.__init__(self)\n self.name = 'Lirc worker thread'\n self.frontendActive = True\n self.configFile = self.generateLircConfigFile(config)\n logger.debug('lircrc file:{0}'.format(self.configFile))\n self.ButtonPressed = Event()\n\n def run(self):\n try:\n self.run_inside_try()\n except Exception as e:\n logger.warning('Rstation has problems starting pylirc: ' + str(e))\n\n def run_inside_try(self):\n self.startPyLirc()\n\n def startPyLirc(self):\n logger.debug('Rstation start pylirc')\n lircHandle = pylirc.init(LIRC_PROG_NAME, self.configFile, 0)\n if(lircHandle != 0):\n while(self.frontendActive):\n self.consumePylirc(lircHandle)\n pylirc.exit()\n\n def consumePylirc(self, lircHandle):\n try:\n if(select.select([lircHandle], [], [], 1) == ([], [], [])):\n pass\n else:\n s = pylirc.nextcode(1)\n self.handleNextCode(s)\n except Exception as e:\n logger.warning('Exception during handling a command: ' + str(e))\n\n def handleNextCode(self, s):\n if s:\n self.handleLircCode(s)\n\n def handleLircCode(self, s):\n for code in s:\n self.handleCommand(code['config'])\n\n def handleCommand(self, cmd):\n self.ButtonPressed(cmd)\n\n def generateLircConfigFile(self, config):\n '''Returns file name of generate config file for pylirc'''\n f = tempfile.NamedTemporaryFile(delete=False)\n skeleton = 'begin\\n prog={2}\\n button={0}\\n config={1}\\nend\\n'\n for action in config:\n entry = skeleton.format(config[action], action, LIRC_PROG_NAME)\n f.write(entry)\n f.close()\n return f.name\n","repo_name":"sgrzys/mopidy-rstation","sub_path":"mopidy_rstation/input/irda/irda.py","file_name":"irda.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"9214979017","text":"from json_excel_converter.csv import Writer\nfrom json_excel_converter.linearize import Value\n\n\ndef test_writer():\n w = Writer()\n w.start()\n w.write_header([\n Value('a', 1),\n Value('b', 2),\n Value('c', 1)\n ])\n w.write_header([\n Value(None, 1),\n Value('b1', 1),\n Value('b2', 1),\n Value(None, 1)\n ])\n w.write_row([Value(1), Value(2), Value(3), Value(4)], data=None)\n w.write_row([Value('1'), Value('2'), Value('3'), Value('4')], data=None)\n w.finish()\n assert w.file.getvalue() == (\n 'a,b,,c\\r\\n' +\n ',b1,b2,\\r\\n' +\n '1,2,3,4\\r\\n' +\n '1,2,3,4\\r\\n'\n )\n","repo_name":"oarepo/json-excel-converter","sub_path":"tests/test_csv_writer.py","file_name":"test_csv_writer.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"77"}
+{"seq_id":"15923860585","text":"# =========================================================================\n# Filename: hist_aqua.py\n# Histograms Equalization \n# Name: Tran Minh Chien - ID: 1870324\n# Subject: Computer Vision and Control - Exercise 2\n# Date: 2019.09.03\n# =========================================================================\n\nimport cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\ndef main():\n # Load the image\n img = cv2.imread('D:/sample.jpg')\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n cv2.imshow('gray',gray)\n\n kernel = np.ones((1,1),np.uint8)\n # # filter2D\n # filter2D = cv2.filter2D(gray,cv2.CV_32F,kernel)\n # cv2.imshow('filter2D',filter2D)\n\n # guassian blur\n guassian = cv2.GaussianBlur(gray,(5,5),cv2.BORDER_DEFAULT)\n cv2.imshow('guassian',guassian)\n\n # medianBlur\n median = cv2.medianBlur(gray, 13)\n cv2.imshow('median',median)\n\n kernel = np.ones((5,5),np.uint8)\n # Erosion\n erosion = cv2.erode(gray,kernel,iterations = 1)\n cv2.imshow('erosion',erosion)\n\n # Dilation\n dilation = cv2.dilate(gray,kernel,iterations = 1)\n cv2.imshow('dilation',dilation)\n\n # Opening\n opening = cv2.morphologyEx(gray, cv2.MORPH_OPEN, kernel)\n cv2.imshow('opening',opening)\n\n # Closing\n closing = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, kernel)\n cv2.imshow('closing',closing)\n\n # Morphological Gradient\n gradient = cv2.morphologyEx(gray, cv2.MORPH_GRADIENT, kernel)\n cv2.imshow('gradient',gradient)\n\nif __name__ == '__main__':\n main()\n cv2.waitKey(0)\n\n\n","repo_name":"mchienbk/computer-vision-control","sub_path":"ex3-filter/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"44164876645","text":"from google.appengine.ext import webapp\nfrom google.appengine.ext import db\n\nfrom models import MP, MPVote\nimport utils\n\n\n\nclass MPVoteListHandler(webapp.RequestHandler, utils.QueryFilter, utils.JsonAPIResponse):\n\tdef get(self, slug):\n\n\t\tresponse = {}\n\t\ttry:\n\t\t\tmp = MP.all().filter('slug =', slug)[0]\n\t\t\tresponse['mp'] = utils.mp_to_dict(mp)\n\t\texcept:\n\t\t\tself.returnJSON(404, response)\n\t\t\treturn\n\n\t\tself.query = MPVote.all().filter('mp_slug =', slug)\n\t\tself.filterQueryOnParam('question')\n\t\tself.filterQueryOnParam('selection')\n\n\t\tresponse['votes'] = []\n\t\tfor vote in self.query:\n\t\t\td = db.to_dict(vote)\n\t\t\td['question'] = utils.question_to_dict(vote.parent())\n\t\t\tdel d['mp_party']\n\t\t\tdel d['mp_constituency']\n\t\t\tdel d['mp_slug']\n\t\t\tdel d['mp_name']\n\t\t\tresponse['votes'].append(d)\n\t\tresponse['total'] = len(response['votes'])\n\n\t\tself.returnJSON(200, response)","repo_name":"ahume/politmus-api","sub_path":"app/views/mpvotes.py","file_name":"mpvotes.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"17808867209","text":"import numpy as np\nimport plotly as py\nimport plotly.graph_objects as go\nimport plotly.express as px\nimport plotly.io as pio\nfrom plotly.subplots import make_subplots\nimport scipy as sp\n\n__all__ = [\n 'plotly_recognition_performance', 'plotly_quality_performance', \n 'plotly_det_scatter', 'plotly_set_det_plot'\n]\n\ndef plotly_det_scatter(fmr, fnmr,name=\"DET\"):\n hovertext=[f\"FMR: {x*100:.3f}% FNMR: {y*100:.3f}%\" for (x, y) in zip(fmr, fnmr)]\n return go.Scatter(\n name=name, \n x = sp.stats.norm.ppf(fmr),\n y = sp.stats.norm.ppf(fnmr),\n hovertext=hovertext,\n hoverinfo=\"text\"\n )\n\ndef plotly_set_det_plot(fig, row=None, col=None):\n ticks = [0.001, 0.004,0.01, 0.023, 0.05, 0.1, 0.20, 0.5, 0.80, 0.95, 0.99, 0.999]\n tick_vals = sp.stats.norm.ppf(ticks)\n tick_labels = [\n \"{:.0%}\".format(s) if (100 * s).is_integer() else \"{:.1%}\".format(s)\n for s in ticks\n ]\n if row != None and col != None:\n fig.update_xaxes(\n tickmode = 'array',\n tickvals = tick_vals,\n ticktext = tick_labels,\n row=row, col=col\n )\n fig.update_yaxes(\n tickmode = 'array',\n tickvals = tick_vals,\n ticktext = tick_labels,\n row=row, col=col\n )\n else:\n fig.update_xaxes(\n tickmode = 'array',\n tickvals = tick_vals,\n ticktext = tick_labels,\n )\n fig.update_yaxes(\n tickmode = 'array',\n tickvals = tick_vals,\n ticktext = tick_labels\n )\n\n\ndef plotly_recognition_performance(fmr, fnmr, treashold, y_true, y_score):\n fig = py.subplots.make_subplots(rows=1, cols=3)\n hovertext=[f\"FMR: {x:.3f} FNMR: {y:.3f}\" for (x, y) in zip(fmr, fnmr)]\n fig.add_trace(plotly_det_scatter(fmr, fnmr, name=\"DET\"), row=1, col=1)\n plotly_set_det_plot(fig, row=1, col=1)\n fig.add_trace(go.Histogram(name=f\"Genuine\", x=y_score[y_true == 1], histnorm='probability',opacity=0.5,nbinsx=20), row=1, col=2)\n fig.add_trace(go.Histogram(name=f\"Impostor\", x=y_score[y_true == 0], histnorm='probability',opacity=0.5,nbinsx=20), row=1, col=2)\n fig.update_layout(barmode='overlay')\n fig.add_trace(go.Scatter(name=f\"FMR\", y=fmr, x=treashold), row=1, col=3)\n fig.add_trace(go.Scatter(name=f\"FNMR\", y=fnmr, x=treashold), row=1, col=3)\n return fig\n\ndef plotly_quality_performance(irr, fnmr, dets):\n irr=np.array(irr)\n fnmr=np.array(fnmr)\n fig = py.subplots.make_subplots(rows=1, cols=2)\n for d in dets:\n fig.add_trace(plotly_det_scatter(dets[d][0], dets[d][1],\n name=f\"Rejection rate {d:.0%}\"\n ), row=1, col=2)\n plotly_set_det_plot(fig, row=1, col=2)\n fig.add_trace(go.Scatter(\n name=f\"False match rate {0.01:.0%}\",\n x=irr*100, y=fnmr*100, hovertemplate=\"IRR: %{x:0.3f}% FNMR: %{y:0.3f}%\"),row=1, col=1)\n\n return fig","repo_name":"nosebastian/DP","sub_path":"lightning/plots/plotly_plots.py","file_name":"plotly_plots.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"20476787755","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('booking/', views.booking, name='booking'),\n path('about us', views.index2, name='index2'),\n path('contact us', views.contact_us, name='contact_us'),\n path('Presidental', views.Presidental, name='Presidental'),\n\n path('register/', views.register, name='register'),\n path('sign_in/', views.sing_in, name='sign_in'),\n path('login/', views.loginuser, name='loginuser'),\n path('signup/',views.signupuser,name = 'signupuser'),\n\n path('current/',views.currenttodo,name = 'currenttodo'),\n path('completed/', views.completedtodos, name='completedtodos'),\n path('create/', views.createtodo, name='createtodo'),\n path('todo/', views.viewtodo, name='viewtodo'),\n path('todo//complete', views.completetodo, name='completetodo'),\n path('todo//delete', views.deletetodo, name='deletetodo')\n]","repo_name":"KamalovDias/DjPROj","sub_path":"djangoProject1/main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"19042388298","text":"import asyncio\nimport re\nimport logging\nfrom typing import Union\n\nfrom enum import Enum\nfrom datetime import datetime, timedelta\nfrom dateutil import tz\nfrom bson import ObjectId\n\nimport copy\nfrom pytz import common_timezones as pytz_common_timezones, country_timezones\n\nimport discord\nfrom discord.ext import commands, tasks\n\nfrom util.consts import Consts\nfrom lib.Connector import Connector\nfrom lib.Reminder import Reminder, IntervalReminder\nfrom lib.CommunitySettings import CommunitySettings, CommunityAction\nimport lib.input_parser\nimport lib.permissions\nimport lib.ReminderRepeater\nimport util.interaction\nimport util.reminderInteraction\n\nfrom lib.Analytics import Analytics, Types\n\n\nlog = logging.getLogger('Remindme.Creation')\n\n\nclass NewReminderView(util.interaction.CustomView):\n def __init__(self, reminder: Reminder, stm: util.reminderInteraction.STM, info_str: str, rrule_override, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.reminder = reminder\n self.stm = stm\n self.info_str = info_str\n self.rrule_override = rrule_override\n\n if isinstance(self.reminder, IntervalReminder):\n self.edit_interval.label='Edit Interval'\n\n def get_embed(self) -> discord.Embed:\n return self.reminder.get_tiny_embed(info=self.info_str, rrule_override=self.rrule_override)\n\n\n @discord.ui.button(label='Set Interval', emoji='🔁', style=discord.ButtonStyle.primary)\n async def edit_interval(self, button: discord.ui.Button, interaction: discord.Interaction):\n \n view = util.reminderInteraction.ReminderIntervalAddView(self.reminder, self.stm, self.message)\n await interaction.response.edit_message(embed=view.get_embed(), view=view)\n await view.wait()\n\n self.message = view.message # could've migrated\n self.reminder = view.reminder # could be an interval with different id now\n\n # re-send this button menu\n if isinstance(self.message, discord.WebhookMessage):\n func = self.message.edit\n else:\n func = self.message.edit_original_message\n\n await func(embed=self.get_embed(), view=self)\n\n\n @discord.ui.button(label='Edit', emoji='🛠️', style=discord.ButtonStyle.secondary)\n async def edit_reminder(self, button: discord.ui.Button, interaction: discord.Interaction):\n\n modal = util.reminderInteraction.EditModal(reminder=self.reminder, \n custom_callback=None,\n tz_str=self.stm.tz_str,\n title='Edit the Reminder')\n await interaction.response.send_modal(modal)\n await modal.wait()\n\n # update reminder (or interval)\n if isinstance(self.reminder, IntervalReminder):\n self.reminder = Connector.get_interval_by_id(self.reminder._id)\n else:\n self.reminder = Connector.get_reminder_by_id(self.reminder._id)\n\n # re-send this button menu\n if isinstance(self.message, discord.WebhookMessage):\n func = self.message.edit\n else:\n func = self.message.edit_original_message\n\n await func(embed=self.get_embed(), view=self)\n\n\n\n @discord.ui.button(emoji='🗑️', style=discord.ButtonStyle.danger)\n async def del_reminder(self, button: discord.ui.Button, interaction: discord.Interaction):\n eb_title = None\n if Connector.delete_reminder(self.reminder._id):\n eb_title = 'Deleted the reminder'\n color = Consts.col_warn\n Analytics.reminder_deleted(Types.DeleteAction.DIRECT_BTN) \n elif Connector.delete_interval(self.reminder._id):\n eb_title = 'Deleted the reminder'\n color = Consts.col_warn\n Analytics.interval_deleted(Types.DeleteAction.DIRECT_BTN) \n else:\n eb_title = 'Failed to delete reminder due to an unknown issue'\n color = Consts.col_crit\n log.error(f'Couldn\\'t direct-delete a reminder of type {type(self.reminder)}. Both delete queries didn\\'t suceed.')\n\n\n eb = discord.Embed(title=eb_title, color=color)\n self.disable_all()\n self.del_reminder.style = discord.ButtonStyle.danger # keep this btn red\n await interaction.response.edit_message(embed=eb, view=self)\n self.stop()\n\n\n\nclass ReminderCreation(commands.Cog):\n\n REMIND_FORMAT_HELP = \\\n 'basic example:\\n'\\\n '> /remindme `time: 2d` `message: Hello World`\\n'\\\n '\\n'\\\n 'remind other users and roles\\n'\\\n '> /remind `target: @Role` `time: 24 dec` `message: Merry Christmas`\\n'\\\n '\\n'\\\n 'create repeating reminders\\n'\\\n '> /remindme `time: every friday at 20:15` `message: do stuff`\\n'\\\n '\\n'\\\n 'try different formats\\n'\\\n '```'\\\n '• 5 jul, 5th july, july 5\\n'\\\n '• 23 aug at 3pm, 23 aug at 15\\n'\\\n '• every other week\\n'\\\n '\\n'\\\n '```'\\\n '\\n'\\\n 'Call `/help page: syntax` for more detailed information.\\n'\n \n HELP_FOOTER = 'If you find a bug in the parser, please reach out to us.\\n'\\\n 'You can contact us on Github or join the support server.'\n\n\n @staticmethod\n def to_int(num_str: str, base: int=10):\n \n try:\n conv_int = int(num_str, base)\n except ValueError:\n conv_int = None\n finally:\n return conv_int\n\n\n # =====================\n # internal functions\n # =====================\n\n\n def __init__(self, client):\n self.client = client\n \n self.timezone_country = {}\n for countrycode in country_timezones:\n timezones = country_timezones[countrycode]\n for timezone in timezones:\n self.timezone_country[timezone] = countrycode\n\n\n async def process_reminder(self, ctx: discord.ApplicationContext, author: Union[discord.User, discord.Member], target, period, message, channel):\n\n if ctx.guild:\n instance_id = ctx.guild.id\n # try and get the last message, for providing a jump link\n try:\n last_msg = await ctx.channel.history(limit=1).flatten()\n except:\n last_msg = None\n last_msg = last_msg[0] if last_msg else None\n else:\n instance_id = author.id\n last_msg = None\n\n \n \n\n tz_str = Connector.get_timezone(instance_id)\n auto_del_action = Connector.get_auto_delete(instance_id)\n is_legacy = Connector.is_legacy_interval(instance_id)\n\n utcnow = datetime.utcnow()\n remind_at, info = lib.input_parser.parse(period, utcnow, tz_str)\n rrule = None\n\n if isinstance(remind_at, datetime):\n interval = (remind_at - utcnow)\n if remind_at is None or interval <= timedelta(hours=0):\n if info != '':\n out_str = f'```Parsing hints:\\n{info}```\\n'\n else:\n out_str = ''\n\n if interval == timedelta(hours=0):\n # only append full help on invalid strings\n # not on negative intervals\n out_str += ReminderCreation.REMIND_FORMAT_HELP\n elif interval < timedelta(hours=0):\n out_str += 'Make sure your server is using the correct timezone `/settings timezone`'\n\n embed = discord.Embed(title='Failed to create the reminder', color=0xff0000, description=out_str)\n embed.set_footer(text=ReminderCreation.HELP_FOOTER)\n await ctx.respond(embed=embed, ephemeral=True)\n\n if interval == timedelta(hours=0):\n Analytics.reminder_creation_failed(Types.CreationFailed.INVALID_F_STR)\n else:\n Analytics.reminder_creation_failed(Types.CreationFailed.PAST_DATE)\n return # error exit\n\n elif remind_at is None:\n if info != '':\n out_str = f'```Parsing hints:\\n{info}```\\n'\n else:\n out_str = ''\n out_str += ReminderCreation.REMIND_FORMAT_HELP\n\n embed = discord.Embed(title='Failed to create the reminder', color=0xff0000, description=out_str)\n embed.set_footer(text=ReminderCreation.HELP_FOOTER)\n await ctx.respond(embed=embed, ephemeral=True)\n Analytics.reminder_creation_failed(Types.CreationFailed.INVALID_F_STR) \n return \n\n elif isinstance(remind_at, str):\n\n if is_legacy:\n dtstart = utcnow\n else:\n dtstart = utcnow.replace(tzinfo=tz.UTC).astimezone(tz.gettz(tz_str)).replace(tzinfo=None)\n\n rrule, info = lib.input_parser.rrule_normalize(remind_at, dtstart=dtstart, instance_id=instance_id)\n if not rrule:\n if info != '':\n out_str = f'```Parsing hints:\\n{info}```\\n'\n else:\n # only show general help, if normalizing doesn't give\n # specific error\n out_str = ReminderCreation.REMIND_FORMAT_HELP\n\n embed = discord.Embed(title='Failed to create the reminder', color=0xff0000, description=out_str)\n embed.set_footer(text=ReminderCreation.HELP_FOOTER)\n await ctx.respond(embed=embed, ephemeral=True)\n Analytics.reminder_creation_failed(Types.CreationFailed.INVALID_F_STR) \n return\n \n elif not lib.permissions.check_user_permission(ctx.guild.id, ctx.author.roles, required_perms=CommunityAction(repeating=True)):\n # make sure the user is allowed to create repeating reminders\n return\n\n if auto_del_action == Connector.AutoDelete.HIDE:\n defer_hidden=True\n else:\n defer_hidden=False\n await ctx.defer(ephemeral=defer_hidden) # allow more headroom for response latency, before command fails\n rem = Reminder()\n\n\n info = '' if not info else info\n if channel is None:\n # command was called in DM\n rem.g_id = None\n rem.ch_id = None\n rem.ch_name = 'DM'\n else:\n if isinstance(channel, discord.channel.PartialMessageable):\n # channel not fully loaded (due to sharding or permissions)\n try:\n res_channel = await self.client.fetch_channel(channel.id)\n channel = res_channel\n rem.ch_name = channel.name[0:25] # only keep first 25 letters \n except discord.errors.Forbidden:\n rem.ch_name = '*Unresolved Channel*'\n info += f'\\n• Failed to resolve the target channel. The reminder *might* not be delivered due to missing permissions.' \n else:\n # channel name by attribute\n rem.ch_name = channel.name[0:25] # only keep first 25 letters\n \n # independant of channel itself\n rem.g_id = ctx.guild.id\n rem.ch_id = channel.id\n\n if rem.ch_id != ctx.channel_id:\n info += f'\\n• This reminder will be delivered to `{rem.ch_name}`.\\nMake sure this bot has permission to send messages into that channel'\n\n\n rem.msg = message\n rem.at = remind_at\n rem.author = author.id\n\n rem.created_at = utcnow\n rem.last_msg_id = last_msg.id if last_msg else None\n\n\n if isinstance(target, int):\n # use user-mention (no &) as fallback\n # as it's more likely to not resolve a user\n rem.target = target\n rem.target_name = f'<@{target}>'\n rem.target_mention = f'<@{target}>'\n print('failed to resolve mentionable')\n elif isinstance(target, discord.member.Member):\n rem.target = target.id\n rem.target_name = target.mention\n rem.target_mention = target.mention\n else:\n rem.target = target.id\n rem.target_name = target.name\n # everyone requires a special case\n # as it cannot be mentioned by using the id\n if ctx.guild and ctx.guild.default_role == target:\n rem.target_mention = target.name # @everyone\n else:\n rem.target_mention = target.mention\n\n if rrule:\n old_rem = rem\n old_rem.at = dtstart\n rem = IntervalReminder(old_rem._to_json())\n rem.first_at = old_rem.at\n rem.rrules.append(str(rrule))\n\n rem.at = rem.next_trigger(utcnow, tz_str=tz_str)\n # do NOT save, if trigger creation faild\n # this should not be possible\n if rem.at:\n \n rem._id = Connector.add_interval(rem)\n Analytics.reminder_created(rem, country_code=self.timezone_country.get(tz_str, 'UNK'), direct_interval=True)\n else:\n # the id is required in case the users wishes to abort\n rem._id = Connector.add_reminder(rem)\n Analytics.reminder_created(rem, country_code=self.timezone_country.get(tz_str, 'UNK'))\n\n\n if auto_del_action == Connector.AutoDelete.TIMEOUT:\n delete_after = 300\n hidden=False\n elif auto_del_action == Connector.AutoDelete.NEVER:\n delete_after = None\n hidden=False\n else:\n delete_after = None\n hidden=True\n\n\n stm = util.reminderInteraction.STM(\n ctx,\n Connector.Scope(is_private=False, guild_id=ctx.guild.id if ctx.guild else None, user_id=ctx.author.id)\n )\n stm.tz_str = tz_str\n\n view = NewReminderView(rem, stm=stm, info_str=info, rrule_override=rrule, timeout=delete_after)\n tiny_embed = view.get_embed() \n\n msg = await ctx.respond(embed=tiny_embed, delete_after=delete_after, view=view, \n allowed_mentions=discord.AllowedMentions.none(), ephemeral=hidden)\n view.message = msg\n\n\n # =====================\n # events functions\n # =====================\n\n @discord.Cog.listener()\n async def on_ready(self):\n log.info('loaded')\n\n\n # =====================\n # commands functions\n # =====================\n # TODO: fix mentionable type, wait for lib fix\n @commands.slash_command(name='remind', description='set a reminder after a certain time period')\n async def remind_user(self, ctx:discord.ApplicationContext,\n target:discord.Option((discord.Member, discord.Role), 'the user or role you want to remind', required=True),\n time:discord.Option(str, 'time/date when the reminder is triggered (see syntax page on /help)', required=True),\n message:discord.Option(str, 'the bot will remind you with this message', required=True)):\n #channel:discord.Option((discord.TextChannel,discord.VoiceChannel), 'Show the reminder in a channel other than the current one', required=False)=None):\n\n channel=None\n if not target:\n # TODO: monitor if this ever gets hit\n target_resolve = await ctx.guild.fetch_member(int(target))\n log.critical('user not loaded, investigation required')\n 1/0\n\n # determining if the mention is @everyone depends\n # on how the role was resolved (and if it even is a role)\n if not ctx.guild:\n is_everyone = False\n elif isinstance(target, int):\n is_everyone = (ctx.guild.id == target)\n else:\n is_everyone = (ctx.guild.default_role == target)\n\n if ctx.guild:\n # only allow execution if all permissions are present \n action = CommunityAction(foreign=True, everyone=is_everyone)\n err_eb = lib.permissions.get_missing_permissions_embed(ctx.guild.id, ctx.author.roles, required_perms=action)\n if err_eb:\n await ctx.respond(embed=err_eb)\n return\n\n # update channel, when not specified (optional parameter)\n channel = channel or ctx.channel\n\n await self.process_reminder(ctx, ctx.author, target, time, message, channel=channel)\n \n\n @commands.slash_command(name='remindme', description='set a reminder after a certain time period')\n async def remindme(self, ctx:discord.ApplicationContext,\n time:discord.Option(str, 'time/date when the reminder is triggered (see syntax page on /help)', required=True),\n message:discord.Option(str, 'the bot will remind you with this message', required=True)):\n #channel:discord.Option((discord.TextChannel,discord.VoiceChannel), 'Show the reminder in a channel other than the current one', required=False)=None):\n channel = None\n if ctx.guild:\n # call will fail if community mode is enabled\n err_eb = lib.permissions.get_missing_permissions_embed(ctx.guild.id, ctx.author.roles)\n if err_eb:\n await ctx.respond(embed=err_eb)\n return\n channel = channel or ctx.channel # overwrite if not specified\n\n await self.process_reminder(ctx, ctx.author, ctx.author, time, message, channel=channel)\n \n\n\ndef setup(client):\n client.add_cog(ReminderCreation(client))\n","repo_name":"Mayerch1/RemindmeBot","sub_path":"Bot/cogs/ReminderCreation.py","file_name":"ReminderCreation.py","file_ext":"py","file_size_in_byte":17688,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"77"}
+{"seq_id":"29344219479","text":"#Cálculo del dígito verificador de un rut\nrut = input()\nserie = True\ndigito = len(rut)\ncalculo = 0\n\nwhile serie:\n for i in range(2, 8):\n if digito != 0:\n calculo += int(rut[digito-1])*i\n digito -= 1\n\n else:\n serie = False\n \n \n\ncalculo2 = 11 - calculo%11\n\nif calculo2 == 10:\n dv = \"k\"\n \nelif calculo2 == 11:\n dv = 0\n \nelse:\n dv = calculo2\n \nprint(\"dv=\", dv)","repo_name":"pabloschwarzenberg/grader","sub_path":"hito1_ej5/hito1_ej5_841e75bac52d51bb81087b16405d3403.py","file_name":"hito1_ej5_841e75bac52d51bb81087b16405d3403.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"11498673396","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom functools import partial\nimport numpy.random as npr\n\n\ndef file_to_str(filepath):\n with open(filepath, \"r\") as myfile:\n data = myfile.read()\n return data\n\n\ndef truncate_sample(distribution, thr=0, s='lower'):\n if s == 'lower':\n def f(size=1000):\n X = distribution(size=size)\n X[X<=thr] = X[X>thr].min()\n return X\n elif s == 'upper':\n def f(size=1000):\n X = distribution(size=size)\n X[X>=thr] = X[X1:\n if sys.argv[1] in ['--help', '-h']:\n print(\"Pass path to a file with model as argument. See example file.\")\n else:\n exec(file_to_str(sys.argv[1]))\n mcgwrapper(model)\n","repo_name":"iprokin/mcguesstimate","sub_path":"gst.py","file_name":"gst.py","file_ext":"py","file_size_in_byte":3527,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"2369423979","text":"\"\"\"\n下面的文件将会从csv文件中读取读取短信与电话记录,\n你将在以后的课程中了解更多有关读取文件的知识。\n\"\"\"\nimport csv\nimport re\n\nwith open('texts.csv', 'r') as f:\n reader = csv.reader(f)\n texts = list(reader)\n\nwith open('calls.csv', 'r') as f:\n reader = csv.reader(f)\n calls = list(reader)\n\n\"\"\"\n任务4:\n电话公司希望辨认出可能正在用于进行电话推销的电话号码。\n找出所有可能的电话推销员:\n这样的电话总是向其他人拨出电话,\n但从来不发短信、接收短信或是收到来电\n\n\n请输出如下内容\n\"These numbers could be telemarketers: \"\n\n电话号码不能重复,每行打印一条,按字典顺序排序后输出。\n\"\"\"\n\ndef getSalesPhone(calllist, textlist):\n '''\n Get all sales number\n '''\n\n call_out_list = []\n except_list = []\n result_list = []\n for callline in calllist:\n call_out_list.append(callline[0])\n except_list.append(callline[1])\n\n for textline in textlist:\n except_list.append(textline[0])\n except_list.append(textline[1])\n\n for call_num in call_out_list:\n if call_num not in except_list:\n result_list.append(call_num)\n\n return result_list\n\nif __name__ == '__main__':\n '''\n Run Part\n '''\n\n result_list = list(set(getSalesPhone(calls, texts)))\n result_list.sort()\n print('These numbers could be telemarketers:')\n for result in result_list:\n print(result)\n","repo_name":"kylechenoO/investigate-texts-and-calls","sub_path":"Task4.py","file_name":"Task4.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"69858338488","text":"import inspect\nimport logging\n\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\n\nlogger = logging.getLogger(__name__)\n\n\ndef command(*, name: str = None, cls=None, **attrs):\n \"\"\"Decorator that turns a coroutine into a Command.\n \"\"\"\n\n if cls and not inspect.isclass(cls):\n raise TypeError(f'cls must be of type not <{type(cls)}>')\n\n cls = cls or DefaultCommand\n\n def decorator(func):\n fname = name or func.__name__\n command = cls(name=fname, func=func, **attrs)\n\n return command\n return decorator\n\n\nclass DefaultCommand(commands.Command):\n def __init__(self, name: str, func=None, text: str = None, **attrs):\n if func is None:\n assert (text is not None)\n self._func = self.cmd_textcommand\n else:\n self._func = func\n\n super().__init__(self._func, name=name, **attrs)\n\n self.text = text\n if self.text is not None:\n assert (func is None)\n\n async def cmd_textcommand(self, ctx: Context):\n await ctx.send(self.text)\n\n def serialize(self) -> dict:\n\n if self.text is None:\n func = self._func\n else:\n func = None\n\n return {\n 'cls': self.__class__,\n 'name': self.name,\n 'aliases': self.aliases,\n 'func': func,\n 'text': self.text,\n }\n","repo_name":"keelimeguy/keelimebot","sub_path":"keelimebot/discord/commands/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"26845849697","text":"import cupy as cp\nfrom CATCH.training.YOLO_data_generator import makedata\nfrom CATCH.Localizer import Localizer\nfrom CATCH.utilities.mtd import feature_extent\nfrom pylorenzmie.theory import Sphere\nimport json, os, cv2, ast\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib.patches import Rectangle\n\ndef localizer_accuracy(configuration='yolov5_test', nframes=None, version=None, plot=False, savedir='./results/', overwrite=False):\n basedir = os.path.dirname(os.path.abspath(__file__)).split('eval')[0]\n path = basedir + 'cfg_yolov5/{}.json'.format(configuration)\n\n with open(path, 'r') as f:\n config = json.load(f)\n \n file_header = os.path.abspath(config['directory'])\n eval_dir = file_header + '/eval'\n \n mtd_config = config.copy()\n mtd_config['directory'] = eval_dir\n if not nframes:\n nframes = config['nframes_eval']\n \n mtd_config['nframes'] = nframes\n mtd_config['particle']['nspheres'] = [1,1]\n mtd_config['overwrite'] = overwrite\n print('making data')\n makedata(config = mtd_config)\n print('data made')\n \n localizer = Localizer(configuration=configuration, version=version)\n\n imgpath_fmt = config['directory']+'/eval/images/image{}.png'\n parampath_fmt = config['directory']+'/eval/params/image{}.json'\n\n df = pd.DataFrame(columns = ['img_num', 'x_true', 'y_true', 'ext_true', 'num_detections', 'x_pred', 'y_pred', 'ext_pred', 'conf'])\n style = dict(fill=False, linewidth=3, edgecolor='r')\n for n in range(nframes):\n print('frame {}'.format(n), end='\\r')\n img = cv2.imread(imgpath_fmt.format(str(n).zfill(5)))\n with open(parampath_fmt.format(str(n).zfill(5)), 'r') as f:\n params = json.load(f)[0]\n sphere = Sphere()\n sphere.loads(params)\n params = ast.literal_eval(params)\n ext = 2. * feature_extent(sphere, mtd_config)\n\n results = localizer.detect([img])[0]\n\n if plot:\n fig, ax = plt.subplots()\n ax.imshow(img, cmap='gray')\n for feature in results:\n corner, w, h = feature['bbox']\n ax.add_patch(Rectangle(xy=corner, width=w, height=h, **style))\n plt.show()\n \n resultsdict = {'img_num':n, 'x_true':params['x_p'], 'y_true':params['y_p'], 'ext_true':ext, 'num_detections':len(results), 'x_pred':None, 'y_pred':None, 'ext_pred':None, 'conf':None}\n\n if len(results) == 1 and not results[0]['edge']:\n r = results[0]\n p_ext = max(r['bbox'][1:])\n resultsdict['x_pred'] = r['x_p']\n resultsdict['y_pred'] = r['y_p']\n resultsdict['conf'] = r['conf']\n resultsdict['ext_pred'] = p_ext\n \n df = df.append(resultsdict, ignore_index=True)\n\n print(df)\n\n saveheader = savedir + configuration\n if version:\n saveheader += '_v{}'.format(version)\n savepath = saveheader + '_eval.csv'\n df.to_csv(savepath)\n\n truepos = df[df.num_detections==1]\n falseneg = df[df.num_detections==0]\n falsepos = df[df.num_detections>1]\n numfalsepos = int(falsepos.num_detections.sum() - len(falsepos))\n numtruepos = len(truepos) + len(falsepos)\n numfalseneg = len(falseneg)\n\n print('{} true positive detections, {} false positive (additional) detections, {} false negative detections'.format(numtruepos, numfalsepos, numfalseneg))\n\n inplane_err_sq = (truepos.x_true - truepos.x_pred)**2 + (truepos.y_true - truepos.y_pred)**2\n inplane_RMSE = np.sqrt(inplane_err_sq.sum()/len(inplane_err_sq))\n inplane_err = np.sqrt(inplane_err_sq)\n\n fig, ax = plt.subplots()\n loc = ax.scatter(truepos.x_true, truepos.y_true, c=np.log(inplane_err), cmap='Spectral')\n ax.set_xlabel(r'$x_p$ [px]')\n ax.set_xlabel(r'$y_p$ [px]')\n ax.grid(alpha=0.3)\n fig.colorbar(loc, label='log(In-plane error [px])')\n ax.annotate('In-plane RMSE: {}px'.format('%.1f'%inplane_RMSE), xy=(0.05, 0.95), xycoords='axes fraction', bbox=dict(facecolor='white', edgecolor='black',alpha=0.5))\n fig.tight_layout()\n fig.savefig(saveheader + '_inplane_err.png')\n plt.show()\n \n ext_err_sq = (truepos.ext_true - truepos.ext_pred)**2\n ext_RMSE = np.sqrt(ext_err_sq.sum()/len(ext_err_sq))\n ext_percent = np.sqrt(ext_err_sq)/truepos.ext_true\n print(ext_percent)\n ext_perror = ext_percent.mean()*100\n\n fig, ax = plt.subplots()\n ax.plot(truepos.ext_true, truepos.ext_true, c='r')\n ax.scatter(truepos.ext_true, truepos.ext_pred, alpha=0.3, c='b')\n ax.annotate('{}% Extent Error'.format('%.1f'%ext_perror), xy=(0.05, 0.95), xycoords='axes fraction', bbox=dict(facecolor='white', edgecolor='black',alpha=0.5))\n ax.set_xlabel('True feature size [px]')\n ax.set_ylabel('Predicted bounding box size [px]')\n ax.grid(alpha=0.3)\n fig.tight_layout()\n fig.savefig(saveheader + '_ext_err.png')\n plt.show()\n \n \nif __name__ == '__main__':\n localizer_accuracy(configuration='small_noisy', nframes = 25000, savedir='./results/for_paper/', overwrite=True)\n #localizer_accuracy(version=2, nframes = 5000)\n","repo_name":"laltman2/CATCH","sub_path":"eval/localizer_eval.py","file_name":"localizer_eval.py","file_ext":"py","file_size_in_byte":5127,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"77"}
+{"seq_id":"22064600658","text":"# Определяем класс ProceduralLanguage для процедурных языков программирования\r\nclass ProceduralLanguage:\r\n def __init__(self, name, year, is_abstract_type_supported):\r\n self.name = name\r\n self.year = year\r\n self.is_abstract_type_supported = is_abstract_type_supported\r\n\r\n\r\n# Определяем класс InheritanceType для типов наследования\r\nclass InheritanceType:\r\n Single = \"Single\"\r\n Multiple = \"Multiple\"\r\n\r\n\r\n# Определяем класс ObjectOrientedLanguage для объектно-ориентированных языков программирования\r\nclass ObjectOrientedLanguage:\r\n def __init__(self, name, year, is_abstract_type_supported, inheritance_type, interfaces):\r\n self.name = name\r\n self.year = year\r\n self.is_abstract_type_supported = is_abstract_type_supported\r\n self.inheritance_type = inheritance_type\r\n self.interfaces = interfaces\r\n\r\n\r\n# Создаем объекты процедурных языков программирования\r\nc = ProceduralLanguage(\"C\", 1972, False)\r\npascal = ProceduralLanguage(\"Pascal\", 1970, True)\r\nfortran = ProceduralLanguage(\"FORTRAN\", 1957, False)\r\ncobol = ProceduralLanguage(\"COBOL\", 1959, False)\r\nbasic = ProceduralLanguage(\"BASIC\", 1964, True)\r\n\r\n# Создаем объекты объектно-ориентированных языков программирования\r\njava = ObjectOrientedLanguage(\"Java\", 1995, True, InheritanceType.Multiple, [\"Java SE\", \"Java EE\"])\r\ncpp = ObjectOrientedLanguage(\"C++\", 1983, True, InheritanceType.Multiple, [\"STL\", \"Boost\"])\r\npython = ObjectOrientedLanguage(\"Python\", 1991, True, InheritanceType.Multiple, [\"ABC\", \"DEF\"])\r\nruby = ObjectOrientedLanguage(\"Ruby\", 1995, True, InheritanceType.Single, [\"Ruby on Rails\"])\r\nswift = ObjectOrientedLanguage(\"Swift\", 2014, True, InheritanceType.Multiple, [\"UIKit\", \"Foundation\"])\r\n\r\n# Тестирование\r\nprint(c.name, c.year, c.is_abstract_type_supported)\r\nprint(java.name, java.year, java.is_abstract_type_supported, java.inheritance_type, java.interfaces)","repo_name":"AlexXPython/Tech_prog","sub_path":"oop.py","file_name":"oop.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"25138528101","text":"# Other implementations\n#\n# https://github.com/sagelywizard/pytorch-mdn\n#\nfrom enum import Enum, auto\n\nimport numpy as np\nimport torch\nimport torch.distributions as D\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom . import lin as nnx\nfrom stdlib import mul\n\n\n# ---------------------------------------------------------------------------\n# from keras-mdn-layer package\n# ---------------------------------------------------------------------------\n# https://github.com/cpmpercussion/keras-mdn-layer\n#\nEPS = 1e-6\n\n# Non Negative Exponential Linear Unit (nnelu)\ndef elu_plus_one_plus_epsilon(x):\n return F.elu(x) + 1 + EPS\n\n\ndef softmax(w, t=1.0):\n \"\"\"Softmax function for a list or numpy array of logits. Also adjusts temperature.\n\n Arguments:\n w -- a list or numpy array of logits\n\n Keyword arguments:\n t -- the temperature for to adjust the distribution (default 1.0)\n \"\"\"\n e = w / t # adjust temperature\n e -= e.max() # subtract max to protect from exploding exp values.\n e = np.exp(e)\n dist = e / np.sum(e)\n # e = w/t\n # e -= e.max()\n # e = torch.exp(e)\n # dist = e/e.sum()\n return dist\n\n\ndef sample_from_categorical(dist):\n \"\"\"Samples from a categorical model PDF.\n\n Arguments:\n dist -- the parameters of the categorical model\n\n Returns:\n One sample from the categorical model, or -1 if sampling fails.\n \"\"\"\n # r = torch.rand(1) # uniform random number in [0,1]\n # accumulate = torch.tensor(0., dtype=dist.dtype)\n # for i in range(0, len(dist)):\n # accumulate += dist[i]\n # if accumulate >= r:\n # return i\n # return -1\n n = len(dist)\n r = np.random.rand(1)\n accumulate = 0.\n for i in range(0, n):\n accumulate += dist[i]\n if accumulate >= r:\n return i\n return n-1\n\n\ndef split_mixture_params(mdn_params, output_size, n_mixtures):\n \"\"\"Splits up an array of mixture parameters into mus, sigmas, and pis\n depending on the number of mixtures and output dimension.\n\n Arguments:\n params -- the parameters of the mixture model\n output_dim -- the dimension of the normal models in the mixture model\n num_mixes -- the number of mixtures represented\n \"\"\"\n if len(mdn_params.shape) == 1:\n mus = mdn_params[:n_mixtures*output_size]\n sigmas = mdn_params[n_mixtures*output_size:2*n_mixtures*output_size]\n pi_logits = mdn_params[-n_mixtures:]\n else:\n mus = mdn_params[:, :n_mixtures * output_size]\n sigmas = mdn_params[:, n_mixtures*output_size:2*n_mixtures*output_size]\n pi_logits = mdn_params[:, -n_mixtures:]\n\n mus = mus.reshape((-1, n_mixtures, output_size))\n sigmas = sigmas.reshape((-1, n_mixtures, output_size))\n\n return mus, sigmas, pi_logits\n\n\ndef sample_from_output(params, output_size, n_mixtures, temp=1.0, sigma_temp=1.0):\n \"\"\"Sample from an MDN output with temperature adjustment.\n This calculation is done outside of the Keras model using\n Numpy.\n\n Arguments:\n params -- the parameters of the mixture model\n output_dim -- the dimension of the normal models in the mixture model\n num_mixes -- the number of mixtures represented\n\n Keyword arguments:\n temp -- the temperature for sampling between mixture components (default 1.0)\n sigma_temp -- the temperature for sampling from the normal distribution (default 1.0)\n\n Returns:\n One sample from the the mixture model.\n \"\"\"\n mus, sigmas, pi_logits = split_mixture_params(params, output_size, n_mixtures)\n pis = softmax(pi_logits, t=temp)\n m = sample_from_categorical(pis)\n # Alternative way to sample from categorical:\n # m = np.random.choice(range(len(pis)), p=pis)\n mus_vector = mus[m * output_size:(m + 1) * output_size]\n sig_vector = sigmas[m * output_size:(m + 1) * output_size]\n scale_matrix = np.diag(sig_vector) # scale matrix from diag\n cov_matrix = np.matmul(scale_matrix, scale_matrix.T) # cov is scale squared.\n cov_matrix = cov_matrix * sigma_temp # adjust for sigma temperature\n sample = np.random.multivariate_normal(np.array(mus_vector), np.array(cov_matrix), 1)\n return sample\n\n\n# def get_keras_mixture_loss_func(output_size, n_mixtures):\n# def mdn_loss_func(y_true, mdn_params):\n# # Reshape inputs in case this is used in a TimeDistributed layer\n# # UPDATE: instead to return a conactenated tensor, NOW it is returned just the tuple\n# y_true = y_true.reshape((-1, output_size))\n# mus, sigmas, pi = mdn_params\n#\n# cat = Categorical(logits=pi)\n#\n# component_splits = [output_size] * n_mixtures\n# mus = torch.tensor_split(mus, component_splits, dim=1)\n# sigmas = torch.tensor_split(sigmas, component_splits, dim=1)\n#\n# coll = [MultivariateNormal(loc=loc, scale_tril=scale) for loc, scale in zip(mus, sigmas)]\n# mixture = MixtureSameFamily(cat, coll)\n#\n# loss = mixture.log_prob(y_true)\n# loss = torch.negative(loss)\n# loss = torch.mean(loss)\n#\n# return loss\n#\n# return mdn_loss_func\n\n\nclass MixtureDensityNetwork(nn.Module):\n\n def __init__(self, in_features, out_features, n_mixtures,):\n super().__init__()\n\n self.in_features = in_features\n self.out_features = out_features\n self.n_mixtures = n_mixtures\n\n self.mus = nnx.Linear(in_features=in_features, out_features=(n_mixtures * out_features))\n self.sigmas = nnx.Linear(in_features=in_features, out_features=(n_mixtures * out_features))\n self.pi_logits = nn.Linear(in_features=in_features, out_features=n_mixtures)\n\n def forward(self, x):\n mus = self.mus(x)\n sigmas = elu_plus_one_plus_epsilon(self.sigmas(x))\n pi_logits = self.pi_logits(x)\n\n # mus [n_mixtures, output_size]\n # sigmas [n_mixtures, output_size]\n # pi [n_mixtures]\n\n return torch.cat([mus, sigmas, pi_logits], dim=1)\n\n\nclass MixtureDensityNetworkLoss(nn.Module):\n\n def __init__(self, out_features, n_mixtures):\n super().__init__()\n self.out_features = out_features\n self.n_mixtures = n_mixtures\n\n def forward(self, mdn_params, y_true):\n out_features = self.out_features\n n_mixtures = self.n_mixtures\n\n # mus [N, n_mixtures, output_size]\n # sigmas [N, n_mixtures, output_size]\n # pi [N, n_mixtures]\n\n # Reshape inputs in case this is used in a TimeDistributed layer\n # UPDATE: instead to return a concatenated tensor, NOW it is returned just the tuple\n batch = y_true.shape[0]\n y_true = y_true.reshape((batch, -1))\n mus, sigmas, pi_logits = split_mixture_params(mdn_params, out_features, n_mixtures)\n cat = D.Categorical(logits=pi_logits)\n total_loss = None\n\n for i in range(out_features):\n mu = mus[:, :, i]\n sigma = sigmas[:, :, i]\n norm = D.Normal(mu, sigma)\n mixture = D.MixtureSameFamily(cat, norm)\n loss = mixture.log_prob(y_true[:, i])\n loss = torch.negative(loss)\n\n if total_loss is None:\n total_loss = loss\n else:\n total_loss += loss\n\n return total_loss.mean()\n\n\nclass MixtureDensityNetworkPredictor:\n\n def __init__(self, model, out_features, n_mixtures, n_samples=1):\n self.model = model\n self.out_features = mul(out_features)\n self.n_mixtures = n_mixtures\n self.n_samples = n_samples\n\n def predict(self, x):\n n = len(x)\n pred_list = []\n for i in range(n):\n pred = self._predict(x[i:i+1])\n pred_list.append(pred)\n return np.concatenate(pred_list, axis=0)\n\n def _predict(self, x):\n output_size = self.out_features\n n_mixtures = self.n_mixtures\n pred_fscaled = self.model.predict(x)\n pred_dist = np.zeros((1, 1, self.out_features))\n for i in range(self.n_samples):\n y_samples = np.apply_along_axis(sample_from_output, 1, pred_fscaled, output_size, n_mixtures, temp=1.0)\n pred_dist += y_samples\n return pred_dist.mean(axis=0)\n\n\n# ---------------------------------------------------------------------------\n# https://eadains.github.io/OptionallyBayesHugo/posts/vol_mdn/\n#\n# Implementation\n#\n# https://github.com/tonyduan/mixture-density-network\n#\n#\n\nclass NoiseType(Enum):\n DIAGONAL = auto()\n ISOTROPIC = auto()\n ISOTROPIC_ACROSS_CLUSTERS = auto()\n FIXED = auto()\n\n\nclass TonyduanMixtureDensityNetwork(nn.Module):\n \"\"\"\n Mixture density network.\n\n [ Bishop, 1994 ]\n\n Parameters\n ----------\n in_feature: int; dimensionality of the covariates\n out_features: int; dimensionality of the response variable\n n_mixtures: int; number of components in the mixture model\n \"\"\"\n def __init__(self, in_features, out_features, n_mixtures,\n hidden_size=None,\n noise_type=NoiseType.DIAGONAL, fixed_noise_level=None, eps=1e-6):\n super().__init__()\n assert (fixed_noise_level is not None) == (noise_type is NoiseType.FIXED)\n num_sigma_channels = {\n NoiseType.DIAGONAL: out_features * n_mixtures,\n NoiseType.ISOTROPIC: n_mixtures,\n NoiseType.ISOTROPIC_ACROSS_CLUSTERS: 1,\n NoiseType.FIXED: 0,\n }[noise_type]\n\n if hidden_size is None:\n hidden_size = n_mixtures*out_features\n\n self.in_features = in_features\n self.out_features = out_features\n self.n_components = n_mixtures\n self.noise_type = noise_type\n self.fixed_noise_level = fixed_noise_level\n self.eps = eps\n\n self.pi_network = nn.Sequential(\n nn.Linear(in_features, hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, n_mixtures),\n )\n self.normal_network = nn.Sequential(\n nn.Linear(in_features, hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, out_features * n_mixtures + num_sigma_channels)\n )\n\n def forward(self, x):\n eps = self.eps\n #\n # Returns\n # -------\n # log_pi: (bsz, n_components)\n # mu: (bsz, n_components, dim_out)\n # sigma: (bsz, n_components, dim_out)\n #\n log_pi = torch.log_softmax(self.pi_network(x), dim=-1)\n normal_params = self.normal_network(x)\n mu = normal_params[..., :self.out_features * self.n_components]\n sigma = normal_params[..., self.out_features * self.n_components:]\n\n if self.noise_type is NoiseType.DIAGONAL:\n sigma = torch.exp(sigma + eps)\n if self.noise_type is NoiseType.ISOTROPIC:\n sigma = torch.exp(sigma + eps).repeat(1, self.out_features)\n if self.noise_type is NoiseType.ISOTROPIC_ACROSS_CLUSTERS:\n sigma = torch.exp(sigma + eps).repeat(1, self.n_components * self.out_features)\n if self.noise_type is NoiseType.FIXED:\n sigma = torch.full_like(mu, fill_value=self.fixed_noise_level)\n\n mu = mu.reshape(-1, self.n_components, self.out_features)\n sigma = sigma.reshape(-1, self.n_components, self.out_features)\n return log_pi, mu, sigma\n\n def loss(self, x, y):\n log_pi, mu, sigma = self.forward(x)\n z_score = (y.unsqueeze(1) - mu) / sigma\n normal_loglik = (\n -0.5 * torch.einsum(\"bij,bij->bi\", z_score, z_score)\n - torch.sum(torch.log(sigma), dim=-1)\n )\n loglik = torch.logsumexp(log_pi + normal_loglik, dim=-1)\n return -loglik\n\n def loss_hat(self, y_hat, y):\n log_pi, mu, sigma = y_hat\n z_score = (y.unsqueeze(1) - mu) / sigma\n normal_loglik = (\n -0.5 * torch.einsum(\"bij,bij->bi\", z_score, z_score)\n - torch.sum(torch.log(sigma), dim=-1)\n )\n loglik = torch.logsumexp(log_pi + normal_loglik, dim=-1)\n return -loglik.mean()\n\n def sample(self, x):\n log_pi, mu, sigma = self.forward(x)\n cum_pi = torch.cumsum(torch.exp(log_pi), dim=-1)\n rvs = torch.rand(len(x), 1).to(x)\n rand_pi = torch.searchsorted(cum_pi, rvs)\n rand_normal = torch.randn_like(mu) * sigma + mu\n samples = torch.take_along_dim(rand_normal, indices=rand_pi.unsqueeze(-1), dim=1).squeeze(dim=1)\n return samples\n\n\nclass TonyduanMixtureDensityNetworkLoss(nn.Module):\n\n def __init__(self, eps=1e-6):\n super().__init__()\n self.eps = eps\n\n def forward(self, mdn_params, y_true):\n log_pi, mu, sigma = mdn_params\n z_score = (y_true.unsqueeze(1) - mu) / sigma\n normal_loglik = (\n -0.5 * torch.einsum(\"bij,bij->bi\", z_score, z_score)\n - torch.sum(torch.log(sigma), dim=-1)\n )\n loglik = torch.logsumexp(log_pi + normal_loglik, dim=-1)\n return -loglik.mean()\n","repo_name":"corradomio/python_projects","sub_path":"commons/torchx/nn/modules/mdn.py","file_name":"mdn.py","file_ext":"py","file_size_in_byte":13040,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"39934647254","text":"from elasticsearch import Elasticsearch\nimport json\nimport os\nimport requests\n\nes = Elasticsearch([\n {\n 'host': 'localhost',\n 'port': 9200\n }\n])\n\nlistOfFiles = [f for f in os.listdir() if os.path.isfile(f) if '.json' in f]\n\ndata = dict()\n\nfor file in listOfFiles:\n doc_name = file.split('.json')[0]\n\n with open(file) as json_data:\n d = json.load(json_data)\n\n for x in range(len(d)):\n data = d[x]['fields']\n data['pk'] = d[x]['pk']\n\n es.index(index='swapi', doc_type=doc_name, body=data)\n\nprint('done indexing')\n","repo_name":"VinayakBagaria/SWAPI---Vue","sub_path":"python-json/automate.py","file_name":"automate.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"77"}
+{"seq_id":"39219395037","text":"from flask import Flask, redirect, render_template, request, url_for\n\napp = Flask(__name__, static_folder='static')\n\napp.config[\"DEBUG\"] = True\n\ncomments = []\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef index():\n if request.method == \"GET\":\n return render_template(\"forum.html\", comments=comments)\n\n comments.append(request.form[\"contents\"])\n return redirect(url_for('index'))\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"pearlinn/Pearlin-Portfolio","sub_path":"forum/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"29491534639","text":"#decodificadores\n\ndef decodificador(codigo):\n letras_cod = codigo.split(\",\")\n msj = \"\"\n for i in range(len(letras_cod)):\n msj = msj + chr(binario_decimal(letras_cod[i]))\n return msj\n\ndef binario_decimal(binario):\n posicion = 0\n decimal = 0\n binario = binario[::-1]\n for digito in binario:\n multiplicador = 2**posicion\n decimal += int(digito) * multiplicador\n posicion += 1\n return decimal\n\nif __name__ == \"__main__\":\n print(\"Mensaje: \" + decodificador(\"01101000,01101111,01101100,01100001\"))","repo_name":"pabloschwarzenberg/grader","sub_path":"tema9_ej3/tema9_ej3_cb5c72a49af0425c8c4e6e2f8e866f2b.py","file_name":"tema9_ej3_cb5c72a49af0425c8c4e6e2f8e866f2b.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"10363557840","text":"from transitions.extensions import LockedMachine as Machine\nfrom dbox_app.phy.rgb_led import Color\nfrom transitions.extensions.states import add_state_features, Timeout\n\n\n@add_state_features(Timeout)\nclass TimeoutStateMachine(Machine):\n pass\n\n\nclass StateMachine(object):\n\n states = [\n {\n 'name': 'startup',\n 'ignore_invalid_triggers': True,\n },\n {\n 'name': 'idle',\n 'ignore_invalid_triggers': True,\n },\n {\n 'name': 'unlatch_failure',\n 'timeout': 3,\n 'on_timeout': 'advance',\n 'ignore_invalid_triggers': True,\n 'on_enter': '_enter_unlatch_failure_state',\n 'on_exit': '_exit_unlatch_failure_state',\n },\n {\n 'name': 'unlatch',\n 'timeout': 3,\n 'on_timeout': 'advance',\n 'ignore_invalid_triggers': True,\n 'on_enter': '_enter_unlatch_state',\n 'on_exit': '_exit_unlatch_state'\n },\n {\n 'name': 'exiting',\n 'ignore_invalid_triggers': True,\n }\n ]\n\n def __init__(self, button, led, secure_lock, bluetooth, latch):\n \"\"\"\n Main state machine for the application. Implements the \"transitions\" library\n :param button:\n :param led:\n :param secure_lock:\n :param bluetooth:\n :param latch:\n \"\"\"\n self.__button = button\n self.__led = led\n self.__secure_lock = secure_lock\n self.__bluetooth = bluetooth\n self.__latch = latch\n\n self.machine = TimeoutStateMachine(model=self, states=self.states, initial='idle')\n\n # Set up the startup state transition\n self.machine.add_transition(\n \"_on_start\",\n \"startup\",\n \"idle\",\n )\n\n # Set up button press handler\n self.machine.add_transition(\n \"_trigger_button_press\",\n \"idle\",\n \"unlatch_failure\",\n conditions=['_is_device_locked'],\n )\n self.machine.add_transition(\n \"_trigger_button_press\",\n \"idle\",\n \"unlatch\"\n )\n self.__button.on_press_and_release = self._trigger_button_press\n\n # Transitions back to idle from button press handlers\n self.machine.add_transition(\n \"advance\",\n \"unlatch_failure\",\n \"idle\",\n )\n self.machine.add_transition(\n \"advance\",\n \"unlatch\",\n \"idle\",\n )\n\n # Set up the exit transitions\n self.machine.add_transition(\n \"_on_exit\",\n \"idle\",\n \"exiting\"\n )\n self.machine.add_transition(\n \"_on_exit\",\n \"unlatch_failure\",\n \"exiting\"\n )\n self.machine.add_transition(\n \"_on_exit\",\n \"unlatch\",\n \"exiting\"\n )\n\n def start(self):\n \"\"\"\n Move the state machine from the startup to idle state\n :return:\n \"\"\"\n self._on_start()\n\n def exit(self):\n \"\"\"\n Begin the state machine exit procedure\n :return:\n \"\"\"\n self._on_exit()\n\n def _is_device_locked(self):\n \"\"\"\n Returns true if the device is locked, else false\n :return:\n \"\"\"\n return self.__secure_lock.is_locked\n\n\n def _enter_unlatch_failure_state(self):\n \"\"\"\n Tasks to run when entering the unlatch failure state\n :return:\n \"\"\"\n self.__led.disable()\n self.__led.set_color(Color.RED)\n self.__led.blink(4)\n self.__led.enable()\n\n def _exit_unlatch_failure_state(self):\n \"\"\"\n Tasks to run when exiting the unlatch failure state\n :return:\n \"\"\"\n self.__led.disable()\n\n def _enter_unlatch_state(self):\n self.__led.disable()\n if self.__latch.unlatch():\n self.__led.set_color(Color.GREEN)\n else:\n self.__led.set_color(Color.PINK)\n self.__led.blink(4)\n\n def _exit_unlatch_state(self):\n self.__latch.release()\n self.__led.disable()\n\n\n","repo_name":"PseudoDesign/dbox_app","sub_path":"dbox_app/state_machine/state_machine.py","file_name":"state_machine.py","file_ext":"py","file_size_in_byte":4175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"7615297818","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pandas as pd # type: ignore\n\n\ndef _prev(x: pd.Series) -> pd.Series:\n prev_x = x.shift(1)\n prev_x[:1] = x.values[0]\n return prev_x\n\n\n_samephase_nb: int = 10\n\n\ndef gain_value(\n actions: pd.DataFrame,\n gains: pd.Series,\n) -> pd.Series:\n sameteam = _prev(actions.team_id) == actions.team_id\n prev_gains = _prev(gains) * sameteam # + _prev(scores) * (~sameteam)\n\n # if the previous action was too long ago, the odds of prev_gains are now 0\n toolong_idx = (\n abs(actions.time_seconds - _prev(actions.time_seconds)) > _samephase_nb\n )\n prev_gains[toolong_idx] = 0\n\n # if the previous action was a goal, the odds of prev_gains are now 0\n prevgoal_idx = (\n _prev(actions.type_name).isin([\"shot\", \"shot_freekick\", \"shot_penalty\"])\n ) & (_prev(actions.result_name) == \"success\")\n prev_gains[prevgoal_idx] = 0\n\n return gains - prev_gains\n\n\ndef effective_attack_value(\n actions: pd.DataFrame,\n effective_attack: pd.Series,\n) -> pd.Series:\n\n sameteam = _prev(actions.team_id) == actions.team_id\n prev_effective_attack = (\n _prev(effective_attack) * sameteam\n ) # + _prev(scores) * (~sameteam)\n\n # if the previous action was too long ago, the odds of prev_effective_attack are now 0\n toolong_idx = (\n abs(actions.time_seconds - _prev(actions.time_seconds)) > _samephase_nb\n )\n prev_effective_attack[toolong_idx] = 0\n\n # if the previous action was a goal, the odds of prev_effective_attack are now 0\n prevgoal_idx = (\n _prev(actions.type_name).isin([\"shot\", \"shot_freekick\", \"shot_penalty\"])\n ) & (_prev(actions.result_name) == \"success\")\n prev_effective_attack[prevgoal_idx] = 0\n\n return -(effective_attack - prev_effective_attack)\n\n\ndef offensive_value(\n actions: pd.DataFrame,\n scores: pd.Series,\n concedes: pd.Series,\n) -> pd.Series:\n\n sameteam = _prev(actions.team_id) == actions.team_id\n prev_scores = _prev(scores) * sameteam + _prev(concedes) * (~sameteam)\n\n # if the previous action was too long ago, the odds of scoring are now 0\n toolong_idx = (\n abs(actions.time_seconds - _prev(actions.time_seconds)) > _samephase_nb\n )\n prev_scores[toolong_idx] = 0\n\n # if the previous action was a goal, the odds of scoring are now 0\n prevgoal_idx = (\n _prev(actions.type_name).isin([\"shot\", \"shot_freekick\", \"shot_penalty\"])\n ) & (_prev(actions.result_name) == \"success\")\n prev_scores[prevgoal_idx] = 0\n\n # fixed odds of scoring when penalty\n penalty_idx = actions.type_name == \"shot_penalty\"\n prev_scores[penalty_idx] = 0.792453\n\n # fixed odds of scoring when corner\n corner_idx = actions.type_name.isin([\"cornerkick\", \"corner_short\"])\n prev_scores[corner_idx] = 0.046500\n\n return scores - prev_scores\n\n\ndef defensive_value(\n actions: pd.DataFrame,\n scores: pd.Series,\n concedes: pd.Series,\n) -> pd.Series:\n\n sameteam = _prev(actions.team_id) == actions.team_id\n prev_concedes = _prev(concedes) * sameteam + _prev(scores) * (~sameteam)\n\n toolong_idx = (\n abs(actions.time_seconds - _prev(actions.time_seconds)) > _samephase_nb\n )\n prev_concedes[toolong_idx] = 0\n\n # if the previous action was a goal, the odds of conceding are now 0\n prevgoal_idx = (\n _prev(actions.type_name).isin([\"shot\", \"shot_freekick\", \"shot_penalty\"])\n ) & (_prev(actions.result_name) == \"success\")\n prev_concedes[prevgoal_idx] = 0\n\n return -(concedes - prev_concedes)\n\n\ndef value(\n actions: pd.DataFrame,\n features: pd.DataFrame,\n preds: pd.DataFrame,\n drops: list,\n C_vdep_v0=3.9,\n) -> pd.DataFrame:\n # insert np.nan into the index where all elements in freeze_frame_360 are NaNs.\n preds = preds.values\n for index in drops:\n preds = np.insert(preds, index, np.nan, axis=0)\n preds = pd.DataFrame(\n data=preds, columns=[\"scores\", \"concedes\", \"gains\", \"effective_attack\"]\n )\n\n # which team is attacking or defending?\n teams = actions[\"team_name\"].unique()\n attack_team = actions[\"team_name\"].values.tolist()\n defense_team = actions[\"team_name\"].values.tolist()\n for i, team in enumerate(actions[\"team_name\"]):\n if (\n (\n actions.at[actions.index[i], \"type_name\"]\n in [\n \"interception\",\n \"tackle\",\n \"clearance\",\n \"keeper_punch\",\n \"keeper_claim\",\n \"keeper_save\",\n ]\n )\n or ( # which side commit foul?\n (0 < i < len(actions) - 1)\n & (actions.at[actions.index[i], \"type_name\"] == \"foul\")\n & (actions.at[actions.index[i - 1], \"team_name\"] != team)\n )\n or (actions.at[actions.index[i], \"result_name\"] == \"owngoal\")\n ):\n attack_team[i] = teams[teams != team][0]\n else:\n defense_team[i] = teams[teams != team][0]\n\n v = pd.DataFrame()\n v[\"offensive_value\"] = offensive_value(actions, preds.scores, preds.concedes)\n v[\"defensive_value\"] = defensive_value(actions, preds.scores, preds.concedes)\n v[\"vaep_value\"] = v[\"offensive_value\"] + v[\"defensive_value\"]\n d = pd.DataFrame()\n d[\"vdep_value\"] = preds.gains - C_vdep_v0 * preds.effective_attack\n d[\"gain_value\"] = gain_value(actions, preds.gains)\n d[\"attacked_value\"] = effective_attack_value(actions, preds.effective_attack)\n ids = pd.DataFrame()\n ids[\"attack_team\"] = pd.Series(attack_team)\n ids[\"defense_team\"] = pd.Series(defense_team)\n # ids[\"gains_id\"] = features[\"regain_a0\"] | features[\"result_offside_a0\"]\n ids[\"gains_id\"] = features[\"regain_a0\"]\n ids[\"effective_id\"] = features[\"penetration_a0\"] | (\n (actions[\"type_name\"].str.contains(\"shot\")) & (actions[\"period_id\"] < 5)\n )\n\n return v, d, ids\n","repo_name":"Rikuhei-ynwa/Generalized-VDEP","sub_path":"socceraction/vdep/formula.py","file_name":"formula.py","file_ext":"py","file_size_in_byte":5924,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"77"}
+{"seq_id":"40097728506","text":"import The_Real_LSTM as gstm\n\nfrom torch import optim\nfrom torch import save, load\nfrom torch import cuda, set_default_tensor_type\n\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.nn import Module ; from random import shuffle\n\nset_default_tensor_type('torch.cuda.FloatTensor' if cuda.is_available() else 'torch.FloatTensor')\n\n\n\n\ndef make_model(hm_channels, vector_size, memory_size, blueprints=None):\n\n if blueprints is None: blueprints = tuple([(\n (int(memory_size * 3/5), memory_size), # module : intermediate state\n (int(memory_size * 3/5), memory_size), # module : global state\n (int(vector_size * 3/5), vector_size), # module : global output\n ) for _ in range(2)])\n else: blueprints = tuple([[module + tuple([size]) if len(module) == 0 or size != module[-1] else module\n for _, (module, size) in enumerate(zip(structure, [memory_size, memory_size, vector_size]))]\n for structure in blueprints])\n\n model = gstm.create_networks(blueprints, vector_size, memory_size, hm_channels)\n params = gstm.get_params(model)\n\n\n return GSTM(model, params)\n\n\n\nclass GSTM(Module):\n\n def __init__(self, model, params):\n super(GSTM, self).__init__()\n\n self.model = model\n self.params, self.names = params\n\n def forward(self, sequence, hm_timestep=None, drop=0.0):\n return gstm.propogate_model(self.model, sequence, gen_iterations=hm_timestep, dropout=drop)\n\n\n\nclass Dataset(Dataset):\n\n def __init__(self, hm_channels, channel_size, min_seq_len, max_seq_len, hm_data, file, obj):\n\n\n if obj is not None:\n self.data = obj\n self.hm_data = len(obj)\n\n elif file is not None:\n from glob import glob\n\n raw_files = glob(file)\n self.data = []\n for file in raw_files:\n self.data.extend(pickle_load(file))\n\n shuffle(self.data) ; self.hm_data = hm_data\n self.data = self.data[:hm_data]\n\n\n else:\n import random\n\n self.hm_data = hm_data\n self.min_seq_len = min_seq_len\n self.max_seq_len = max_seq_len\n self.hm_channels = hm_channels\n self.channel_size = channel_size\n\n data_fn = lambda : [random.random() for _ in range(channel_size)]\n len_fn = lambda : random.randint(min_seq_len,max_seq_len)\n generate= lambda : [[data_fn() for e in range(self.hm_channels)] for _ in range(len_fn())]\n\n self.data = [(generate(), generate())\n for _ in range(hm_data)]\n\n self.shuffle = lambda : shuffle(self.data)\n\n def split(self, dev_ratio=0.0, test_ratio=0.0):\n hm_train = int((1-dev_ratio-test_ratio) * self.hm_data)\n hm_dev = int(dev_ratio * self.hm_data)\n hm_test = int(test_ratio * self.hm_data)\n\n dev = Dataset(0, 0, 0, 0, 0, 0,\n obj=self.data[hm_dev:-hm_test])\n test = Dataset(0, 0, 0, 0, 0, 0,\n obj=self.data[-hm_test:])\n self.data = self.data[:hm_dev]\n self.hm_data = hm_train\n\n returns = [self, dev, test]\n return tuple([r for r in\n returns if len(r) > 0])\n\n def batchify(self, batch_size):\n hm_batches = int(self.hm_data / batch_size)\n hm_leftover = int(self.hm_data % batch_size)\n batched_resource = [self.data[_ * batch_size : (_+1) * batch_size]\n for _ in range(hm_batches)]\n if hm_leftover != 0:\n batched_resource.append(self.data[-hm_leftover:])\n\n return batched_resource\n\n def __getitem__(self, index):\n return self.data[index]\n\n def __len__(self): return self.hm_data\n\n\n\ndef make_data(hm_channels=1, channel_size=5, min_seq_len=50, max_seq_len=75, data_size=200, from_file=None, from_obj=None):\n return Dataset(hm_channels, channel_size, min_seq_len, max_seq_len, data_size, from_file, from_obj)\n\ndef propogate(model, input, target_length=None, dropout=0.0):\n return model.forward(input, target_length, drop=dropout)\n\ndef make_grads(output, target):\n loss = gstm.loss(output, target)\n loss.backward()\n return float(loss)\n\ndef make_optimizer(model, lr, type=None):\n if type == 'adam':\n return optim.Adam(model.params, lr)\n elif type == 'rms':\n return optim.RMSprop(model.params, lr)\n else: return optim.SGD(model.params, lr)\n\ndef take_step(optimizer):\n optimizer.step() ; optimizer.zero_grad()\n\n\n # Helpers #\n\n\ndef save_session(model, optimizer=None):\n pickle_save(model.model, 'model.pkl')\n if optimizer is not None:\n save(optimizer.state_dict(), 'meta.pkl')\n\n\ndef load_session():\n model = pickle_load('model.pkl')\n if model is None: params = None\n else: params = gstm.get_params(model)\n\n if model is not None:\n mtorch = GSTM(model, params)\n try: meta = load('meta.pkl')\n except Exception:\n return mtorch, make_optimizer(mtorch, 0.001)\n type = get_opt_type(meta)\n opt = make_optimizer(mtorch, 0, type)\n opt.load_state_dict(meta)\n\n else: return None, None\n return mtorch, opt\n\n\nimport pickle\n\n\ndef pickle_save(obj, file_path):\n with open(file_path, \"wb\") as f:\n return pickle.dump(obj, MacOSFile(f), protocol=pickle.HIGHEST_PROTOCOL)\n\n\ndef pickle_load(file_path):\n try:\n with open(file_path, \"rb\") as f:\n return pickle.load(MacOSFile(f))\n except: return None\n\n\n\nclass MacOSFile(object):\n\n def __init__(self, f):\n self.f = f\n\n def __getattr__(self, item):\n return getattr(self.f, item)\n\n def read(self, n):\n # print(\"reading total_bytes=%s\" % n, flush=True)\n if n >= (1 << 31):\n buffer = bytearray(n)\n idx = 0\n while idx < n:\n batch_size = min(n - idx, 1 << 31 - 1)\n buffer[idx:idx + batch_size] = self.f.read(batch_size)\n idx += batch_size\n return buffer\n return self.f.read(n)\n\n def write(self, buffer):\n n = len(buffer)\n idx = 0\n while idx < n:\n batch_size = min(n - idx, 1 << 31 - 1)\n self.f.write(buffer[idx:idx + batch_size])\n idx += batch_size\n\n\ndef get_opt_type(meta):\n # print(f'Opt params: {meta['param_groups'][0].keys()}')\n for key in meta['param_groups'][0].keys():\n if key == 'dampening': return None\n elif key == 'alpha': return 'rms'\n elif key == 'amsgrad':return 'adam'\n\n\ndef plot(losses):\n try:\n import matplotlib.pyplot as plot\n\n if len(losses) <= 10:\n hm_epochs = len(losses[0])\n for _, color in enumerate(('r', 'g', 'b')):\n try:\n plot.plot(range(hm_epochs), losses[_], color)\n except : pass\n else: plot.plot(range(len(losses)), losses, 'k')\n\n plot.show()\n except: print('graph unavailable.')\n","repo_name":"MultiTrickFox/the_Real_LSTM","sub_path":"mk1/VanillaV2.py","file_name":"VanillaV2.py","file_ext":"py","file_size_in_byte":6980,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"9672456495","text":"def countsort(A, k):\n C = [0 for _ in range(k)]\n B = []\n for j in range(len(A)):\n C[A[j]] += 1\n for i in range(len(C)):\n for j in range(C[i]):\n B.append(i)\n return B\n\nif __name__ == \"__main__\":\n arr = [5, 4, 2, 8, 6, 4, 4, 2, 8, 6, 2]\n k = 10\n sorted_arr = countsort(arr, k)\n print(sorted_arr)\n","repo_name":"bensenberner/ctci","sub_path":"clrs/sorting/countingsort.py","file_name":"countingsort.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"32284556139","text":"from typing import List\n\n\nclass Solution:\n def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\n res = []\n\n for i in range(0, len(nums) - k + 1):\n mx = nums[i]\n\n for i in range(i, i + k):\n print(i)\n mx = max(mx, nums[i])\n\n res.append(mx)\n\n return res\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n print(sol.maxSlidingWindow([1, 3, -1, -3, 5, 3, 6, 7], 3))\n","repo_name":"Vortexx2/DSA-questions","sub_path":"leetcode/hard/239-sliding/brute.py","file_name":"brute.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"27432014102","text":"import os\r\n# import rsa\r\nimport random\r\n\r\ndef isprime(n:int,t:int=10):\r\n assert n>1\r\n if n==2:\r\n return True\r\n if not n&1:\r\n return False\r\n\r\n s=0\r\n d=n-1\r\n while not d&1:\r\n d>>=1\r\n s+=1\r\n assert (1<>1\r\n q=getprime(b-qs)\r\n while not (q-1)%e:\r\n print('q',end='')\r\n q=getprime(b-qs)\r\n p=getprime(qs)\r\n while p==q or not (p-1)%e:\r\n print('p',end='')\r\n p=getprime(qs)\r\n assert (p-1)*(q-1)%e\r\n return p,q\r\n\r\np,q=getpq(4096)\r\n\r\nprint()\r\nprint('e =',e)\r\nprint('p =',p)\r\nprint('q =',q)\r\nn=p*q\r\n\r\nm='Hello world!'\r\nc=pow(bytes_to_long(m.encode('utf-8')),e,n)\r\nprint(long_to_bytes(c))\r\n\r\nphi=(p-1)*(q-1)\r\nd=inverse(e,phi)\r\nm=pow(c,d,n)\r\nprint(long_to_bytes(m).decode('utf8'))\r\n","repo_name":"userElaina/plt-draw-homework","sub_path":"others/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"43430555001","text":"import sys\nsys.path.append(\"..\")\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QMessageBox\nfrom login.loginbackend import *\nfrom login.loginfrontend import *\nfrom chatting.chatting import *\nHOST = '127.0.0.1'\nPORT = 14333\nBUFSIZE = 1024\nADDR=(HOST,PORT)\nclass logQmain(QtWidgets.QMainWindow):#主要是为了添加一个回车登陆功能\n enter = QtCore.pyqtSignal()\n closes = QtCore.pyqtSignal()\n def __init__(self):\n super(logQmain,self).__init__()\n def keyPressEvent(self,e):\n if e.key() == QtCore.Qt.Key_Return:\n self.enter.emit()\nclass Login(QtCore.QObject):#为前后��的signal和slot提供连接的平台\n def __init__(self):\n super(Login,self).__init__()\n self.waytologin = False;\n self.window = logQmain()\n self.window.setWindowFlags(Qt.Qt.MSWindowsFixedSizeDialogHint)\n self.ui = Loginfrontend(self.window)\n self.client = Loginbackend()\n self.window.closes.connect(self.client.close)\n self.ui.logsucess.connect(self.enterChatting)\n self.ui.logininfo.connect(self.client.login)\n self.client.loginresult.connect(self.ui.checkLog)\n self.ui.gui.register.clicked.connect(self.enterRegister)\n self.ui.wannainvisible.connect(self.stateDefined)\n self.window.show()\n def enterAnother(self):\n username = self.ui.gui.username.text()\n self.enterChatting(username)\n def enterChatting(self,username):\n self.window.close()#关闭当前窗口\n self.client.changeLink()#把link交给chatting\n self.chatting = Chatting(username,self.waytologin)\n def enterRegister(self):#开启注册窗口\n self.register = Register(self.client)\n def stateDefined(self,value):\n self.waytologin = value\n self.client.userstate = value\n","repo_name":"tx19980520/Ty-s-Online-Chatting-Room","sub_path":"client/login/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"34393978886","text":"#Exo 16\r\ndef solve(n):\r\n s=0\r\n nb=2**n\r\n L=list(str(nb)) #Je découpe ma liste digit par digit (transformé en chaine de caractère)\r\n for i in range(len(L)):\r\n L[i]=int(L[i]) #Conversion str en int\r\n s+=L[i] #Je somme les digits\r\n \r\n return s\r\nassert(solve(15)==26)\r\nprint(solve(10000))","repo_name":"mines-nancy-tcss5ac-2018/td1-gaspardHouillon","sub_path":"TD1-ex16.Houillon.py","file_name":"TD1-ex16.Houillon.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"38399101103","text":"from collections import deque\n\nN, M = map(int, input().split()) # N x M 배열. (1, 1) 출발 (N, M) 도착 위치\n\n# 최단 경로 찾는 문제라 bfs로 풀이\ndef bfs(start, dest):\n queue = deque()\n queue.append(start)\n visited[start[0]][start[1]] = 1 # visited는 좌표값으로 접근하기 위해 2차원 리스트로 구성\n\n while queue:\n num = queue.popleft()\n\n if num == dest: # dest 찾으면 해당 좌표에 누적된 이동거리 return\n return visited[num[0]][num[1]]\n\n for nxt in graph[num]:\n if not visited[nxt[0]][nxt[1]]:\n queue.append(nxt)\n visited[nxt[0]][nxt[1]] = (\n visited[num[0]][num[1]] + 1\n ) # 하나씩 이동하면서 최소 거리 찾기 위해 visited에 누적합. bfs로 접근하기 때문에 중복해서 더해질 문제 X\n\n\ndata = [list(map(int, list(input()))) for _ in range(N)]\nvisited = [[0] * M for _ in range(N)]\n# 상하좌우로 이동하며 그래프에 넣어주기 위한 델타\ndx = [-1, 1, 0, 0]\ndy = [0, 0, -1, 1]\n# 인접행렬이나 인접리스트보다 딕셔너리로 하는 게 깔끔할 거 같아서 딕셔너리로 그래프 구성\ngraph = dict()\n# 각 좌표 이동하며 상, 하, 좌, 우에 갈 수 있는 곳 있는지 그래프로 구성\nfor row in range(N):\n for col in range(M):\n for i in range(4):\n nxt_row = row + dx[i]\n nxt_col = col + dy[i]\n # 좌표 범위 내면서, 이동할 위치가 1이고, 현재 위치도 1이면\n if (\n 0 <= nxt_col < M\n and 0 <= nxt_row < N\n and data[nxt_row][nxt_col] == 1\n and data[row][col] == 1\n ):\n if graph.get((row, col)): # 딕셔너리에 현재 좌표 키 존재하면 append\n graph[(row, col)].append((nxt_row, nxt_col))\n else: # 키 존재하지 않으면 새로운 키 생성\n graph[(row, col)] = [(nxt_row, nxt_col)]\n\nstart = (0, 0) # 시작 좌표\ndest = (N - 1, M - 1) # 끝 좌표\n\nprint(bfs(start, dest))\n","repo_name":"LeeSungRyul/TIL","sub_path":"Algorithm/BAEKJOON/Graph/2178_미로탐색.py","file_name":"2178_미로탐색.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"22178293396","text":"from typing import Iterator, Tuple\n\nimport numpy as np\n\n\ndef iter_bits(val: int, width: int, *, signed: bool = False) -> Iterator[int]:\n \"\"\"Iterate over the bits in a binary representation of `val`.\n\n This uses a big-endian convention where the most significant bit\n is yielded first.\n\n Args:\n val: The integer value. Its bitsize must fit within `width`\n width: The number of output bits.\n signed: If True, the most significant bit represents the sign of\n the number (ones complement) which is 1 if val < 0 else 0.\n Raises:\n ValueError: If `val` is negative or if `val.bit_length()` exceeds `width`.\n \"\"\"\n if val.bit_length() + int(val < 0) > width:\n raise ValueError(f\"{val} exceeds width {width}.\")\n if val < 0 and not signed:\n raise ValueError(f\"{val} is negative.\")\n if signed:\n yield 1 if val < 0 else 0\n width -= 1\n for b in f'{abs(val):0{width}b}':\n yield int(b)\n\n\ndef iter_bits_twos_complement(val: int, width: int) -> Iterator[int]:\n \"\"\"Iterate over the bits in a binary representation of `val`.\n\n This uses a big-endian convention where the most significant bit\n is yielded first. Allows for negative values and represents these using twos\n complement.\n\n Args:\n val: The integer value. Its bitsize must fit within `width`\n width: The number of output bits.\n\n Raises:\n ValueError: If `val.bit_length()` exceeds `2 * width + 1`.\n \"\"\"\n if (val.bit_length() - 1) // 2 > width:\n raise ValueError(f\"{val} exceeds width {width}.\")\n mask = (1 << width) - 1\n for b in f'{val&mask:0{width}b}':\n yield int(b)\n\n\ndef iter_bits_fixed_point(val: float, width: int, *, signed: bool = False) -> Iterator[int]:\n r\"\"\"Represent the floating point number -1 <= val <= 1 using `width` bits.\n\n $$\n val = \\sum_{b=0}^{width - 1} val[b] / 2^{1+b}\n $$\n\n Args:\n val: Floating point number in [-1, 1]\n width: The number of output bits in fixed point binary representation of `val`.\n signed: If True, the most significant bit represents the sign of\n the number (ones complement) which is 1 if val < 0 else 0.\n\n Raises:\n ValueError: If val is not between [0, 1] (signed=False) / [-1, 1] (signed=True).\n \"\"\"\n lb = -1 if signed else 0\n assert lb <= val <= 1, f\"{val} must be between [{lb}, 1]\"\n if signed:\n yield 1 if val < 0 else 0\n width -= 1\n val = abs(val)\n for _ in range(width):\n val = val * 2\n out_bit = np.floor(val)\n val = val - out_bit\n yield int(out_bit)\n\n\ndef float_as_fixed_width_int(val: float, width: int) -> Tuple[int, int]:\n \"\"\"Returns a `width` length fixed point binary representation of `val` where -1 <= val <= 1.\"\"\"\n bits = [*iter_bits_fixed_point(val, width, signed=True)]\n return bits[0], int(''.join(str(b) for b in bits[1:]), 2)\n","repo_name":"quantumlib/Cirq","sub_path":"cirq-ft/cirq_ft/infra/bit_tools.py","file_name":"bit_tools.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","stars":3974,"dataset":"github-code","pt":"77"}
+{"seq_id":"4644771174","text":"#!/usr/bin/env python3\n\n\nimport sys\nimport util\n\n\nif __name__ == '__main__':\n for block in util.blocks(sys.stdin):\n lines = block.splitlines()\n if any('S' in line for line in lines[1:]):\n print()\n else:\n print(block, end='')\n","repo_name":"texttheater/xlci","sub_path":"src/python/iob_filter.py","file_name":"iob_filter.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"77"}
+{"seq_id":"2152978443","text":"#\n# [200] Number of Islands\n#\n# https://leetcode.com/problems/number-of-islands/description/\n#\n# algorithms\n# Medium (36.81%)\n# Total Accepted: 177.3K\n# Total Submissions: 481.7K\n# Testcase Example: '[[\"1\",\"1\",\"1\",\"1\",\"0\"],[\"1\",\"1\",\"0\",\"1\",\"0\"],[\"1\",\"1\",\"0\",\"0\",\"0\"],[\"0\",\"0\",\"0\",\"0\",\"0\"]]'\n#\n# Given a 2d grid map of '1's (land) and '0's (water), count the number of\n# islands. An island is surrounded by water and is formed by connecting\n# adjacent lands horizontally or vertically. You may assume all four edges of\n# the grid are all surrounded by water.\n# \n# Example 1:\n# \n# \n# Input:\n# 11110\n# 11010\n# 11000\n# 00000\n# \n# Output: 1\n# \n# \n# Example 2:\n# \n# \n# Input:\n# 11000\n# 11000\n# 00100\n# 00011\n# \n# Output: 3\n# \n# \n#\nclass UnionFind(object):\n \n def __init__(self, m, n, count):\n self.m = m\n self.n = n\n self.root = [i for i in range(m * n)]\n self.size = [1] * (m * n)\n self.count = count\n \n def getCoor(self, p):\n i, j = p\n # 一定要重视 是 self.n 不是 self.m\n return self.n * i + j\n \n def find(self, p):\n p = self.getCoor(p)\n while p != self.root[p]:\n p = self.root[p]\n return p\n \n def union(self, p1, p2):\n root1 = self.find(p1)\n root2 = self.find(p2)\n if root1 == root2:\n return\n self.root[root2] = root1\n self.size[root1] += self.size[root2]\n self.count -= 1\n\n\n\nclass Solution(object):\n def numIslands(self, grid):\n \"\"\"\n :type grid: List[List[str]]\n :rtype: int\n \"\"\"\n if len(grid) == 0 or grid is None:\n return 0\n m = len(grid)\n n = len(grid[0])\n count = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == '1':\n count += 1\n \n uf = UnionFind(len(grid), len(grid[0]), count)\n visited = set()\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == '1':\n visited.add((i, j))\n for dir in [[0,1], [0, -1], [-1, 0], [1, 0]]:\n x = dir[0] + i\n y = dir[1] + j\n if x < 0 or x >=m or y < 0 or y >= n or (x, y) in visited:\n continue\n elif grid[x][y] == '1':\n uf.union([i, j], [x, y])\n return uf.count\n \n \n","repo_name":"eechooo/letcode","sub_path":"200.number-of-islands.171651636.ac.py","file_name":"200.number-of-islands.171651636.ac.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"14266909357","text":"import tkinter as tk\r\n\r\n\r\nclass AlarmMessageDialog:\r\n def __init__(self, config):\r\n self.config = config\r\n\r\n def show_alarm_message_dialog(self, icon, item):\r\n config = self.config\r\n\r\n class InputDialog(tk.Toplevel):\r\n def __init__(self, parent, title):\r\n super().__init__(parent)\r\n self.title(title)\r\n self.geometry(\"300x100\")\r\n\r\n self.label = tk.Label(self, text=\"Enter your alarm message:\")\r\n self.label.pack()\r\n\r\n self.entry = tk.Entry(self)\r\n self.entry.insert(0, config.alarm_message)\r\n self.entry.pack()\r\n\r\n self.ok_button = tk.Button(self, text=\"OK\", command=self.on_ok)\r\n self.ok_button.pack()\r\n\r\n def on_ok(self):\r\n self.user_input = self.entry.get()\r\n self.destroy()\r\n\r\n root = tk.Tk()\r\n root.withdraw()\r\n\r\n input_dialog = InputDialog(root, \"User Input\")\r\n root.wait_window(input_dialog)\r\n\r\n self.config.alarm_message = input_dialog.user_input\r\n self.config.save_to_file()\r\n\r\n root.destroy()\r\n","repo_name":"wmatecki97/PostureBonk","sub_path":"app/menu/alarm_message_dialog.py","file_name":"alarm_message_dialog.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"8752608298","text":"import requests\nimport sys\nfrom urllib3.exceptions import InsecureRequestWarning\nimport re\nrequests.urllib3.disable_warnings()\n\nlinksregex = \"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+\"\nurl = sys.argv[1]\nif not \"https://\" in url:\n url = \"https://\" + url\nheaders={'User-agent':'Mozilla//5.0',}\nr = requests.get(url=url, verify=False,headers=headers,timeout=2)\ngetcontent = r.content.decode(\"utf-8\", \"ignore\") #get the entire content of website if successful, has to be ISO-8859-1 to decode the content\nlinksall = re.findall(linksregex, getcontent, re.IGNORECASE)\nfor links in linksall: #print as an iteration\n print(links)\n","repo_name":"whitehat92/getcalls","sub_path":"links.py","file_name":"links.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"22250641053","text":"import argparse\nimport sys\nimport os\nimport subprocess\nimport psutil\nimport json\nimport datetime\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir)))\nfrom jobs_launcher.core.config import main_logger\nfrom jobs_launcher.core.config import RENDER_REPORT_BASE\n\n\ndef createArgsParser():\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--tests_list', required=True, metavar=\"\")\n parser.add_argument('--render_path', required=True, metavar=\"\")\n parser.add_argument('--scene_path', required=True, metavar=\" int:\n \"\"\"\n Find optimal number of clusters for unsupervised case.\n Parameters\n ----------\n df : DataFrame\n Input DataFrame with obtained embeddings\n cl_method : Clustering method from sklearn.cluster\n\n Returns\n -------\n Optimal number of clusters w.r.t. the method and given dataset\n \"\"\"\n cl = pd.DataFrame(list(map(np.ravel, df.iloc[:, 1])))\n print(\"First row of Data: \\n\", cl.iloc[0].values)\n cur_score = 0.0\n cur_num_cl = 2\n for cur_cl in range(2, CONFIG.NUM_CL_MAX):\n km = cl_method(n_clusters=cur_cl)\n predicted_labels = km.fit_predict(cl)\n silhouette_avg = silhouette_score(cl, predicted_labels)\n if silhouette_avg >= cur_score:\n cur_score = silhouette_avg\n cur_num_cl = cur_cl\n print(f\"Current clustering method is {cl_method}\")\n print(f\"Optimal number of clusters is {cur_num_cl}. The average silhouette_score is {cur_score}\")\n return cur_num_cl\n","repo_name":"AlexWorldD/NetEmbs","sub_path":"NetEmbs/Clustering/find_optimal.py","file_name":"find_optimal.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"5472693991","text":"# 2579 계단 오르기\n# 아직 완료못함.\nimport sys\n\n\ndef solve(stair_num, stair_list):\n max_list = [0]\n # 계단수가 1, 2 일 경우\n if stair_num < 3:\n for i in range(1, stair_num+1):\n max_list.append(max_list[i - 1] + stair_list[i])\n\n # 계단수가 3개 이상\n elif stair_num >= 3:\n for i in range(1, 3):\n max_list.append(max_list[i-1] + stair_list[i])\n\n for i in range(3, stair_num+1):\n # i 번째 계단 까지 올라가는데 i-1 번째 계단에서 i 로 오르는 경우, i-2 번째 계단에서 i 로 오르는 경우 둘 중 큰 값(점수)를 얻는 경우 리턴\n max_list.append(max(max_list[i-3] + stair_list[i-1] + stair_list[i], max_list[i-2] + stair_list[i]))\n\n print(max_list[stair_num])\n\n\nif __name__ == \"__main__\":\n my_stair_num = int(sys.stdin.readline())\n my_stair_list = [0]\n\n for _ in range(my_stair_num):\n my_stair_list.append(int(sys.stdin.readline()))\n\n solve(my_stair_num, my_stair_list)\n","repo_name":"UJHa/Codeit-Study","sub_path":"(11) 알고리즘 기초 - Dynamic Programming/05) 2579 계단 오르기/junhyoung_2579.py","file_name":"junhyoung_2579.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"31834933402","text":"import collections\n# Collecions Counter makes a dict in where it shows how many times does a value occur in an array\nprint(\"heloo world\")\nlen_size = int(input())\nsizes = list(map(int,input().split(' ')))\nmanage = collections.Counter(sizes)\ndays_pay = 0\nfor i in range(int(input())):\n need_size,cost = list(map(int,input().split(' ')))\n if need_size in manage.keys() and manage[need_size]>0:\n manage[need_size]-=1\n days_pay += cost\nprint(days_pay)\n","repo_name":"sage-kanishq/PythonFiles","sub_path":"Challenges/collection_counter.py","file_name":"collection_counter.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"7267991919","text":"#Importing the required dependencies\nimport cv2 #for video rendering\nimport dlib #for face and landmark detection\nimport imutils\nfrom scipy.spatial import distance as dist #for calculating dist b/w the eye landmarks\nfrom imutils import face_utils #to get the landmark ids of the left and right eyes ----you can do this manually too\n\n\n\ncam = cv2.VideoCapture('assets/me_blinking.mp4')\n\n#------defining a function to calulate the EAR-----------#\ndef calculate_EAR(eye) :\n #---calculate the verticle distances---#\n y1 = dist.euclidean(eye[1] , eye[5])\n y2 = dist.euclidean(eye[2] , eye[4])\n\n #----calculate the horizontal distance---#\n x1 = dist.euclidean(eye[0],eye[3])\n\n #----------calculate the EAR--------#\n EAR = (y1+y2) / x1\n return EAR\n\n#---------Mark the eye landmarks-------#\ndef mark_eyeLandmark(img , eyes):\n for eye in eyes:\n pt1,pt2 = (eye[1] , eye[5])\n pt3,pt4 = (eye[0],eye[3])\n cv2.line(img,pt1,pt2,(200,00,0),2)\n cv2.line(img, pt3, pt4, (200, 0, 0), 2)\n return img\n\n#---------Variables-------#\nblink_thresh = 0.5\nsucc_frame = 2\ncount_frame = 0\n\n#-------Eye landmarks------#\n(L_start, L_end) = face_utils.FACIAL_LANDMARKS_IDXS[\"left_eye\"]\n(R_start, R_end) = face_utils.FACIAL_LANDMARKS_IDXS['right_eye']\n\n#------Initializing the Models for Landmark and face Detection---------#\ndetector = dlib.get_frontal_face_detector()\nlandmark_predict = dlib.shape_predictor('Model/shape_predictor_68_face_landmarks.dat')\n\n\nwhile 1 :\n\n #------If the video ends Reset it to start-----#\n if cam.get(cv2.CAP_PROP_POS_FRAMES) == cam.get(cv2.CAP_PROP_FRAME_COUNT) :\n cam.set(cv2.CAP_PROP_POS_FRAMES, 0)\n\n #-------Reading the frame from the video--------#\n _,frame = cam.read()\n frame = imutils.resize(frame,width=640)\n #---converting frame to gray scale to pass to detector----#\n img_gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n #---detecting the faces---#\n faces = detector(img_gray)\n for face in faces :\n #----landmark detection-----#\n shape = landmark_predict(img_gray,face)\n #----converting the shape class directly to a list of (x,y) cordinates-----#\n shape = face_utils.shape_to_np(shape)\n for lm in shape:\n cv2.circle(frame,(lm),3,(10,2,200))\n #----parsing the landmarks list to extract lefteye and righteye landmarks--#\n lefteye = shape[L_start : L_end]\n righteye = shape[R_start:R_end]\n\n #-----Calculate the EAR---#\n left_EAR = calculate_EAR(lefteye)\n right_EAR = calculate_EAR(righteye)\n img = frame.copy()\n #----mark the landmarks----#\n img = mark_eyeLandmark(img,[lefteye,righteye])\n\n #-----Avg of left and right eye EAR----#\n avg = (left_EAR+right_EAR)/2\n if avg= succ_frame :\n cv2.putText(img, 'Blink Detected',(30,30) , cv2.FONT_HERSHEY_DUPLEX , 1,(0,200,0),1)\n else:\n count_frame=0\n\n cv2.imshow(\"Video\", img)\n if cv2.waitKey(1) & 0xFF == ord('q') :\n break\n\ncam.release()\ncv2.destroyAllWindows()","repo_name":"yagyesh-bobde/Eye-Blink-Detector","sub_path":"basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"24459160532","text":"from cryptle.metric.base import Timeseries, MemoryTS\nimport numpy as np\n\nimport cryptle.logging as logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass SMA(Timeseries):\n \"\"\"Timeseries for calculating the simple moving average of the upstream.\n\n Args\n ----\n lookback : int\n The lookback period for calculating the SMA.\n name : str, optional\n To be used by :meth:`__repr__` method for debugging\n \"\"\"\n\n def __repr__(self):\n return self.name\n\n def __init__(self, ts, lookback, name=\"sma\", list=False):\n self.name = f'{name}{lookback}'\n super().__init__(ts)\n logger.debug('Obj: {}. Initialized the parent Timeseries of SMA.', type(self))\n self._lookback = lookback\n self._ts = ts\n self._cache = []\n self.value = None\n if list:\n self.onList()\n\n # Any ts would call evaluate as new_candle emits. This updates its ts value for calculating the\n # correct value for output and further sourcing.\n @MemoryTS.cache('normal')\n def evaluate(self, candle=None):\n logger.debug('Obj {} Calling evaluate in SMA.', type(self))\n self.value = np.mean(self._cache)\n\n def onList(self):\n pass\n # self.history = list(pd.DataFrame(self._ts).rolling(self._lookback).mean())\n","repo_name":"bridgelancer/cryptle_fork","sub_path":"cryptle/metric/timeseries/sma.py","file_name":"sma.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"74179620087","text":"from django.http import HttpResponseBadRequest, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom .transcribe import Transcribe\nfrom .download import Download\nfrom rest_framework import viewsets\nfrom .models import File\nfrom .serializers import MediaFileSerializer\nimport asyncio\nimport os\n\n@csrf_exempt\ndef transcribe(request):\n \"\"\"\n API to handle transcription service\n\n Args:\n request (file): File object of form data\n\n Returns:\n JsonResponse: Formatted JsonResponse object on success\n \"\"\"\n if request.method == 'POST' and 'file' in request.FILES:\n file = request.FILES['file']\n transcriber = Transcribe()\n\n # Save the file to the storage and get its ID\n file_instance = File(file=file)\n file_instance.save()\n file_id = file_instance.id\n\n data = file_instance\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n data = loop.run_until_complete(transcriber.transcribe_file(file))\n\n # Delete the uploaded media file\n file_path = file_instance.file.path\n os.remove(file_path)\n \n if data is not None:\n response_data = {\n 'status': 'success',\n 'message': 'File received and processed successfully',\n 'data': data\n }\n return JsonResponse(response_data)\n else:\n return HttpResponseBadRequest(\"Failed to transcribe the file\")\n else:\n return HttpResponseBadRequest(\"No file received\")\n\n@csrf_exempt\ndef download(request):\n if request.method == 'POST':\n data = request.POST.get('data')\n fmat = request.POST.get('format')\n filename = request.POST.get('file_name')\n downloader = Download()\n response = downloader.download(fmat, data, filename)\n return response\n else:\n return HttpResponseBadRequest(\"No file received\")\n\n\nclass FileView(viewsets.ModelViewSet):\n queryset = File.objects.all()\n serializer_class = MediaFileSerializer","repo_name":"sukhman31/backend-transcribe","sub_path":"transcription_webapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"11233702966","text":"# coding=utf-8\n# /usr/bin/env python3\n'''\nAuthor:Fuxin Jiang\nEmail:jiangfuxin17@mails.ucas.ac.cn\n'''\n# 主要利用多线程进行加速处理数据\nimport pandas as pd\n# 首先将原来的usage里面没有用的app过滤掉\nimport time\nimport multiprocessing\nimport os\n\nimport numpy as np\nimport json\nfrom joblib import Parallel, delayed\nimport multiprocessing\nfrom scipy import sparse\nfrom sklearn.feature_extraction import DictVectorizer\n# 训练集、测试集的路径\nage_train_file = \"../age_train.csv\"\nage_test_file = \"../age_test.csv\"\nfrom scipy.sparse import csr_matrix\n# 该函数主要用于过滤没有用的app的\ndef filter_app_usage(file_path, effctive_apps_files):\n time_start_ = time.time()\n user_app_usage = pd.read_csv(file_path, header=None, names=['id', 'app', 'duration', 'times', 'date'], usecols=['id', 'app', 'duration', 'times', 'date'])\n effective_apps = pd.read_csv(effctive_apps_files, header=None)\n effective_apps.columns = ['app']\n effective_apps_list = list(effective_apps['app'])\n user_app_usage_filter = user_app_usage.loc[user_app_usage.app.isin(effective_apps_list)]\n time_final_ = time.time()\n print(\"过滤有效的APP完毕!\")\n print(\"花费时间为:\")\n print(time_final_ - time_start_)\n return user_app_usage_filter\n# 对过滤之后的APP进行计算\ndef duration_sum_times(data, effctive_apps_files):\n print(\"开始计算duration和times的总和计算!\")\n time_start_duration_sum_times = time.time()\n data_train = pd.read_csv(age_train_file, header=None, names=['id', 'label'], usecols=['id'], dtype={'id': np.str}, index_col='id')\n data_test = pd.read_csv(age_test_file, header=None, names=['id'], dtype={'id': np.str}, index_col='id')\n effective_apps = pd.read_csv(effctive_apps_files, header=None)\n effective_apps.columns = ['app']\n effective_apps_list = list(effective_apps['app'])\n dictionary = dict(zip(effective_apps_list, list(range(len(effective_apps_list)))))\n data_train['trainrow'] = np.arange(data_train.shape[0])\n data_test['testrow'] = np.arange(data_test.shape[0])\n data_train.index = data_train.index.astype(np.str)\n data_test.index = data_test.index.astype(np.str)\n\n datalist = data['date'].unique().tolist()\n # 总共的APP数量\n app_numbers = 5000\n def temp(data, date):\n temp_1 = data.loc[(data['date'] == date)]\n temp_1.reset_index(drop=True, inplace=True)\n temp_1['appId_category'] = temp_1['app'].map(dictionary)\n temp_1 = temp_1.dropna().reset_index()\n temp_1 = temp_1.set_index('id')\n temp_1.index = temp_1.index.astype(np.str)\n temp_1_train = temp_1.merge(data_train, on='id')\n temp_1_test = temp_1.merge(data_test, on='id')\n temp_1_train_duration = csr_matrix((temp_1_train['duration'].values, (temp_1_train.trainrow, temp_1_train.appId_category)), shape=(data_train.shape[0], app_numbers))\n temp_1_test_duration = csr_matrix((temp_1_test['duration'].values, (temp_1_test.testrow, temp_1_test.appId_category)), shape=(data_test.shape[0], app_numbers))\n temp_1_train_times = csr_matrix((temp_1_train['times'].values, (temp_1_train.trainrow, temp_1_train.appId_category)), shape=(data_train.shape[0], app_numbers))\n temp_1_test_times = csr_matrix((temp_1_test['times'].values, (temp_1_test.testrow, temp_1_test.appId_category)), shape=(data_test.shape[0], app_numbers))\n user_app_usage_train_duration[date] = temp_1_train_duration\n user_app_usage_test_duration[date] = temp_1_test_duration\n user_app_usage_train_times[date] = temp_1_train_times\n user_app_usage_test_times[date] = temp_1_test_times\n\n with multiprocessing.Manager() as manager:\n user_app_usage_train_duration = manager.dict()\n user_app_usage_test_duration = manager.dict()\n user_app_usage_train_times = manager.dict()\n user_app_usage_test_times = manager.dict()\n multipro = []\n\n for i, date in enumerate(datalist):\n print(date)\n thread_name = \"usage_thead_%d\" % i\n multipro.append(multiprocessing.Process(target=temp, name=thread_name, args=(data, date,)))\n for process in multipro:\n process.start()\n for process in multipro:\n process.join()\n\n for i, date in enumerate(datalist):\n if i == 0:\n train_duration = user_app_usage_train_duration[date]\n test_duration = user_app_usage_test_duration[date]\n\n train_times = user_app_usage_train_times[date]\n test_times = user_app_usage_test_times[date]\n else:\n train_duration += user_app_usage_train_duration[date]\n test_duration += user_app_usage_test_duration[date]\n\n train_times += user_app_usage_train_times[date]\n test_times += user_app_usage_test_times[date]\n\n sparse.save_npz('train_sparse_matrix_duration_sum.npz', train_duration) # 保存\n sparse.save_npz('test_sparse_matrix_duration_sum.npz', test_duration) # 保存\n sparse.save_npz('train_sparse_matrix_times_sum.npz', train_times) # 保存\n sparse.save_npz('test_sparse_matrix_times_sum.npz', test_times) # 保存\n\n time_final_duration_sum_times = time.time()\n print(\"训练集的usage和测试集的usage已经划分好了!\")\n print(\"花费时间为:\", time_final_duration_sum_times - time_start_duration_sum_times)\n\nif __name__ == \"__main__\":\n\n time_start = time.time()\n # 读取原始文件\n file_path2 = '../user_app_usage.csv'\n # 过滤有用的APP\n effective_apps_file = \"../effective_apps_max_features_5000.csv\"\n user_app_usage_filter = filter_app_usage(file_path2, effective_apps_file)\n print(\"读取usage文件完毕!\")\n\n # 对APP的duration还有times进行加和处理\n duration_sum_times(user_app_usage_filter, effective_apps_file)\n del user_app_usage_filter\n\n time_final = time.time()\n print(\"总共用时为:\", time_final - time_start)\n\n\n\n","repo_name":"fuxinjiang/huawei2019","sub_path":"lightgbm/user_app_usage.py","file_name":"user_app_usage.py","file_ext":"py","file_size_in_byte":6015,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"10107545227","text":"# This Python program:\n# Given an defined velocity and angle, calculate how far an object will travel before hitting the ground\n# based on inputted force of gravity. Prompt user for value of gravity in terms of 2 numbers and a mathematical\n# operand (i.e. addition, subtraction, multiplication, division)\n# Formula for parabolic motion on the x plane:\n# R = (v^2 sin 2θ)/g\n# where:\n# v = initial velocity\n# θ = initial angle in degrees\n# g = 9.8m/s^2 on earth at sea level\n# Alberth Matos\n# 06/04/2023\n# CMIS 102\n\nfrom math import radians, sin\n\n# Constants:\nDEVELOPER = 'Alberth Matos'\nDATE = '06/04/2023'\nCLASS = 'CMIS 102' # n.b. class (all lowercase) is a reserved named\n\ndef main():\n # Class information\n print(f'Developer: {DEVELOPER}')\n print(f'Date: {DATE}')\n print(f'Class: {CLASS}\\n')\n\n print('We will calculate the range of parabolic motion for an object at an initial velocity of')\n print('50m/s at an angle of 45 degrees, at your preferred gravity.')\n print('To enter gravity, please provide two numbers and a mathematical operation')\n print(' (i.e. addition, subtraction, multiplication, division)')\n number1 = input('Please enter the first number: ')\n number2 = input('Please enter the second number: ')\n operand = input('Please enter the operand (Options are: + - * /): ')\n\n if operand == '+':\n gravity = float(number1) + float(number2)\n elif operand == '-':\n gravity = float(number1) - float(number2)\n elif operand == '*':\n gravity = float(number1) * float(number2)\n elif operand == '/':\n gravity = float(number1) / float(number2)\n else:\n print('Operand did not match one of: + - * /')\n exit\n\n velocity = 50\n angle = 45\n\n # See the formula statement above. range = (v^2 * sin 2θ) / g\n range = ((velocity**2) * sin(2 * radians(angle))) / gravity # math.sin expects radians, we need to convert degrees to rads\n\n print(f'if gravity is equal to {number1}{operand}{number2}, or {gravity}m/s/s then')\n if gravity < 0:\n print('The object would drift off into space because gravity is less than 0.')\n else:\n print(f'the object will travel for {range} meters before landing.')\n\nmain()","repo_name":"amatos/CMIS-102","sub_path":"MatosAlberth_wk3.py","file_name":"MatosAlberth_wk3.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"20434371771","text":"from feat_extract import *\nfrom classify import *\nimport warnings\nwarnings.filterwarnings('ignore')\n\ntrait_variation = 0.9\n#cnn_weights= 'weights/pretrained.h5'\ncnn_weights= 'weights/model224nobg-body_global.h5'\n#cnn_weights= 'weights/4shizo-body.h5'\ncnn_layer = 5\npooling_type = 'avg'\nstrat_k_fold = 2\nADASYN_ = False \nk = 6 \n\npath = 'datasets/pleo224'\n#path = 'datasets/shizo224nd_7class'\nrotate = False \nrotation_degree = 20 \nadd_fakes = False \nfake_path= 'fakes4_5class'\nnumber_of_fakes = 20\nrebalance_dataset = False \nrebalance_to = 100 \nSMOTE_fct = False \nprint_results = True \ndisplay_dataset_table = False\nmultiples = None\nfusion_layers = [3,4]\nfuse = False\n\nargs = dict(path=path,\n weights=cnn_weights,\n pooling=pooling_type,\n cnn_layer=cnn_layer,\n fuse=fuse,\n fusion=fusion_layers,\n rotate=rotate,\n fakes=add_fakes,\n fakes_path=fake_path,\n rebalance=rebalance_dataset,\n rebalance_size=rebalance_to,\n number_of_fakes=number_of_fakes,\n iterations=1000,\n norm=True,\n pca=True,\n retain_info=trait_variation,\n dim_red=None,\n smote_fct=SMOTE_fct,\n k_neighbors=k,\n adasyn=ADASYN_,\n stratkfold=strat_k_fold,\n repeated=multiples)\n\nresults = classify(**args).svm_bottleneck()\n\nprint(\"%.2f\" % results[1][0] )\nprint(\"& %.2f\" % results[1][1])\nprint(\"& %.2f\" % results[1][2])\nprint(\"& %.2f\" % results[1][3])\nprint(\"& %.2f\" % results[1][4])\n\n\nc, x_shape = get_pca_coef(multiples=multiples,\n path=path,\n weights=cnn_weights,\n pooling=pooling_type,\n smote_fct=SMOTE_fct,\n rotate=rotate,\n fakes=add_fakes,\n fakes_path=fake_path,\n rebalance=rebalance_dataset,\n rebalance_size=rebalance_to,\n number_of_fakes=number_of_fakes,\n k_neighbors=k,\n adasyn=ADASYN_,\n stratkfold=strat_k_fold)\nprint(c,x_shape)","repo_name":"m-klasen/automated-identification-tool","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"47082176203","text":"import logging\nfrom datetime import datetime\n\nfrom celery import chord\nfrom django.contrib.auth import get_user_model\nfrom django.db import transaction\nfrom pytz import utc\n\nfrom inboxen.celery import app\nfrom inboxen.models import Inbox\nfrom inboxen.tasks import batch_delete_items\n\nlog = logging.getLogger(__name__)\n\n\n@app.task(rate_limit=\"10/m\", default_retry_delay=5 * 60) # 5 minutes\n@transaction.atomic()\ndef disown_inbox(inbox_id):\n try:\n inbox = Inbox.objects.get(id=inbox_id)\n except Inbox.DoesNotExist:\n return False\n\n # delete emails in another task(s)\n batch_delete_items.delay(\"email\", kwargs={'inbox__id': inbox.pk})\n\n # remove identifying data from inbox\n inbox.deleted = True\n inbox.description = \"\"\n inbox.user = None\n inbox.created = datetime.utcfromtimestamp(0).replace(tzinfo=utc)\n inbox.save()\n\n return True\n\n\n@app.task(ignore_result=True)\n@transaction.atomic()\ndef finish_delete_user(result, user_id):\n inbox = Inbox.objects.filter(user__id=user_id).only('id').exists()\n user = get_user_model().objects.get(id=user_id)\n if inbox:\n raise Exception(\"User {0} still has inboxes!\".format(user.username))\n else:\n log.info(\"Deleting user %s\", user.username)\n user.delete()\n\n\n@app.task(ignore_result=True)\n@transaction.atomic()\ndef delete_account(user_id):\n # first we need to make sure the user can't login\n user = get_user_model().objects.get(id=user_id)\n user.set_unusable_password()\n user.is_active = False\n user.save()\n\n # get ready to delete all inboxes\n inboxes = user.inbox_set.only('id')\n if len(inboxes): # pull in all the data\n delete = chord([disown_inbox.s(inbox.id) for inbox in inboxes], finish_delete_user.s(user_id))\n delete.apply_async()\n\n log.info(\"Deletion tasks for %s sent off\", user.username)\n","repo_name":"wrestrtdr/Inboxen","sub_path":"inboxen/account/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"77"}
+{"seq_id":"4583307427","text":"from gensim import models\nfrom gensim.models import KeyedVectors\nfrom joblib import load\nimport numpy as np \nimport sys\nsys.path.append(\"..\")\nfrom customlib import vectorizeText,accessMysql,check_params\n\ntfidf_vectorize_model_link = '../models_bin/tfidf_model.joblib'\ntf = load(tfidf_vectorize_model_link)\n\nmodel_link = '../models_bin/wiki.vi.model.bin'\nword2vec_model = KeyedVectors.load_word2vec_format(model_link, binary=True)\nword_vector = word2vec_model.wv \nsens = []\nwith open(\"test_doc_1.txt\",'r',encoding=\"utf-8\") as f:\n sens = f.readlines()\nwith open(\"test_vector_1.txt\",'w',encoding=\"utf-8\") as f:\n for sen in sens:\n sen = sen.replace('\\n','')\n words = sen.split(' ')\n for word in words:\n if word in word_vector:\n word_vec = word2vec_model[word.lower()]\n word_vec = word_vec/np.sqrt(word_vec.dot(word_vec))\n f.write(word)\n f.write(str(word_vec))\n f.write('\\n')\n # sent_vec = np.zeros(400)\n # try:\n # sent_vec = np.add(sent_vec,word2vec_model[sen])\n # except:\n # pass\n # sent_vec = sent_vec/np.sqrt(sent_vec.dot(sent_vec))\n \n f.write('\\n\\n\\n')\n f.write(\"\\n\\n\\n\\n\")\n for sen in sens:\n f.write(str(tf.transform(sen.split(\" \"))))\n f.write('\\n\\n')\n ","repo_name":"trieuhoangan/ViolentDetecting","sub_path":"sourcecode/experiences/vectorize_exp_1.py","file_name":"vectorize_exp_1.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"41603617408","text":"import sys\nimport glob\nimport subprocess\n\n\nif len(sys.argv) != 4:\n print(\"usage : python3 run_all.py out_dir args search_string\")\n exit()\n\nout_dir = sys.argv[1]\nsearch_string = sys.argv[3].encode()\n\nfor i in range(1, 3 + 1):\n out_tmp_dir = out_dir + \"/\" + str(i)\n print(out_tmp_dir)\n min_queue_tc_idx = 1234567890\n min_crash_tc_idx = 1234567890\n min_time = 123456789000000\n for file_path in glob.glob(out_tmp_dir + \"/queue/*\") + glob.glob(out_tmp_dir + \"/crashes/*\"):\n cmd = sys.argv[2].replace(\"@@\", file_path).split(\" \")\n run = subprocess.run(cmd , stdout = subprocess.PIPE, stderr = subprocess.STDOUT)\n if search_string in run.stdout:\n tc_id = int(file_path.split(\"id:\")[1][:6])\n if \"queue\" in file_path and tc_id < min_queue_tc_idx:\n min_queue_tc_idx = tc_id\n if \"crash\" in file_path and tc_id < min_crash_tc_idx:\n min_crash_tc_idx = tc_id\n if \"time\" in file_path:\n time = int(file_path.split(\"time:\")[1].split(\",\")[0])\n if min_time > time:\n min_time = time\n print(\"min_queue_idx : {}, min_crash_idx : {}, min_time : {}\\n\".format(min_queue_tc_idx, min_crash_tc_idx, min_time))\n","repo_name":"yunho-kim/aflplusplus","sub_path":"tools/run_all_get_time.py","file_name":"run_all_get_time.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"30959553670","text":"import argparse\nimport logging\nimport os\nimport sys\nimport matplotlib\nimport torch\nimport yaml\n\nfrom torch.utils.data import DataLoader\n\nimport asd_tools\nimport asd_tools.models\nimport asd_tools.losses\nimport asd_tools.optimizers\nimport asd_tools.schedulers\nfrom asd_tools.datasets import WaveCollator\nfrom asd_tools.trainer import MetricOECTrainer\nfrom asd_tools.utils import count_params\nfrom asd_tools.utils import seed_everything\n\n\n# set to avoid matplotlib error in CLI environment\nmatplotlib.use(\"Agg\")\n\n\ndef main():\n \"\"\"Run training process.\"\"\"\n parser = argparse.ArgumentParser(\n description=\"Train outlier exposure model (See detail in asd_tools/bin/train.py).\"\n )\n parser.add_argument(\n \"--pos_machine\", type=str, required=True, help=\"Name of positive machine.\"\n )\n parser.add_argument(\n \"--train_pos_machine_scp\",\n default=None,\n type=str,\n help=\"root directory of positive train dataset.\",\n )\n parser.add_argument(\n \"--train_neg_machine_scps\",\n default=[],\n type=str,\n nargs=\"+\",\n help=\"list of root directories of positive train datasets.\",\n )\n parser.add_argument(\n \"--valid_pos_machine_scp\",\n default=None,\n type=str,\n help=\"root directory of positive train dataset.\",\n )\n parser.add_argument(\n \"--valid_neg_machine_scps\",\n default=[],\n type=str,\n nargs=\"+\",\n help=\"list of root directories of positive train datasets.\",\n )\n parser.add_argument(\n \"--outdir\", type=str, required=True, help=\"directory to save checkpoints.\"\n )\n parser.add_argument(\n \"--config\", type=str, required=True, help=\"yaml format configuration file.\"\n )\n parser.add_argument(\n \"--outlier_scp\",\n default=\"\",\n type=str,\n help=\"Scp file of outlier dataset.\",\n )\n parser.add_argument(\n \"--statistic_path\",\n type=str,\n default=\"\",\n help=\"Statistic info of positive data in json.\",\n )\n parser.add_argument(\n \"--resume\",\n default=\"\",\n type=str,\n nargs=\"?\",\n help='checkpoint file path to resume training. (default=\"\")',\n )\n parser.add_argument(\n \"--verbose\",\n type=int,\n default=1,\n help=\"logging level. higher is more logging. (default=1)\",\n )\n parser.add_argument(\n \"--rank\",\n \"--local_rank\",\n default=0,\n type=int,\n help=\"rank for distributed training. no need to explictly specify.\",\n )\n args = parser.parse_args()\n\n args.distributed = False\n if not torch.cuda.is_available():\n device = torch.device(\"cpu\")\n else:\n device = torch.device(\"cuda\")\n\n # suppress logging for distributed training\n if args.rank != 0:\n sys.stdout = open(os.devnull, \"w\")\n\n # set logger\n if args.verbose > 1:\n logging.basicConfig(\n level=logging.DEBUG,\n stream=sys.stdout,\n format=\"%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s\",\n )\n logging.getLogger(\"matplotlib.font_manager\").disabled = True\n elif args.verbose > 0:\n logging.basicConfig(\n level=logging.INFO,\n stream=sys.stdout,\n format=\"%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s\",\n )\n else:\n logging.basicConfig(\n level=logging.WARN,\n stream=sys.stdout,\n format=\"%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s\",\n )\n logging.warning(\"Skip DEBUG/INFO messages\")\n\n # check directory existence\n if not os.path.exists(args.outdir):\n os.makedirs(args.outdir)\n\n # load and save config\n with open(args.config) as f:\n config = yaml.load(f, Loader=yaml.Loader)\n config.update(vars(args))\n seed_everything(seed=config[\"seed\"])\n with open(os.path.join(args.outdir, \"config.yml\"), \"w\") as f:\n yaml.dump(config, f, Dumper=yaml.Dumper)\n for key, value in config.items():\n logging.info(f\"{key} = {value}\")\n # get dataset\n if len(args.outlier_scp) == 0:\n from asd_tools.datasets import OECBalancedBatchSampler\n from asd_tools.datasets import WaveASDDataset\n\n train_dataset = WaveASDDataset(\n pos_machine_scp=args.train_pos_machine_scp,\n neg_machine_scps=args.train_neg_machine_scps,\n allow_cache=config.get(\"allow_cache\", False),\n use_target=config[\"use_target\"],\n augmentation_params=config.get(\"augmentation_params\", {}),\n in_sample_norm=config.get(\"in_sample_norm\", False),\n )\n valid_dataset = WaveASDDataset(\n pos_machine_scp=args.valid_pos_machine_scp,\n neg_machine_scps=args.valid_neg_machine_scps,\n allow_cache=True,\n use_target=config[\"use_target\"],\n in_sample_norm=config.get(\"in_sample_norm\", False),\n )\n train_balanced_batch_sampler = OECBalancedBatchSampler(\n train_dataset,\n batch_size=config[\"batch_size\"],\n shuffle=True,\n drop_last=True,\n n_target=config.get(\"n_target\", 0),\n )\n valid_balanced_batch_sampler = OECBalancedBatchSampler(\n valid_dataset,\n batch_size=config[\"batch_size\"],\n shuffle=False,\n drop_last=False,\n n_target=config.get(\"n_target\", 0),\n )\n else:\n from asd_tools.datasets import OutlierBalancedBatchSampler\n from asd_tools.datasets import OutlierWaveASDDataset\n\n train_dataset = OutlierWaveASDDataset(\n pos_machine_scp=args.train_pos_machine_scp,\n neg_machine_scps=args.train_neg_machine_scps,\n outlier_scp=args.outlier_scp,\n allow_cache=config.get(\"allow_cache\", False),\n use_target=config[\"use_target\"],\n augmentation_params=config.get(\"augmentation_params\", {}),\n statistic_path=args.statistic_path,\n in_sample_norm=config.get(\"in_sample_norm\", False),\n )\n logging.info(f\"train outlier = {len(train_dataset.outlier_files)}.\")\n valid_dataset = OutlierWaveASDDataset(\n pos_machine_scp=args.valid_pos_machine_scp,\n neg_machine_scps=args.valid_neg_machine_scps,\n outlier_scp=\"\",\n allow_cache=True,\n use_target=config[\"use_target\"],\n statistic_path=args.statistic_path,\n in_sample_norm=config.get(\"in_sample_norm\", False),\n )\n logging.info(f\"valid outlier = {len(valid_dataset.outlier_files)}.\")\n train_balanced_batch_sampler = OutlierBalancedBatchSampler(\n train_dataset,\n n_pos=config[\"n_pos\"],\n n_neg=config[\"n_neg\"],\n shuffle=True,\n drop_last=True,\n n_target=config.get(\"n_target\", 0),\n )\n valid_balanced_batch_sampler = OutlierBalancedBatchSampler(\n valid_dataset,\n n_pos=config[\"n_pos\"],\n n_neg=config[\"n_pos\"],\n shuffle=False,\n drop_last=False,\n n_target=config.get(\"n_target\", 0),\n )\n logging.info(f\"The number of training files = {len(train_dataset)}.\")\n logging.info(f\"train pos_source = {len(train_dataset.pos_source_files)}.\")\n logging.info(f\"train pos_target = {len(train_dataset.pos_target_files)}.\")\n logging.info(f\"train neg = {len(train_dataset.neg_files)}.\")\n logging.info(f\"The number of validation files = {len(valid_dataset)}.\")\n logging.info(f\"valid pos_source = {len(valid_dataset.pos_source_files)}.\")\n logging.info(f\"valid pos_target = {len(valid_dataset.pos_target_files)}.\")\n logging.info(f\"valid neg = {len(valid_dataset.neg_files)}.\")\n train_collator = WaveCollator(\n sf=config[\"sf\"],\n sec=config[\"sec\"],\n pos_machine=args.pos_machine,\n shuffle=True,\n use_target=config[\"use_target\"],\n use_is_normal=False,\n )\n valid_collator = WaveCollator(\n sf=config[\"sf\"],\n sec=config[\"sec\"],\n pos_machine=args.pos_machine,\n shuffle=False,\n use_target=config[\"use_target\"],\n use_is_normal=False,\n )\n data_loader = {\n \"train\": DataLoader(\n dataset=train_dataset,\n batch_sampler=train_balanced_batch_sampler,\n collate_fn=train_collator,\n num_workers=config[\"num_workers\"],\n pin_memory=config[\"pin_memory\"],\n ),\n \"valid\": DataLoader(\n valid_dataset,\n batch_sampler=valid_balanced_batch_sampler,\n collate_fn=valid_collator,\n num_workers=config[\"num_workers\"],\n pin_memory=config[\"pin_memory\"],\n ),\n }\n\n # define models and optimizers\n model_class = getattr(asd_tools.models, config[\"model_type\"])\n model = model_class(**config[\"model_params\"]).to(device)\n logging.info(model)\n params_cnt = count_params(model)\n logging.info(f\"Size of model is {params_cnt}.\")\n criterion = {\n \"machine_loss\": getattr(asd_tools.losses, config[\"machine_loss_type\"],)(\n **config[\"machine_loss_params\"]\n ).to(device),\n \"section_loss\": getattr(asd_tools.losses, config[\"section_loss_type\"],)(\n **config[\"section_loss_params\"]\n ).to(device),\n }\n optimizer_class = getattr(\n asd_tools.optimizers,\n config[\"optimizer_type\"],\n )\n params_list = [{\"params\": model.parameters()}]\n metric_fc = None\n if config.get(\"metric_fc_type\", None) is not None:\n metric_fc_class = getattr(\n asd_tools.losses,\n config[\"metric_fc_type\"],\n )\n metric_fc = metric_fc_class(**config[\"metric_fc_params\"]).to(device)\n params_list.append({\"params\": metric_fc.parameters()})\n optimizer = optimizer_class(params_list, **config[\"optimizer_params\"])\n scheduler = None\n if config.get(\"scheduler_type\", None) is not None:\n scheduler_class = getattr(\n asd_tools.schedulers,\n config[\"scheduler_type\"],\n )\n if config[\"scheduler_type\"] == \"OneCycleLR\":\n config[\"scheduler_params\"][\"epochs\"] = config[\"train_max_epochs\"]\n if config.get(\"n_pos\", None) is not None:\n n_pos = config[\"n_pos\"]\n else:\n n_pos = config[\"batch_size\"] // 2\n config[\"scheduler_params\"][\"steps_per_epoch\"] = (\n len(train_dataset.pos_source_files) // n_pos + 1\n )\n scheduler = scheduler_class(optimizer=optimizer, **config[\"scheduler_params\"])\n\n # define trainer\n trainer = MetricOECTrainer(\n steps=1,\n epochs=1,\n data_loader=data_loader,\n model=model.to(device),\n criterion=criterion,\n optimizer=optimizer,\n scheduler=scheduler,\n config=config,\n device=device,\n train=True,\n metric_fc=metric_fc,\n )\n\n # resume from checkpoint\n if len(args.resume) != 0:\n trainer.load_checkpoint(args.resume)\n logging.info(f\"Successfully resumed from {args.resume}.\")\n\n # run training loop\n try:\n trainer.run()\n except KeyboardInterrupt:\n trainer.save_checkpoint(\n os.path.join(config[\"outdir\"], f\"checkpoint-{trainer.steps}steps.pkl\")\n )\n logging.info(f\"Successfully saved checkpoint @ {trainer.steps}steps.\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ibkuroyagi/dcase2022_task2_challenge_recipe","sub_path":"asd_tools/bin/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":11506,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"77"}
+{"seq_id":"23653010575","text":"from flask import Flask, render_template, abort, jsonify, send_from_directory, request, make_response\n\n\nfrom flask_bootstrap import Bootstrap5\nimport base64\nimport urllib\nimport sys\nsys.path.append('..')\nfrom ultrastar.songhelper import UltraStarHelper\nfrom ultrastar.appenv import AppEnv\nfrom ultrastar.helper import Helper\n\n\n\ndef create_app(config_file):\n app = Flask(__name__)\n Bootstrap5(app)\n # to serve all the files from local, instead of CDN\n app.config['BOOTSTRAP_SERVE_LOCAL'] = True\n\n AppEnv.config(config_file)\n AppEnv.print_config()\n \n\n app.AppEnv = AppEnv\n app.ultrastar_helper = UltraStarHelper(AppEnv.config())\n app.ultrastar_helper.load_db()\n\n @app.template_filter()\n def b64encode(s):\n return base64.b64encode(s.encode('utf-8'))\n\n @app.template_filter()\n def b64decode(s):\n return base64.b64decode(s).decode()\n\n @app.template_filter()\n def uuencode(s):\n return urllib.parse.quote_plus(s.encode('utf-8'))\n\n @app.template_filter()\n def uudecode(s):\n return urllib.parse.unquote(s)\n\n @app.route(\"/\")\n @app.route(\"/artists\")\n def artists():\n search = request.args.get('search', default = \"\", type = str)\n cursor = app.ultrastar_helper.db.cursor()\n # using the ID to get the cover is somewhat crap\n # but works (the cover of any of the song)\n if search:\n ## add like string format to ease the search\n search = \"%%%s%%\" % search\n cursor.execute(\"select artist, id, count(artist) as songs from songs where artist like ? group by(artist) order by artist;\",(search,))\n else:\n cursor.execute(\"select artist, id, count(artist) as songs from songs group by(artist) order by artist;\")\n rows = cursor.fetchall()\n cursor.close()\n artist_list = list(map(lambda x: dict(x),rows))\n return render_template(\"artists.html\", \n title=\"UltraStar Artist List\", \n items = artist_list,\n search_action = \"/\")\n\n\n\n @app.route(\"/playlists\")\n def playlists():\n search = request.args.get('search', default = \"\", type = str)\n \n # using the ID to get the cover is somewhat crap\n # but works (the cover of any of the song)\n # TODO\n if search:\n ## add like string format to ease the search\n playlist_list = app.ultrastar_helper.get_playlists(filter=search)\n else:\n playlist_list = app.ultrastar_helper.get_playlists()\n\n return render_template(\"playlists.html\", \n title=\"UltraStar Playlists\", \n items = playlist_list,\n search_action = \"/playlists\")\n\n\n @app.route(\"/playlist\")\n def playlist():\n playlist_id_uu = request.args.get('name', default = \"\", type = str)\n \n \n if not playlist_id_uu:\n abort(403)\n\n playlist_id = uudecode(playlist_id_uu)\n playlist = app.ultrastar_helper.get_playlist(filename=playlist_id)\n if not playlist:\n abort(403)\n title = \"Ultrastar Playlist %s\" % playlist.name \n \n \n return render_template(\"songs.html\", \n title=title, \n artist=None,\n search=None,\n playlist=playlist,\n search_action = \"/songs\")\n\n\n @app.route(\"/songs\")\n def songs():\n artist_id = request.args.get('artist', default = \"\", type = str)\n search = request.args.get('search', default = \"\", type = str)\n title=\"Ultrastar song list\"\n if artist_id:\n artist_id = uudecode(artist_id)\n cursor = app.ultrastar_helper.db.cursor()\n cursor.execute(\"select artist from songs where artist=?\",(artist_id,))\n artist = cursor.fetchone()\n cursor.close()\n artist = dict(artist)\n title = \"Ultrastar song list for %s\" % artist_id \n \n \n return render_template(\"songs.html\", \n title=title, \n artist=uuencode(artist_id), \n playlist=None,\n search=search,\n search_action = \"/songs\")\n \n \n @app.route(\"/data\")\n def data():\n artist_id = request.args.get('artist', default = \"\", type = str)\n playlist_id = request.args.get('playlist', default = \"\", type = str)\n search = request.args.get('search', default = \"\", type = str)\n cursor = app.ultrastar_helper.db.cursor()\n \n if playlist_id:\n playlist_id = uudecode(playlist_id)\n playlist = app.ultrastar_helper.get_playlist(filename = playlist_id)\n if not playlist:\n abort(403)\n # read the songs.\n rows = playlist.songs\n \n \n else:\n\n if not search:\n if artist_id:\n cursor.execute(\"select * from songs where artist=? order by title\",(artist_id,))\n else:\n cursor.execute(\"select * from songs;\")\n else:\n ## add like string format to ease the search\n search = \"%%%s%%\" % search\n if artist_id:\n cursor.execute(\"select * from songs where artist=? and title like ? order by title\",(artist_id,search))\n else:\n cursor.execute(\"select * from songs where title like ?;\", (search,))\n \n rows = cursor.fetchall()\n\n data = []\n for row in rows:\n item = dict(row)\n item['duration'] = Helper.seconds_to_str(item['duration'], trim=True)\n item['multi'] = \"Yes\" if item['multi'] else \"No\"\n data.append(item)\n json = jsonify(data=data)\n cursor.close()\n return json\n \n\n\n @app.route('/img/cover/')\n \n def serve_img(id):\n # use the id of the song to get the cover\n # but use also the cover for the artist\n cursor = app.ultrastar_helper.db.cursor()\n cursor.execute(\"select dirname,cover from songs where id=?;\",(id,))\n item = cursor.fetchone()\n if not item:\n abort(404)\n response = make_response(send_from_directory(item[\"dirname\"], item[\"cover\"], as_attachment=False))\n response.cache_control.max_age = 300\n return response\n\n @app.route('/mp3/')\n def serve_mp3(id):\n # use the id of the song to get the cover\n # but use also the cover for the artist\n cursor = app.ultrastar_helper.db.cursor()\n cursor.execute(\"select dirname,mp3 from songs where id=?;\",(id,))\n item = cursor.fetchone()\n if not item:\n abort(404)\n response = make_response(send_from_directory(item[\"dirname\"], item[\"mp3\"], as_attachment=False))\n response.cache_control.max_age = 300\n return response\n\n @app.errorhandler(404)\n def page_not_found(error):\n return render_template(\"error.html\", error=\"Page not found\"), 404\n\n\n return app","repo_name":"juanmcasillas/UltrastarPlaylists","sub_path":"www/ultraweb.py","file_name":"ultraweb.py","file_ext":"py","file_size_in_byte":7300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"43122289188","text":"from helpers.reader import file_reader, file_writer\nfrom helpers.tmpl import loaded_templates\nfrom .graph import Graph, Vertex\nimport configparser\n\nconfig = configparser.ConfigParser()\nconfig.read(\"../helpers/templates.ini\")\n\n\nclass Freight_Booking:\n def __init__(self, **kwargs):\n self.g = Graph()\n self.op_file = kwargs.pop(\"output_file\", \"outputPS4.txt\")\n\n def readCityTrainfile(self, inputfile):\n train_data = file_reader(inputfile)\n for train in train_data:\n self.g.add_vertex(Vertex(train, \"train\"))\n cities = train_data[train]\n for city in cities:\n self.g.add_vertex(Vertex(city, \"city\"))\n self.g.add_edge(train, city)\n\n def showAll(self):\n vertices = self.g.vertices\n train_list = []\n city_list = []\n for name, vertex in vertices.items():\n if vertex.type == \"train\":\n train_list.append(name)\n elif vertex.type == \"city\":\n city_list.append(name)\n text_train_data = loaded_templates.show(\"show_all\", tcount=len(train_list), ccount=len(city_list),\n train_list=\"\\n\".join(train_list), city_list=\"\\n\".join(city_list))\n text_section = section_header(\"showAll\")\n file_writer(self.op_file, text_section, text_train_data)\n\n def displayTransportHub(self):\n train_count = 0\n hub = \"Not Found\"\n trains = []\n for name, vertex in self.g.vertices.items():\n if vertex.type == \"city\" and len(vertex.neighbours) > train_count:\n trains = vertex.neighbours\n train_count = len(vertex.neighbours)\n hub = vertex.name\n\n text_hub_data = loaded_templates.show(\"t_hub\", hub=hub, tcount=train_count, train_list=\"\\n\".join(trains))\n text_section = section_header(\"displayTransportHub\")\n file_writer(self.op_file, text_section, text_hub_data)\n\n def displayConnectedCities(self, train):\n text_section = section_header(\"displayConnectedCities\")\n if train not in self.g.vertices:\n msg = \"Train {} not found\".format(train)\n file_writer(self.op_file, text_section, msg)\n return\n for name in self.g.vertices:\n if name == train:\n vertex = self.g.vertices[name]\n cities_connected = vertex.neighbours\n count = len(cities_connected)\n text_cities_data = loaded_templates.show(\"cc\", train_no=train, ccount=count,\n city_list=\"\\n\".join(cities_connected))\n file_writer(self.op_file, text_section, text_cities_data)\n\n def displayDirectTrain(self, a, b):\n src = a\n dest = b\n src_vertex = self.g.vertices[src]\n text_section = section_header(\"displayDirectTrain\")\n result_text = \"No direct train found between above cities\"\n for train in src_vertex.neighbours:\n train_vertex = self.g.vertices[train]\n if dest in train_vertex.neighbours:\n train_no = train\n result_text = \"Package can be sent directly: Yes, {}\".format(train_no)\n break\n text_transit_data = loaded_templates.show(\"d_transit\", src=src, dest=dest, msg=result_text)\n file_writer(self.op_file, text_section, text_transit_data)\n\n def findServiceAvailable(self, a, b):\n text_section = section_header(\"findServiceAvailable\")\n try:\n path = self.g.find_path(a, b) # Path finder\n except:\n msg = \"Package cannot be sent from {} to {} due to lack of service connecting these cities\".format(a, b)\n else:\n path_details = \">\".join(path)\n msg = \"Can the package be sent: Yes, \" + path_details\n text_transit_data = loaded_templates.show(\"d_transit\", src=a, dest=b, msg=msg)\n file_writer(self.op_file, text_section, text_transit_data)\n\ndef section_header(section_name):\n return loaded_templates.show(\"section_header\", func=section_name)","repo_name":"sibidass/graphps4","sub_path":"freight/freight_ops.py","file_name":"freight_ops.py","file_ext":"py","file_size_in_byte":4082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"32532203037","text":"from django.conf.urls.static import static\nfrom django.shortcuts import render\nfrom django.views.generic import TemplateView\nfrom django.http import HttpResponse\nfrom django.views import View\nfrom .forms import SubmitUrlForm\nfrom static.py import googleFinHistDown # causing lag\n# Create your views here.\nclass stockView(TemplateView):\n def get(self, request, *args, **kwargs):\n the_form = SubmitUrlForm()\n context = {\n \"title\": \"pyzyme.com\",\n \"form\": the_form,\n }\n return render(request, \"stockAnalysis/query.html\", context)\n # template_name = \"stockAnalysis/query.html\"\n def post(self, request, *args, **kwargs):\n form = SubmitUrlForm(request.POST)\n # return render(request, \"loadingPage/loading.html\")\n if form.is_valid():\n tickr = form.cleaned_data.get(\"url\")\n days = form.cleaned_data.get(\"days\")\n tickrjs = tickr.lower() + days\n tickr = tickr.lower()\n days = int(days)\n geneSearch = googleFinHistDown.main(tickr, days)\n\n context = {\n \"tickr\": tickrjs,\n \"form\": form,\n }\n return render(request, \"stockAnalysis/results.html\", context)\n else:\n test = \"Invalid tickr\"\n context = {\n \"newurl\": test,\n }\n return render(request, \"homepage/inv_keyword.html\", context)\n","repo_name":"aneeshpanoli/pyzyme-do-backup","sub_path":"testProject/stockAnalysis/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"42064018931","text":"\"\"\"Author: Jelmer de Wolde, MVII.\"\"\"\nimport numpy as np\nfrom typing import List\n\nRIGHT_ANGLE = np.pi / 2\n\n\ndef get_angle_between_points(points: List[np.array]) -> float:\n \"\"\"Calculates the angle between three points.\n\n The angle is calculated for the middle point.\n Based on the dot product cosine rule.\n\n Args:\n points (List[np.array]): a list of 3 points, where each point is a 2D array containing the location of the point.\n\n Returns:\n float: the angle between the three points.\n \"\"\"\n a = points[0]\n b = points[1]\n c = points[2]\n\n ba = a - b\n bc = c - b\n return np.arccos(np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc)))\n\n\ndef get_intersection_of_circles(p0: np.array, p1: np.array, r0: float, r1: float) -> List[np.array]:\n \"\"\"Finds the two points with distance r0 from p0 and distance r1 from p1.\n\n This is actually calculating the intersection points of two circles, based on:\n http://paulbourke.net/geometry/circlesphere/#:~:text=Intersection%20of%20two%20circles.\n\n Args:\n p0 (np.array): a 2D array of the position of the first point.\n p1 (np.array): a 2D array of the position of the second point.\n r0 (float): the distance between point p0 and the point of intersection (p3).\n r1 (float): the distance between point p1 and the point of intersection (p3).\n\n Returns:\n List[np.array]: the two points of intersection.\n \"\"\"\n d = np.linalg.norm(p0 - p1)\n dis_p0_p2 = (r0 ** 2 - r1 ** 2 + d ** 2) / (2 * d)\n\n # Return None if input is invalid:\n if r0 ** 2 - dis_p0_p2 ** 2 > 0:\n h = np.sqrt(r0 ** 2 - dis_p0_p2 ** 2)\n p2 = p0 + dis_p0_p2 * (p1 - p0) / d\n\n p3 = []\n\n for kernel in [np.array([-1, 1]), np.array([1, -1])]:\n p3.append(p2 + kernel * h / d * np.flip(p1 - p0))\n\n return p3\n else:\n return [None, None]\n\n\ndef find_fourth_point(\n a: np.array,\n c: np.array,\n da: float,\n cd: float,\n convex: bool,\n) -> np.array:\n \"\"\"Finds the fourth point (d) of a quadrilateral when 2 points (a, c) and the distances da and cd are given, assuming point b is already known.\n\n Args:\n a (np.array): a 2D array of the position of the first point of the quadrilateral.\n c (np.array): a 2D array of the position of the third point of the quadrilateral.\n da (float): the distance between point a and the fourth point (d) we try to find.\n cd (float): the distance between point c and the fourth point (d) we try to find.\n convex (bool): whether the quadrilateral is convex or not.\n\n Returns:\n np.array: the location of the fourth point of the quadrilateral.\n \"\"\"\n r0, r1 = da, cd\n p0, p1 = a, c\n\n d = get_intersection_of_circles(p0, p1, r0, r1)\n\n return d[0] if convex else d[1]\n\n\ndef get_angles(points: List[np.array]) -> List[float]:\n \"\"\"Calculates the angles of a quadrilateral by giving the four points of it.\n\n Args:\n points (List[np.array]): A list containing the positions (2D numpy arrays) of the four points of a quadrilateral.\n\n Returns:\n List[float]: the four angles of the quadrilateral in the same order as the four points are given.\n \"\"\"\n angles = []\n\n for i in range(len(points)):\n # Usually the point i and the previous (i-1) and next (i+1) points are used:\n if i < len(points) - 1:\n angle = get_angle_between_points([points[i - 1], points[i], points[i + 1]])\n # But for the last angle, there is no (i_+1), so points[0] is used:\n else:\n angle = get_angle_between_points([points[i - 1], points[i], points[0]])\n angles.append(angle)\n return angles\n\n\ndef solve_quadritlateral(lengths: List[float], angle_b: float, convex: bool = True, debug: bool = False) -> List[float]:\n \"\"\"Calculates the angles of a quadrilateral given all side lengths and the angle of point b.\n\n It first determines the location of all points where point a is at (0,0).\n Next it calculates and returns all angles.\n\n Args:\n lengths (List[float]): the lengths of the four sides of a quadrilateral, with expected order as [da, ab, bc, cd].\n angle_b (float): the angle in the quadrilateral at point b.\n convex (bool): whether the quadrilateral is convex or not.\n debug (bool): whether debug mode is enabled or not.\n\n Returns:\n List[float]: the four angles of the quadrilateral.\n \"\"\"\n da, ab, bc, cd = lengths\n\n a = np.array([0, 0])\n b = a + np.array([ab, 0])\n c = b + np.array([-np.cos(angle_b) * bc, np.sin(angle_b) * bc])\n d = find_fourth_point(a, c, da, cd, convex)\n points = [a, b, c, d]\n\n angles = get_angles(points)\n\n if debug:\n print(\"Angles are: \", angles)\n check_lengths(points, lengths)\n\n return angles\n\n\ndef check_lengths(points: List[float], real_lengths: List[float]):\n \"\"\"Checks whether the calculated lengths between points are equal to the real lengths.\n\n Expects points as [a, b, c, d] and real_lengths as [da, ab, bc, cd].\n This method is only used for debugging.\n\n Args:\n points (List[np.array]): A list containing the positions (2D numpy arrays) of the four points [a, b, c, d] of a quadrilateral.\n real_lengths (List[float]): A list containing the real lengths [da, ab, bc, cd] of a quadrilateral.\n \"\"\"\n for i in range(len(points)):\n length = np.linalg.norm(points[i - 1] - points[i])\n error = abs(length - real_lengths[i])\n if error > 1e-10:\n print(\"Error difference = \", error)\n","repo_name":"project-march/ProjectMarch","sub_path":"ros2/src/gaits/march_goniometric_ik_solver/march_goniometric_ik_solver/quadrilateral_angle_solver.py","file_name":"quadrilateral_angle_solver.py","file_ext":"py","file_size_in_byte":5583,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"77"}
+{"seq_id":"20367554929","text":"# -*- coding: utf-8 -*-\n\n\"\"\"functions working with patches\"\"\"\n\nimport pandas as pd\nimport daff\n\n\ndef apply_patch(base, patch):\n \"\"\"apply patch created with daff.\n more on the diff format, see: http://specs.frictionlessdata.io/tabular-diff-format/\n\n return: the updated DataFrame.\n \"\"\"\n d = daff.Coopy()\n\n base_df = pd.read_csv(base, header=None)\n patch_df = pd.read_csv(patch, header=None)\n\n base_list = base_df.values.tolist()\n if d.patch(base_list, patch_df.values.tolist()):\n new_df = pd.DataFrame(base_list[1:], columns=base_list[0])\n else:\n raise ValueError(\"patch failed. double check you patch\")\n\n return new_df\n","repo_name":"semio/ddf_utils","sub_path":"ddf_utils/patch.py","file_name":"patch.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"1246626100","text":"from flask import jsonify, request, redirect, url_for, abort\nfrom flask.views import MethodView\nfrom comparison import compare, compare_paths\nfrom ._params import ComparisonGetParams, ComparisonResponseGetParams\nfrom models import ComparisonResponse, VisualizationResponse\n\nfrom util import NumpyEncoder, use_args_with\nimport hashlib\nimport json\n\n\nclass ComparisonAPI(MethodView):\n\n @use_args_with(ComparisonGetParams)\n def get(self, reqargs):\n if reqargs.get(\"response_hash\"):\n comparison_response = ComparisonResponse.get_by_hash(reqargs.get(\"response_hash\"))\n if comparison_response:\n return jsonify(json.loads(comparison_response.data))\n if reqargs.get(\"type\") == 'path':\n compare_paths.update_neo4j_entities()\n conts, preds, data = compare_paths.compare_resources(reqargs.get(\"contributions\"))\n response = {'contributions': conts, 'properties': preds, 'data': data}\n else:\n conts, preds, data = compare.compare_resources(reqargs.get(\"contributions\"))\n response = {'contributions': conts, 'properties': preds, 'data': data}\n json_response = json.dumps(response, cls=NumpyEncoder, sort_keys=True)\n if reqargs.get(\"save_response\"):\n response_hash = hashlib.md5(json_response.encode(\"utf-8\")).hexdigest()\n if not ComparisonResponse.get_by_hash(response_hash):\n comparison_response = ComparisonResponse()\n comparison_response.response_hash = response_hash\n comparison_response.data = json_response\n comparison_response.save()\n response.update({'response_hash': response_hash})\n return jsonify(response)\n\n\nclass OldComparisonAPI(MethodView):\n\n def get(self, contributions: list, **kwargs):\n return redirect(url_for('comparison.compare_resources', contributions=','.join(contributions)), 301)\n\n\nclass ComparisonResponseAPI(MethodView):\n\n @use_args_with(ComparisonResponseGetParams)\n def get(self, reqargs, response_hash):\n comparison_response = ComparisonResponse.get_by_hash(response_hash)\n if comparison_response:\n return comparison_response.data\n else:\n abort(404)\n","repo_name":"TIBHannover/orkg-similarity","sub_path":"comparison/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"7710806382","text":"def func(n , b , arr):\n odd = 0\n even = 0\n cuts = []\n for i in range(n - 1):\n if (arr[i] % 2 != 0):\n odd = odd + 1\n else:\n even = even + 1\n if (odd == even):\n cuts.append(abs(arr[i + 1] - arr[i]))\n cuts.sort()\n ans = 0\n sum = 0\n for i in cuts:\n if (sum + i <= b):\n sum = sum + i\n ans = ans + 1\n return ans\n","repo_name":"Kianoosh76/DS-Course-Materials","sub_path":"2_Sorting/Task7/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"77"}
+{"seq_id":"12204975819","text":"from random import randint\nfrom pygame import *\nfont.init()\nwin_width = 1000\nwin_height = 750\nwindow = display.set_mode((win_width, win_height))\ndisplay.set_caption(\"Maze\") \n\nbackground = transform.scale(image.load(\"kosmos.png\"), (win_width, win_height))\nfail = 0\n\nmixer.init()\nmixer.music.load('sooong.ogg')\nmixer.music.play(-1)\n\nclass GameSprite(sprite.Sprite):\n def __init__(self, player, c_x, c_y, speed, width, height):\n super().__init__()\n self.image = transform.scale(image.load(player), (width, height))\n self.speed = speed\n self.rect = self.image.get_rect()\n self.rect.x = c_x\n self.rect.y = c_y\n def reset(self):\n window.blit(self.image, (self.rect.x, self.rect.y))\n\nclass Player_Movement(GameSprite):\n def update(self):\n keys = key.get_pressed()\n if keys[K_a] and self.rect.x > 5:\n self.rect.x -= self.speed\n if keys[K_d] and self.rect.x < 850:\n self.rect.x += self.speed\n def fire(self):\n keys = key.get_pressed()\n if keys[K_s]:\n Sprite_top = self.rect.top\n Sprite_center_x1 = self.rect.centerx - self.rect.width / 5 * 1.5\n Sprite_center_x2 = self.rect.centerx + self.rect.width / 5 * 1.5\n bullet_hell1.add(Bullet('laser.png', Sprite_center_x1, Sprite_top, 20, 5, 20))\n bullet_hell1.add(Bullet('laser.png', Sprite_center_x2, Sprite_top, 20, 5, 20))\nclass Enemy(GameSprite):\n def update(self):\n self.rect.y += self.speed\n global fail\n if self.rect.y > win_height:\n self.rect.y = 0\n self.rect.x = randint(0, 900)\n fail += 1\n\nclass Bullet(GameSprite):\n def update(self):\n self.rect.y -= self.speed\n\nclass Meter():\n def __init__(self, text, x, y):\n self.font1 = font.Font(None, 36)\n self. text = self.font1.render(text, True, (255, 255, 255))\n self.x = x\n self.y = y\n def set_text(self, text):\n self. text = self.font1.render(text, True, (255, 255, 255))\n def draw(self):\n window.blit(self.text, (self.x, self.y))\n\nLabel = Meter('Счет:', 25, 25)\n\nXWing = Player_Movement('X-Wing.png', 400, 550, 50, 200, 100)\nempire = sprite.Group()\nLaser = Bullet('laser.png', 475, 560, 40, 10, 50 )\nrun = True\nbullet_hell1 = sprite.Group()\nwhile run:\n for ev in event.get():\n if ev.type == QUIT:\n run = False\n window.blit(background, (0, 0))\n if len(empire) < 5:\n X = randint(0, 900)\n empire.add(Enemy('TIE.png', X, 5, 40, 100, 100))\n empire.update()\n empire.draw(window)\n bullet_hell1.update()\n bullet_hell1.draw(window)\n XWing.update()\n XWing.fire()\n XWing.reset()\n display.update()\n time.delay(50)","repo_name":"PlanktonPlanZ/code","sub_path":"shooter_game.py","file_name":"shooter_game.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"40854901517","text":"#!/usr/bin/env python\n\nimport os\nimport requests\n\nfrom google.cloud import pubsub_v1\n\nfrom cloudevents.sdk import converters\nfrom cloudevents.sdk import marshaller\nfrom cloudevents.sdk.converters import structured\nfrom cloudevents.sdk.event import v01\n\ngcp_project = os.environ['PROJECT']\ngcs_subscription = os.environ['SUBSCRIPTION']\ngoogle_credentials = os.environ['CREDENTIALS']\ngoogle_credentials_path = os.environ['GOOGLE_APPLICATION_CREDENTIALS']\nsink_url = os.environ['SINK']\n\ndef write_credentials():\n fh=open(google_credentials_path, 'w')\n fh.write(str(google_credentials))\n fh.close() \n\ndef callback(message):\n print(message.data.decode())\n print(sink_url)\n\n event = (\n v01.Event().\n SetContentType(\"application/json\").\n SetData(message.data.decode()).\n SetEventID(\"my-id\").\n SetSource(\"from-galaxy-far-far-away\").\n SetEventTime(\"tomorrow\").\n SetEventType(\"cloudevent.greet.you\")\n )\n m = marshaller.NewHTTPMarshaller(\n [\n structured.NewJSONHTTPCloudEventConverter()\n ]\n )\n\n headers, body = m.ToRequest(event, converters.TypeStructured, lambda x: x)\n\n requests.post(sink_url, data=body, headers=headers)\n message.ack()\n\nwrite_credentials()\nsub = pubsub_v1.SubscriberClient()\nsub_name = 'projects/%s/subscriptions/%s' % (gcp_project, gcs_subscription)\n\nfuture = sub.subscribe(sub_name, callback)\nfuture.result()\n","repo_name":"sebgoa/triggers","sub_path":"knative/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"73733524730","text":"#Argumentos nomeados\n\ndef imprimir_carro(modelo, ano, qualidade):\n print(\"Modelo do carro: \", modelo)\n print(\"Ano do carro: \", ano)\n print(\"Qualidade do carro: \", qualidade)\n\nmodelo = input(\"Digite o modelo do carro\" )\nano = input(\"Digite o ano do carro \")\nqualidade = input(\"Qual a qualidade do veículo? \")\n\nimprimir_carro(modelo=modelo, ano=ano, qualidade=qualidade)\n\n#Neste exemplo eu utilizei um questionário sobre carros.\n","repo_name":"Diego-A-M/Python-Experience","sub_path":"NamedArguments.py","file_name":"NamedArguments.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"24256528328","text":"# Se solicita recorrer los datos numéricos que se encuentran dentro de la siguiente lista de listas:\nimport pprint\nlistas = [[1, 2, 3], [0, 4, 5], [4, 0, 1], [6, 5, 4]]\n\n# Hay que imprimir cada dato de las listas en pantalla con las siguientes excepciones:\n# • Si el primer número de la sublista es cero, omitir la impresión de toda la sublista,\n# • Si existe un cero en cualquier otra posición, omitir solo la impresión del cero.\n# • Adicionalmente, crear un diccionario donde asignaremos la primera sublista a la clave A, la\n# segunda a la clave B, la tercera a la clave C, y la cuarta a la clave D.\n# • Finalmente, imprimiremos en pantalla el diccionario resultante.\n#\n# Ejemplo de impresión en pantalla:\n# A:[1, 2, 3]\n\n################################\n\"\"\" Imprimir cada dato de la lista con sublistas en pantalla, con excepciones \"\"\"\n# Se declara un diccionario a la que después se asignarán los valores y claves según el requerimiento\ndiccionario = dict()\n# declaracion de variable que almacena las listas ya filtradas y las denomina \"filtradas\" del diccionario\nfiltradas = []\n# variabe iterador\ni = 0\n# se declara una lista para contener los valores de las claves indicadas en requerimientos\nkeys = ['A', 'B', 'C', 'D']\n\n# se establece ciclo for que realiza el filtro de los valores o números que cumplen con los requerimientos\nfor lista in listas:\n if lista[0] == 0: # condiciona si la sublista empieza con '0' ejecute:\n # variable que contine valor del indice de la sublista\n indice_remover = listas.index(lista)\n # remueve el índice capturado anteriormente de la lista 'keys'\n keys.remove(keys[indice_remover])\n # continue, para que no muestre la sublista\n continue\n else: # cuando condición anterior nose cumple (sublista no empieza en '0')\n filtradas.append(lista) # añade la sublista a la lista de 'filtradas'\n for num in lista: # ciclo for que recorre los numeros de la sublista\n if num == 0: # condiciona que si el número de sublista es '0' ejecute:\n lista.remove(num) # remover número de la lista\n\n# imprime el listado de sublistas 'filtradas'\nprint(\"\\nLas sublistas y sus valores filtrados son: \", filtradas)\n\n# Se crea diccionario, asignando a cada 'key' su respectivo value sacado de la nueva lista 'filtradas'\ndiccionario = dict(zip(keys, filtradas))\n# imprime dicccionario resultante\n\nprint(\"\\nEl diccionario resultante queda: \")\npprint.pprint(diccionario)\nprint(\"\\n\")\n","repo_name":"IsauraCG/M3_Ejercicios","sub_path":"M3_S8_Drilling_Recorriendo secuencia/M3_S8_Drilling_IsauraCarrascoGaldames/recorriendo_secuencia.py","file_name":"recorriendo_secuencia.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"73229925690","text":"import urllib3\r\nimport urllib\r\nimport json\r\nimport requests\r\n\r\nurllib3.disable_warnings()\r\n\r\n\r\nclass ServiceDeskPlus:\r\n def __init__(\r\n self, url=\"hotrocntt.cpc.vn\", authtoken=\"564C437D-62C0-4458-8B16-53847F2EEAD9\"\r\n ) -> None:\r\n self.url = url\r\n self.authtoken = authtoken\r\n\r\n def api_get(self, endpoint=None, params=None, data=None):\r\n try:\r\n url = f\"https://{self.url}/{endpoint}\"\r\n headers = {\"authtoken\": self.authtoken}\r\n response = requests.get(\r\n url, headers=headers, params=params, data=data, verify=False\r\n )\r\n response.raise_for_status()\r\n return response.json()\r\n except requests.exceptions.RequestException as e:\r\n return e\r\n\r\n def api_post(self, endpoint, data):\r\n try:\r\n url = f\"https://{self.url}/{endpoint}\"\r\n headers = {\"authtoken\": self.authtoken}\r\n response = requests.post(url, headers=headers, data=data, verify=False)\r\n response.raise_for_status()\r\n return response.json()\r\n except requests.exceptions.RequestException as e:\r\n return e\r\n\r\n def api_delete(self, endpoint, data):\r\n try:\r\n url = f\"https://{self.url}/{endpoint}\"\r\n headers = {\"authtoken\": self.authtoken}\r\n response = requests.delete(url, headers=headers, data=data, verify=False)\r\n response.raise_for_status()\r\n return response.json()\r\n except requests.exceptions.RequestException as e:\r\n return e\r\n\r\n def api_put(self, endpoint, data):\r\n try:\r\n url = f\"https://{self.url}/{endpoint}\"\r\n headers = {\"authtoken\": self.authtoken}\r\n response = requests.put(url, headers=headers, data=data, verify=False)\r\n response.raise_for_status()\r\n return response.json()\r\n except requests.exceptions.RequestException as e:\r\n return e\r\n\r\n def get_requests(self, request_id=None, params=None):\r\n if request_id is not None:\r\n return self.api_get(endpoint=f\"api/v3/requests/{request_id}\")\r\n return self.api_get(endpoint=\"api/v3/requests\")\r\n\r\n def get_users(self, user_id=None, user_email=None):\r\n if user_id is not None:\r\n return self.api_get(endpoint=f\"api/v3/users/{user_id}\")\r\n if user_email is not None:\r\n input_data = json.dumps(\r\n {\r\n \"list_info\": {\r\n \"get_total_count\": True,\r\n \"search_fields\": {\"email_id\": user_email},\r\n }\r\n }\r\n )\r\n params = {\"input_data\": input_data}\r\n return self.api_get(endpoint=\"api/v3/users\", params=params)\r\n return self.api_get(endpoint=\"api/v3/users\")\r\n\r\n def get_sites(self, site_id=None, params=None):\r\n if site_id is not None:\r\n return self.api_get(endpoint=f\"api/v3/sites/{site_id}\")\r\n return self.api_get(endpoint=\"api/v3/sites\")\r\n\r\n def get_technicians(self, technician_id=None, params=None):\r\n if technician_id is not None:\r\n return self.api_get(endpoint=f\"api/v3/technicians/{technician_id}\")\r\n return self.api_get(endpoint=\"api/v3/technicians\")\r\n\r\n def get_categories(self, category_id=None, params=None):\r\n if category_id is not None:\r\n return self.api_get(endpoint=f\"/api/v3/categories/{category_id}\")\r\n return self.api_get(endpoint=\"api/v3/categories\")\r\n\r\n def get_request_approval_levels(self, request_id, approval_level_id=None):\r\n if approval_level_id is not None:\r\n return self.api_get(\r\n endpoint=f\"api/v3/requests/{request_id}/approval_levels/{approval_level_id}\"\r\n )\r\n return self.api_get(endpoint=f\"api/v3/requests/{request_id}/approval_levels\")\r\n\r\n def delete_request_approval_levels(self, request_id, approval_level_id):\r\n return self.api_get(\r\n endpoint=f\"api/v3/requests/{request_id}/approval_levels/{approval_level_id}\"\r\n )\r\n\r\n def add_request_approval(self, request_id, approval_level_id, approver_id):\r\n input_data = json.dumps({\"approval\": {\"approver\": {\"id\": approver_id}}})\r\n payload = {\"input_data\": input_data}\r\n return self.api_post(\r\n endpoint=f\"api/v3/requests/{request_id}/approval_levels/{approval_level_id}/approvals\",\r\n data=payload,\r\n )\r\n\r\n def delete_request_approval(self, request_id, approval_level_id, approval_id):\r\n input_data = {}\r\n payload = {\"input_data\": input_data}\r\n return self.api_delete(\r\n endpoint=f\"api/v3/requests/{request_id}/approval_levels/{approval_level_id}/approvals/{approval_id}\",\r\n data=payload,\r\n )\r\n\r\n def send_notification_for_request_approval(\r\n self, request_id, approval_level_id, approval_id\r\n ):\r\n input_data = json.dumps(\r\n {\r\n \"notification\": {\r\n \"subject\": \"Approval required for a Request\",\r\n \"description\": \"Your approval is required for a Request to act upon. The details of the Request can be found at $ApprovalLink\",\r\n }\r\n }\r\n )\r\n payload = {\"input_data\": input_data}\r\n return self.api_put(\r\n endpoint=f\"api/v3/requests/{request_id}/approval_levels/{approval_level_id}/approvals/{approval_id}/_send_notification\",\r\n data=payload,\r\n )\r\n\r\n def get_request_approvals(self, request_id, approval_level_id, approval_id=None):\r\n if approval_id is not None:\r\n return self.api_get(\r\n endpoint=f\"api/v3/requests/{request_id}/approval_levels/{approval_level_id}/approvals/{approval_id}\"\r\n )\r\n return self.api_get(\r\n endpoint=f\"api/v3/requests/{request_id}/approval_levels/{approval_level_id}/approvals\"\r\n )\r\n\r\n def submit_for_approval(self, request_id, approver_id,message):\r\n try:\r\n request_details = self.get_requests(request_id=request_id, params=None)\r\n request_subject = request_details.get(\"request\").get(\"subject\")\r\n requester_name = request_details.get(\"request\").get(\"requester\").get(\"name\")\r\n requester_email = (\r\n request_details.get(\"request\").get(\"requester\").get(\"email_id\")\r\n )\r\n requester_mobile = (\r\n request_details.get(\"request\").get(\"requester\").get(\"mobile\")\r\n )\r\n request_template = (\r\n request_details.get(\"request\").get(\"udf_fields\").get(\"udf_sline_3019\")\r\n )\r\n notification_title = (\r\n f\"Yêu cầu chờ phê duyệt {request_id} từ hotrocntt.cpc.vn\"\r\n )\r\n notification_description = f\"\"\"\r\n {requester_name} gửi cho bạn có một yêu cầu phê duyệt có nội dung nội dung:
\r\n - Phê duyệt khởi tạo cấu hình {request_template.upper()}
\r\n - Tiêu đề: {request_subject}
\r\n - Chi tiết cấu hình:
https://nssa.cpc.vn/servicedesk/{request_template}/{request_id} \r\n - Lời nhắn: {message}
\r\n Thông tin người yêu cầu:
\r\n - Email: {requester_email}
\r\n - Mobile: {requester_mobile}
\r\n\r\n Anh/Chị vui lòng truy cập link sau để xem chi tiết và thực hiện phê duyệt:
Phê Duyệt \r\n
\"\"\"\r\n input_data = {\r\n \"approvals\": [\r\n {\"approver\": {\"id\": approver}} for approver in approver_id\r\n ],\r\n \"notification\": {\r\n \"title\": notification_title,\r\n \"description\": notification_description,\r\n },\r\n }\r\n payload = \"input_data=\" + urllib.parse.quote(json.dumps(input_data))\r\n headers = {\r\n \"Accept\": \"vnd.manageengine.v3+json\",\r\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\r\n \"authtoken\": \"564C437D-62C0-4458-8B16-53847F2EEAD9\",\r\n }\r\n url = f\"https://{self.url}/api/v3/requests/{request_id}/submit_for_approval\"\r\n response = requests.request(\"POST\", url, headers=headers, data=payload)\r\n response.raise_for_status()\r\n return response.json()\r\n except requests.exceptions as e:\r\n return e\r\n\r\n def get_request_approval_status(self,request_id) -> dict:\r\n request_details = self.get_requests(request_id=request_id)\r\n if type(request_details) is not dict:\r\n return {\"code\": 0, \"message\": \"Exception occurs during get request information from hotrocntt.cpc.vn\"}\r\n return {\"code\": 1, \"message\": request_details.get(\"request\").get(\"approval_status\")}\r\n\r\n def check_request_is_valid(self,request_id,request_template=None) -> dict:\r\n request_details = self.get_requests(request_id=request_id)\r\n if type(request_details) is not dict:\r\n return {\"code\": 0, \"message\": \"Exception occurs during get request information from hotrocntt.cpc.vn\"}\r\n if request_details.get(\"response_status\").get(\"status_code\") == 4000:\r\n return False\r\n if request_details.get(\"response_status\").get(\"status_code\") == 2000:\r\n if request_details.get(\"request\").get(\"udf_fields\") is None:\r\n return False\r\n if request_details.get(\"request\").get(\"udf_fields\").get(\"udf_sline_3019\") is None:\r\n return False\r\n if request_details.get(\"request\").get(\"udf_fields\").get(\"udf_sline_3019\") not in [\"citrix\",\"firewall\"]:\r\n return False\r\n if request_template is not None:\r\n if request_details.get(\"request\").get(\"udf_fields\").get(\"udf_sline_3019\") != request_template:\r\n return False\r\n return True\r\n return False\r\n\r\n ","repo_name":"anhtuan206/ServiceDeskForm","sub_path":"ServiceDeskForm/application/api/manage_engine.py","file_name":"manage_engine.py","file_ext":"py","file_size_in_byte":10307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"23373492739","text":"import os\nfrom os.path import join\nimport utils\nfrom buildercore import core, project, config\nfrom buildercore.utils import first, remove_ordereddict, errcho, lfilter, lmap, isstr\nfrom functools import wraps\nfrom pprint import pformat\nimport logging\n\nLOG = logging.getLogger(__name__)\n\nfrom time import time\n\n# http://stackoverflow.com/questions/1622943/timeit-versus-timing-decorator\ndef timeit(fn):\n @wraps(fn)\n def wrap(*args, **kw):\n ts = time()\n result = fn(*args, **kw)\n te = time()\n LOG.info('func:%r args:[%r, %r] took: %2.4f sec',\n fn.__name__, args, kw, te - ts)\n return result\n return wrap\n\ndef deffile(fname):\n \"returns the proper path to the given default file\"\n return join(config.TEMP_PATH, fname)\n\ndef setdefault(fname, value):\n \"writes the given value to the given default file\"\n open(deffile(fname), 'w').write(value)\n\ndef requires_filtered_project(filterfn=None):\n def wrap1(func):\n @wraps(func)\n def wrap2(_pname=None, *args, **kwargs):\n pname = os.environ.get('PROJECT', _pname) # used by Vagrant ...?\n project_list = project.filtered_projects(filterfn)\n if not pname or not pname.strip() or pname not in project_list:\n pname = utils._pick(\"project\", sorted(project_list), default_file=deffile('.project'))\n return func(pname, *args, **kwargs)\n return wrap2\n return wrap1\n\n# pylint: disable=invalid-name\nrequires_project = requires_filtered_project(None)\n\ndef requires_aws_project_stack(*plist):\n if not plist:\n plist = [utils._pick(\"project\", project.project_list(), default_file=deffile('.project'))]\n\n def wrap1(func):\n @wraps(func)\n def _wrapper(stackname=None, *args, **kwargs):\n region = utils.find_region(stackname)\n asl = core.active_stack_names(region)\n if not asl:\n print('\\nno AWS stacks exist, cannot continue.')\n return\n\n def pname_startswith(stack):\n for pname in plist:\n if stack.startswith(pname):\n return stack\n asl = lfilter(pname_startswith, asl)\n if not stackname or stackname not in asl:\n stackname = utils._pick(\"stack\", asl)\n return func(stackname, *args, **kwargs)\n return _wrapper\n return wrap1\n\ndef requires_aws_stack(func):\n @wraps(func)\n def call(*args, **kwargs):\n stackname = first(args) or os.environ.get('INSTANCE')\n region = utils.find_region(stackname)\n if stackname:\n args = args[1:]\n return func(stackname, *args, **kwargs)\n asl = core.active_stack_names(region)\n if not asl:\n raise RuntimeError('\\nno AWS stacks *in an active state* exist, cannot continue.')\n if not stackname or stackname not in asl:\n stackname = utils._pick(\"stack\", asl, default_file=deffile('.active-stack'))\n args = args[1:]\n return func(stackname, *args, **kwargs)\n return call\n\ndef requires_steady_stack(func):\n @wraps(func)\n def call(*args, **kwargs):\n ss = core.steady_aws_stacks(utils.find_region())\n keys = lmap(first, ss)\n idx = dict(zip(keys, ss))\n helpfn = lambda pick: idx[pick][1]\n if not keys:\n print('\\nno AWS stacks *in a steady state* exist, cannot continue.')\n return\n stackname = first(args) or os.environ.get('INSTANCE')\n if not stackname or stackname not in keys:\n stackname = utils._pick(\"stack\", sorted(keys), helpfn=helpfn, default_file=deffile('.active-stack'))\n return func(stackname, *args[1:], **kwargs)\n return call\n\ndef echo_output(func):\n \"pretty-prints the return value of the task(s) being run to stdout\"\n @wraps(func)\n def _wrapper(*args, **kwargs):\n res = func(*args, **kwargs)\n errcho('output:') # printing to stderr avoids corrupting structured data\n if isstr(res):\n print(res)\n else:\n print(pformat(remove_ordereddict(res)))\n return res\n return _wrapper\n","repo_name":"muzyk10/builder","sub_path":"src/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":4170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"77"}
+{"seq_id":"16421567028","text":"import regex as re\nfrom collections import Counter\nfrom gensim.models import Word2Vec\n\n\nFLAGS = re.MULTILINE | re.DOTALL\n\n\ndef get_class_weights(y):\n counter = Counter(y)\n majority = max(counter.values())\n return {cls: float(majority/count) for cls, count in counter.items()}\n\n\ndef clean_str(txt):\n \"\"\"\n Tokenization/string cleaning for dataset\n Every dataset is lower cased except\n \"\"\"\n # FLAGS = re.MULTILINE | re.DOTALL\n txt = str(txt)\n txt = txt.strip().lower()\n txt = re.sub(r\"\\\\\", \"\", txt, flags=FLAGS)\n txt = re.sub(r\"\\'\", \"\", txt, flags=FLAGS)\n txt = re.sub(r\"\\\"\", \"\", txt, flags=FLAGS)\n txt = re.sub(r\"\\r\", \" \", txt, flags=FLAGS)\n txt = re.sub(r\"\\n\", \" \", txt, flags=FLAGS)\n txt = re.sub(r\">\", \" \", txt, flags=FLAGS)\n txt = re.sub(r\"<\", \" \", txt, flags=FLAGS)\n # txt = re.sub(r':)', \"EMOSMILE\", txt, flags=FLAGS)\n txt = re.sub(r\"[0-9]+\", \"NUMBERS\", txt, flags=FLAGS)\n txt = re.sub(r\"[ ]+\", \" \", txt, flags=FLAGS)\n txt = re.sub(r'(.)\\1{2,}', r'\\1\\1', txt, flags=FLAGS)\n txt = re.sub(r'http\\S+', 'URL', txt, flags=FLAGS)\n return txt\n\n\ndef remove_nb(txt):\n \"\"\"\n Tokenization/string cleaning for dataset\n Every dataset is lower cased except\n \"\"\"\n # FLAGS = re.MULTILINE | re.DOTALL\n txt = str(txt)\n txt = re.sub(r\"[0-9]+\", \"numbers\", txt, flags=FLAGS)\n return txt\n\n\ndef hashtag(text):\n text = text.group()\n hashtag_body = text[1:]\n if hashtag_body.isupper():\n result = \" {} \".format(hashtag_body.lower())\n else:\n result = \" \".join([\"\"] + re.split(r\"(?=[A-Z])\", hashtag_body, flags=FLAGS))\n return result\n\n\ndef allcaps(text):\n text = text.group()\n return text.lower() + \" \"\n\n\ndef tweet_preprocess(text):\n # Different regex parts for smiley faces\n eyes = r\"[8:=;]\"\n nose = r\"['`\\-]?\"\n\n # function so code less repetitive\n def re_sub(pattern, repl):\n return re.sub(pattern, repl, text, flags=FLAGS)\n\n text = re_sub(r\"https?:\\/\\/\\S+\\b|www\\.(\\w+\\.)+\\S*\", \"\")\n text = re_sub(r\"@\\w+\", \"\")\n text = re_sub(r\"{}{}[)dD]+|[)dD]+{}{}\".format(eyes, nose, nose, eyes), \"\")\n text = re_sub(r\"{}{}p+\".format(eyes, nose), \"\")\n text = re_sub(r\"{}{}\\(+|\\)+{}{}\".format(eyes, nose, nose, eyes), \"\")\n text = re_sub(r\"{}{}[\\/|l*]\".format(eyes, nose), \"\")\n text = re_sub(r\"/\", \" / \")\n text = re_sub(r\"<3\", \"\")\n # text = re_sub(r\"RT \", \"\")\n text = re_sub(r\"[-+]?[.\\d]*[\\d]+[:,.\\d]*\", \"\")\n text = re_sub(r\"#\\S+\", hashtag)\n text = re_sub(r\"([!?.]){2,}\", r\"\\1 \")\n text = re_sub(r\"\\b(\\S*?)(.)\\2{2,}\\b\", r\"\\1\\2 \")\n text = re_sub(r\"\\n\", r\" \")\n text = re_sub(r\"\\s+\", r\" \")\n # text = text.translate(str.maketrans('', '', string.punctuation))\n\n # -- I just don't understand why the Ruby script adds to everything so I limited the selection.\n # text = re_sub(r\"([^a-z0-9()<>'`\\-]){2,}\", allcaps)\n text = re_sub(r\"([A-Z]){2,}\", allcaps)\n\n return text.lower()\n\n\ndef remove_dot(text):\n def re_sub(pattern, repl):\n return re.sub(pattern, repl, text, flags=FLAGS)\n\n text = re_sub(r\".+\", r\".\")\n text = re_sub(r\"?+\", r\"?\")\n text = re_sub(r\">\", r\">\")\n text = re_sub(r\"<\", r\"<\")\n\n return text\n\n\n# cleaning master function\ndef clean_tweet(tweet):\n my_punctuation = '!\"$%&\\'()*+,-./:;<=>?[\\\\]^_`–‘{|}~•@…“”’'\n eyes = r\"[8:=;]\"\n nose = r\"['`\\-]?\"\n tweet = tweet.lower() # lower case\n tweet = re.sub(r\">\", r\" \", tweet)\n tweet = re.sub(r\"<\", r\" \", tweet)\n tweet = re.sub(r\"&\", r\" \", tweet)\n tweet = re.sub(r\"\\u200d\", r\" \", tweet)\n tweet = re.sub(r\"{}{}[)dD]+|[)dD]+{}{}\".format(eyes, nose, nose, eyes), \" smile \", tweet)\n tweet = re.sub(r\"{}{}p+\".format(eyes, nose), \" lolface \", tweet)\n tweet = re.sub(r\"{}{}\\(+|\\)+{}{}\".format(eyes, nose, nose, eyes), \" sadface \", tweet)\n tweet = re.sub(r\"{}{}[\\/|l*]\".format(eyes, nose), \" neutralface \", tweet)\n tweet = re.sub(r\"<3\", \" heart \", tweet)\n tweet = re.sub(r\"[0-9]+\", \"numbers\", tweet)\n tweet = re.sub('[' + my_punctuation + ']+', ' ', tweet) # strip punctuation\n tweet = re.sub('\\s+', ' ', tweet) # remove double spacing\n tweet = tweet.strip()\n return tweet\n\n\n'''# cleaning master function\ndef clean_tweet(tweet):\n my_punctuation = '!\"$%&\\'()*+,-./:;<=>?[\\\\]^_`–‘{|}\\\\\\\\~•@…“”’♂'\n eyes = r\"[8:=;]\"\n nose = r\"['`\\-]?\"\n tweet = tweet.lower() # lower case\n tweet = re.sub(r\">\", r\" \", tweet)\n tweet = re.sub(r\"<\", r\" \", tweet)\n tweet = re.sub(r\"&\", r\" \", tweet)\n tweet = re.sub(r\"\\u200d\", r\" \", tweet)\n tweet = re.sub(r\"[0-9]+\", \"numbers\", tweet)\n tweet = re.sub(r\"{}{}[)dD]+|[)dD]+{}{}\".format(eyes, nose, nose, eyes), \" smile \", tweet)\n tweet = re.sub(r\"{}{}p+\".format(eyes, nose), \" lolface \", tweet)\n tweet = re.sub(r\"{}{}\\(+|\\)+{}{}\".format(eyes, nose, nose, eyes), \" sadface \", tweet)\n tweet = re.sub(r\"{}{}[\\/|l*]\".format(eyes, nose), \" neutralface \", tweet)\n tweet = re.sub(r\"<3\", \" heart \", tweet)\n tweet = re.sub('[' + my_punctuation + ']+', ' ', tweet) # strip punctuation\n tweet = re.sub('\\s+', ' ', tweet) # remove double spacing\n tweet = tweet.strip()\n return tweet\n'''\n\n\n'''my_punctuation = '!\"$%&\\'()*+,-./:;<=>?[\\\\]^_`{|}~•@…“”’♂'\n\n# cleaning master function\ndef clean_tweet(tweet):\n eyes = r\"[8:=;]\"\n nose = r\"['`\\-]?\"\n tweet = tweet.lower() # lower case\n tweet = re.sub(r\">\", r\" \", tweet)\n tweet = re.sub(r\"<\", r\" \", tweet)\n tweet = re.sub(r\"&\", r\" \", tweet)\n tweet = re.sub(r\"\\u200d\", r\" \", tweet)\n tweet = re.sub(r\"[0-9]+\", \"numbers\", tweet)\n tweet = re.sub(r\"{}{}[)dD]+|[)dD]+{}{}\".format(eyes, nose, nose, eyes), \"smile\", tweet)\n tweet = re.sub(r\"{}{}p+\".format(eyes, nose), \"lolface\", tweet)\n tweet = re.sub(r\"{}{}\\(+|\\)+{}{}\".format(eyes, nose, nose, eyes), \"sadface\", tweet)\n tweet = re.sub(r\"{}{}[\\/|l*]\".format(eyes, nose), \"neutralface\", tweet)\n tweet = re.sub(r\"<3\", \"heart\", tweet)\n tweet = re.sub('['+ my_punctuation + ']+', ' ', tweet) # strip punctuation\n tweet = re.sub('\\s+', ' ', tweet) # remove double spacing\n tweet = tweet.strip()\n\n return tweet\n'''\n\n\ndef load_w2v():\n return Word2Vec.load('../data/w2v.model')\n","repo_name":"MATvipMAX/twitterML","sub_path":"test/utils2/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"69820917050","text":"from IPython import display\nfrom matplotlib import pyplot as plt\nfrom mxnet import autograd, nd\nimport random\n\nnum_inputs = 2\nnum_examples = 1000\n# 特征真实值\ntrue_w = [2, -3.4]\ntrue_b = 4.2\n\n# 特征服从正太分布\nfeatures = nd.random.normal(scale=1, shape=(num_examples, num_inputs))\n\n# 特征真实值\nlabels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b\nlabels += nd.random.normal(scale=0.01, shape=labels.shape)\n\nprint(features[0], labels[0])\n\n\ndef use_svg_display():\n # 用矢量图显示\n display.set_matplotlib_formats('svg')\n\n\ndef set_figsize(figsize=(3.5, 2.5)):\n use_svg_display()\n # 设置图的尺寸\n plt.rcParams['figure.figsize'] = figsize\n\n\n# set_figsize()\n\nprint(features[:, 1].asnumpy()[0:5])\nprint(labels.asnumpy()[0:5])\n\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.scatter(features[:, 1].asnumpy(), labels.asnumpy())\nplt.show()\n\n\n# plt.scatter(features[:, 1].asnumpy(), labels.asnumpy()); # 加分号只显示图\n","repo_name":"exueyuan/Mxnetdemo","sub_path":"03深度学习基础/02线性回归的从0开始实现.py","file_name":"02线性回归的从0开始实现.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"46846629156","text":"from django.shortcuts import render, get_object_or_404\nfrom .models import Product\nfrom category.models import Category\n\n# Create your views here.\ndef store(request, category_slug=None):\n category = None\n products = None\n\n if category_slug is not None:\n category = get_object_or_404(Category, slug=category_slug)\n products = Product.objects.filter(category=category, is_available=True)\n else:\n products = Product.objects.all().filter(is_available=True)\n\n product_count = products.count()\n\n context = {\n 'products' : products,\n 'product_count' : product_count,\n }\n\n return render(request, 'store/store.html', context)\n\ndef product_detail(request, category_slug=None, product_slug=None):\n category = get_object_or_404(Category, slug=category_slug)\n try:\n # Fetch single query\n product = Product.objects.get(category=category, slug=product_slug)\n except Exception as e:\n raise e\n\n # print(product.product_name)\n # print(product.price)\n\n context = {\n 'product' : product,\n }\n\n return render(request, 'store/product_detail.html', context)","repo_name":"Jatin-1602/ShoppingSite","sub_path":"store/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"36885209410","text":"import paraview\nfrom paraview.simple import *\n\n# This script tests backwards compatibility for the Slice filter.\n# Replaces MergePoints property with Locator one\n\nparaview.compatibility.major = 5\nparaview.compatibility.minor = 11\n\nwavelet = Wavelet()\n\nsliceFilter = Slice(Input=wavelet)\nassert(sliceFilter.MergePoints == 1)\nassert(sliceFilter.GetProperty(\"Locator\").GetData().SMProxy.GetXMLLabel() == \"Uniform Binning\")\n\nsliceFilter.MergePoints = 0\nassert(sliceFilter.MergePoints == 0)\nassert(sliceFilter.GetProperty(\"Locator\").GetData().SMProxy.GetXMLLabel() == \"Not Merging Points\")\n","repo_name":"Kitware/ParaView","sub_path":"Remoting/Application/Testing/Python/SliceBackwardsCompatibilityTest.py","file_name":"SliceBackwardsCompatibilityTest.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":1099,"dataset":"github-code","pt":"77"}
+{"seq_id":"29216780608","text":"import numpy as np\nimport logging\n\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\nclass PrecisionRecallFk:\n \"\"\"\n Calculate precision, recall, f1 for predictions.\n \"\"\"\n\n def __init__(self, enable_logger=False, threshold=0.5, eps=1e-9):\n if enable_logger:\n global logger\n self.logger = logger\n\n self.threshold = threshold\n self.eps = eps\n\n def __call__(self,\n prediction: np.array,\n ground_truth: np.array,\n betas: list = [1],\n top_ks: list = None) -> (float, float, float):\n \"\"\"\n compute F-beta score\n\n input:\n + prediction: predictions of model, np.array of shape [B, N] with B be the batchsize\n and N is the number of classes\n + ground_truth: self explanatory, must have the same shape as prediction\n + betas: a list of betas\n + top_ks: if specified, compute f_score of top_k most confident prediction\n output:\n + f_score: (1+beta**2) * precision*recall/(beta**2 * precision+recall)\n \"\"\"\n if top_ks is None:\n return self.f_k_score(prediction,\n ground_truth,\n betas)\n else:\n return self.f_k_score_top(prediction,\n ground_truth,\n betas,\n top_ks)\n\n def f_k_score(self,\n prediction: np.array,\n ground_truth: np.array,\n betas: list = [1],\n threshold: float = None):\n \"\"\"\n compute F-beta score\n\n input:\n + prediction: unthresholded output of the model, np.array of shape [B, N] with B be the \n batchsize and N is the number of classes\n + ground_truth: self explanatory, must have the same shape as prediction\n + betas: a list of betas\n output:\n + f_scores: (1+beta**2) * precision*recall/(beta**2 * precision+recall)\n \"\"\"\n assert prediction.shape == ground_truth.shape\n\n if threshold is None:\n prediction = prediction >= self.threshold\n else:\n prediction = (prediction >= threshold)\n\n prediction = prediction.astype(int)\n\n ground_truth = ground_truth.reshape(prediction.shape)\n num_prediction = np.count_nonzero(prediction, axis=1)\n num_ground_truth = np.count_nonzero(ground_truth, axis=1)\n\n if hasattr(self, \"logger\"):\n self.logger.info(\n \"Predictions per item: {}, Labels per item: {}\".format(np.mean(num_prediction),\n np.mean(num_ground_truth))\n )\n\n num_true_positive_pred = np.count_nonzero(\n ground_truth & prediction, axis=1)\n\n precision = num_true_positive_pred/num_prediction + self.eps\n recall = num_true_positive_pred/num_ground_truth + self.eps\n\n f_scores = {}\n for beta in betas:\n beta_squared = beta ** 2\n f_score = np.nan_to_num(\n (1 + beta_squared)*precision*recall / (beta_squared * precision+recall))\n f_scores[\"F{}\".format(beta)] = np.nanmean(f_score)\n\n if hasattr(self, \"logger\"):\n self.logger.info(\n \"Can't give predictions to {} items\".format(\n np.count_nonzero(np.isnan(precision)))\n )\n\n return {\"precision\": np.nanmean(precision), \"recall\": np.nanmean(recall), \"f_score\": f_scores}\n\n def f_k_score_top(self,\n prediction: np.array,\n ground_truth: np.array,\n betas: list,\n top_ks: list):\n \"\"\"\n compute F-beta score\n\n input:\n + prediction: unthresholded output of the model, np.array of shape [B, N] with B be the \n batchsize and N is the number of classes\n + ground_truth: self explanatory, must have the same shape as prediction\n + betas: a list of betas\n + top_ks: list of top_ks to compute the f_score\n output:\n + f_scores: (1+beta**2) * precision*recall/(beta**2 * precision+recall)\n \"\"\"\n\n assert len(top_ks) > 0, \"please specify top_k\"\n\n outputs = {}\n\n for top_k in top_ks:\n # compute threshold for every top_k\n k_indices = np.argsort(prediction)[:, ::-1][:, top_k - 1]\n\n k_thresh = prediction[[range(len(k_indices)), k_indices]]\n k_thresh = k_thresh[..., np.newaxis]\n outputs[\"top_{}\".format(top_k)] = self.f_k_score(\n prediction, ground_truth, betas, k_thresh)\n\n return outputs\n","repo_name":"pixta-dev/labteam","sub_path":"MAGNeto/magneto/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":4867,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"77"}
+{"seq_id":"27464818650","text":"from PIL import Image\n# mac = Image.open('images/example.jpg')\n# # Note this is a specialized file type from PIL (pillow)\n# print(type(mac))\n# # mac.show()\n\n# # (width, height)\n# print(mac.size)\n# print(mac.filename)\n# print(mac.format_description)\n\n# mac_new = mac.crop((0,0,100,100))\n# print(mac_new)\n\n# pencils = Image.open(\"images/pencils.jpg\")\n\n# print(pencils.size)\n# # pencils.show()\n\n\n# pencils.size\n\n# # Start at top corner (0,0)\n# x = 0\n# y = 0\n# # Grab about 10% in y direction , and about 30% in x direction\n# w = 1950/3\n# h = 1300/10\n\n# pencils_new = pencils.crop((x,y,w,h))\n# # pencils.show()\n# print(pencils_new.size)\n# pencils_new.save('pencils_new.png')\n\n\n\n\n# computer = mac.crop((x,y,w,h))\n\n# mac.paste(im=computer,box=(0,0))\n\n# mac.show()\n\n# mac.paste(im=computer,box=(796,0))\n\n# mac.save()\n\n\n\n\n\n\n# mac.size\n\n# h,w = mac.size\n\n# new_h = int(h/3)\n# new_w = int(w/3)\n\n# # Note this is not permanent change\n# # for permanent change, do a reassignment\n# # e.g. mac = mac.resize((100,100))\n# mac.resize((new_h,new_w))\n\n\n\nred = Image.open('images/red_color.jpg')\nred.show()\nblue = Image.open('images/purple.png')\n# blue.show()\nred.putalpha(128)\n# red.show()\nblue.putalpha(128)\n# blue.show()\nblue.paste(red,box=(0,0),mask=red)\n\n# Get back an image that is more purple.\n# blue.show()\n\nblue.save('new_purple.png')","repo_name":"cddolanc/cct-start","sub_path":"Sem2/Sem2wk5.py","file_name":"Sem2wk5.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"360583026","text":"import json\nimport os\nimport time\nimport threading\n\nfrom testflows.core import *\nfrom testflows.asserts import error\n# from testflows.connect import Shell\n\n# import e2e.settings as settings\nimport e2e.yaml_manifest as yaml_manifest\nimport e2e.util as util\n\ncurrent_dir = os.path.dirname(os.path.abspath(__file__))\nmax_retries = 20\n\n\ndef launch(command, ok_to_fail=False, ns=None, timeout=600, shell=None):\n # Build commanddef launch\n\n if ns is None:\n if hasattr(current().context, \"test_namespace\"):\n ns = current().context.test_namespace\n\n cmd = f\"{current().context.kubectl_cmd} \"\n cmd_args = command.split(\" \")\n if ns is not None and ns != \"\" and ns != \"--all-namespaces\":\n cmd += f\"{cmd_args[0]} --namespace={ns} \"\n elif ns == \"--all-namespaces\":\n cmd += f\"{cmd_args[0]} {ns} \"\n else:\n cmd += f\"{cmd_args[0]} \"\n\n if len(cmd_args) > 1:\n cmd += \" \".join(cmd_args[1:])\n\n # save command for debug purposes\n # command = cmd\n # print(f\"run command: {cmd}\")\n\n return run_shell(cmd, timeout, ok_to_fail, shell=shell)\n\n\ndef run_shell(cmd, timeout=600, ok_to_fail=False, shell=None):\n # Run command\n\n if shell is None:\n res_cmd = current().context.shell(cmd, timeout=timeout)\n else:\n res_cmd = shell(cmd, timeout=timeout)\n\n # Check command failure\n code = res_cmd.exitcode\n if not ok_to_fail:\n if code != 0:\n print(f\"command failed, command:\\n{cmd}\")\n print(f\"command failed, exit code:\\n{code}\")\n print(f\"command failed, output :\\n{res_cmd.output}\")\n assert code == 0, error()\n # Command test result\n return res_cmd.output if (code == 0) or ok_to_fail else \"\"\n\n\ndef delete_chi(chi, ns=None, wait=True, ok_to_fail=False, shell=None):\n with When(f\"Delete chi {chi}\"):\n launch(\n f\"delete chi {chi} -v 5 --now --timeout=600s\",\n ns=ns,\n timeout=600,\n ok_to_fail=ok_to_fail,\n shell=shell\n )\n if wait:\n wait_objects(\n chi,\n {\n \"statefulset\": 0,\n \"pod\": 0,\n \"service\": 0,\n },\n ns,\n shell=shell\n )\n\n\ndef delete_all_chi(ns=None):\n crds = launch(\"get crds -o=custom-columns=name:.metadata.name\", ns=ns).splitlines()\n if \"clickhouseinstallations.clickhouse.altinity.com\" in crds:\n try:\n chis = get(\"chi\", \"\", ns=ns, ok_to_fail=True)\n except Exception:\n chis = {}\n if \"items\" in chis:\n for chi in chis[\"items\"]:\n # kubectl(f\"patch chi {chi} --type=merge -p '\\{\\\"metadata\\\":\\{\\\"finalizers\\\": [null]\\}\\}'\", ns = ns)\n delete_chi(chi[\"metadata\"][\"name\"], ns)\n\n\ndef delete_all_keeper(ns=None):\n for keeper_type in (\"zookeeper-operator\", \"zookeeper\", \"clickhouse-keeper\"):\n expected_resource_types = (\n (\"zookeepercluster\",) if keeper_type == \"zookeeper-operator\" else (\"sts\", \"pvc\", \"cm\", \"svc\")\n )\n for resource_type in expected_resource_types:\n try:\n item_list = get(\n resource_type,\n \"\",\n label=f\"-l app={keeper_type}\",\n ns=ns,\n ok_to_fail=True,\n )\n except Exception as e:\n item_list = {}\n if \"items\" in item_list:\n for item in item_list[\"items\"]:\n name = item[\"metadata\"][\"name\"]\n launch(f\"delete {resource_type} -n {current().context.test_namespace} {name}\", ok_to_fail=True)\n\n\ndef create_and_check(manifest, check, ns=None, shell=None, timeout=900):\n chi_name = yaml_manifest.get_chi_name(util.get_full_path(f\"{manifest}\"))\n\n # state_field = \".status.taskID\"\n # prev_state = get_field(\"chi\", chi_name, state_field, ns)\n\n if \"apply_templates\" in check:\n debug(\"Need to apply additional templates\")\n for t in check[\"apply_templates\"]:\n debug(f\"Applying template: {util.get_full_path(t, False)} \\n{t}\")\n apply(util.get_full_path(t, False), ns=ns, shell=shell)\n time.sleep(5)\n\n apply_chi(util.get_full_path(manifest, False), ns=ns, timeout=timeout, shell=shell)\n\n # Wait for reconcile to start before performing other checks. In some cases it does not start, so we can pass\n # wait_field_changed(\"chi\", chi_name, state_field, prev_state, ns)\n wait_chi_status(chi_name, \"InProgress\", ns=ns, retries=3, throw_error=False, shell=shell)\n\n if \"chi_status\" in check:\n wait_chi_status(chi_name, check[\"chi_status\"], ns=ns, shell=shell)\n else:\n wait_chi_status(chi_name, \"Completed\", ns=ns, shell=shell)\n\n if \"object_counts\" in check:\n wait_objects(chi_name, check[\"object_counts\"], ns=ns, shell=shell)\n\n if \"pod_count\" in check:\n wait_object(\n \"pod\",\n \"\",\n label=f\"-l clickhouse.altinity.com/chi={chi_name}\",\n count=check[\"pod_count\"],\n ns=ns,\n shell=shell\n )\n\n if \"pod_image\" in check:\n check_pod_image(chi_name, check[\"pod_image\"], ns=ns, shell=shell)\n\n if \"pod_volumes\" in check:\n check_pod_volumes(chi_name, check[\"pod_volumes\"], ns=ns, shell=shell)\n\n if \"pod_podAntiAffinity\" in check:\n check_pod_antiaffinity(chi_name, ns=ns, shell=shell)\n\n if \"pod_ports\" in check:\n check_pod_ports(chi_name, check[\"pod_ports\"], ns=ns, shell=shell)\n\n if \"service\" in check:\n check_service(check[\"service\"][0], check[\"service\"][1], ns=ns, shell=shell)\n\n if \"configmaps\" in check:\n check_configmaps(chi_name, ns=ns, shell=shell)\n\n if \"pdb\" in check:\n check_pdb(chi_name, check[\"pdb\"], ns=ns, shell=shell)\n\n if \"do_not_delete\" not in check:\n delete_chi(chi_name, ns=ns, shell=shell)\n\n\ndef get(kind, name, label=\"\", ns=None, ok_to_fail=False, shell=None):\n out = launch(f\"get {kind} {name} {label} -o json\", ns=ns, ok_to_fail=ok_to_fail, shell=shell)\n return json.loads(out.strip())\n\n\ndef create_ns(ns):\n if ns is None:\n launch(f\"create ns {current().context.test_namespace}\", ns=None)\n launch(f\"get ns {current().context.test_namespace}\", ns=None)\n else:\n launch(f\"create ns {ns}\", ns=None)\n launch(f\"get ns {ns}\", ns=None)\n\n\ndef delete_ns(ns = None, delete_chi=False, ok_to_fail=False, timeout=1000):\n if ns == None:\n ns = current().context.test_namespace\n if delete_chi:\n delete_all_chi(ns)\n launch(\n f\"delete ns {ns} -v 5 --now --timeout={timeout}s\",\n ns=None,\n ok_to_fail=ok_to_fail,\n timeout=timeout,\n )\n for attempt in retries(timeout=300, delay=10):\n with attempt:\n out = launch(f\"get namespace {ns}\", ok_to_fail=True)\n assert \"Error\" in out\n\n\ndef get_count(kind, name=\"\", label=\"\", chi=\"\", ns=None, shell=None):\n if chi != \"\" and label == \"\":\n label = f\"-l clickhouse.altinity.com/chi={chi}\"\n\n if kind == \"pv\":\n # pv is not namespaced so need to search namespace in claimRef\n out = launch(f'get pv {label} -o yaml | grep \"namespace: {current().context.test_namespace}\"', ok_to_fail=True, shell=shell)\n else:\n out = launch(\n f\"get {kind} {name} -o=custom-columns=kind:kind,name:.metadata.name {label}\",\n ns=ns,\n ok_to_fail=True,\n shell=shell\n )\n\n if (out is None) or (len(out) == 0):\n return 0\n else:\n return len(out.splitlines()) - 1\n\n\ndef count_objects(label=\"\", ns=None, shell=None):\n return {\n \"statefulset\": get_count(\"sts\", ns=ns, label=label, shell=shell),\n \"pod\": get_count(\"pod\", ns=ns, label=label, shell=shell),\n \"service\": get_count(\"service\", ns=ns, label=label, shell=shell),\n }\n\n\ndef apply(manifest, ns=None, validate=True, timeout=600, shell=None):\n for attempt in retries(timeout=500, delay=1):\n with attempt:\n with When(f\"{manifest} is applied\"):\n if \" | \" not in manifest:\n manifest = f'\"{manifest}\"'\n launch(f\"apply --validate={validate} -f {manifest}\", ns=ns, timeout=timeout, shell=shell)\n else:\n run_shell(\n f\"set -o pipefail && {manifest} | {current().context.kubectl_cmd} apply --namespace={current().context.test_namespace} --validate={validate} -f -\",\n timeout=timeout,\n shell=shell\n )\n\n\ndef apply_chi(manifest, ns=None, validate=True, timeout=600, shell=None):\n if ns is None:\n ns = current().context.test_namespace\n chi_name = yaml_manifest.get_chi_name(manifest)\n with When(f\"CHI {chi_name} is applied\"):\n if current().context.kubectl_mode == \"replace\":\n if get_count(\"chi\", chi_name, ns=ns) == 0:\n create(manifest, ns=ns, validate=validate, timeout=timeout)\n else:\n replace(manifest, ns=ns, validate=validate, timeout=timeout)\n else:\n apply(manifest, ns=ns, validate=validate, timeout=timeout, shell=shell)\n\n\ndef create(manifest, ns=None, validate=True, timeout=600):\n with When(f\"{manifest} is created\"):\n if \"<(\" not in manifest:\n manifest = f'\"{manifest}\"'\n launch(f\"create --validate={validate} -f {manifest}\", ns=ns, timeout=timeout)\n\n\ndef replace(manifest, ns=None, validate=True, timeout=600):\n with When(f\"{manifest} is replaced\"):\n if \"<(\" not in manifest:\n manifest = f'\"{manifest}\"'\n launch(f\"replace --validate={validate} -f {manifest}\", ns=ns, timeout=timeout)\n\n\ndef delete(manifest, ns=None, timeout=600):\n with When(f\"{manifest} is deleted\"):\n if \" | \" not in manifest:\n manifest = f'\"{manifest}\"'\n return launch(f\"delete -f {manifest}\", ns=ns, timeout=timeout)\n else:\n run_shell(f\"{manifest} | {current().context.kubectl_cmd} delete -f -\", timeout=timeout)\n\n\ndef wait_objects(chi, object_counts, ns=None, shell=None, retries = max_retries):\n with Then(\n f\"Waiting for: \"\n f\"{object_counts['statefulset']} statefulsets, \"\n f\"{object_counts['pod']} pods and \"\n f\"{object_counts['service']} services \"\n f\"to be available\"\n ):\n for i in range(1, retries):\n cur_object_counts = count_objects(label=f\"-l clickhouse.altinity.com/chi={chi}\", ns=ns, shell=shell)\n if cur_object_counts == object_counts:\n break\n with Then(\n f\"Not ready yet. [ \"\n f\"statefulset: {cur_object_counts['statefulset']} \"\n f\"pod: {cur_object_counts['pod']} \"\n f\"service: {cur_object_counts['service']} ]. \"\n f\"Wait for {i * 5} seconds\"\n ):\n time.sleep(i * 5)\n assert cur_object_counts == object_counts, error()\n\n\ndef wait_object(kind, name, label=\"\", count=1, ns=None, retries=max_retries, backoff=5, shell=None):\n with Then(f\"{count} {kind}(s) {name} should be created\"):\n for i in range(1, retries):\n cur_count = get_count(kind, ns=ns, name=name, label=label, shell=shell)\n if cur_count >= count:\n break\n with Then(f\"Not ready yet. {cur_count}/{count}. Wait for {i * backoff} seconds\"):\n time.sleep(i * backoff)\n assert cur_count >= count, error()\n\n\ndef wait_command(command, result, count=1, ns=None, retries=max_retries):\n with Then(f\"{command} should return {result}\"):\n for i in range(1, retries):\n res = launch(command, ok_to_fail=True, ns=ns)\n if res == result:\n break\n with Then(\"Not ready. Wait for \" + str(i * 5) + \" seconds\"):\n time.sleep(i * 5)\n assert res == result, error()\n\n\ndef wait_chi_status(chi, status, ns=None, retries=max_retries, throw_error=True, shell=None):\n wait_field(\"chi\", chi, \".status.status\", status, ns, retries, throw_error=throw_error, shell=shell)\n\n\ndef get_chi_status(chi, ns=None):\n get_field(\"chi\", chi, \".status.status\", ns)\n\n\ndef wait_pod_status(pod, status,shell=None, ns=None):\n wait_field(\"pod\", pod, \".status.phase\", status, ns, shell=shell)\n\n\ndef wait_container_status(pod, status, ns=None):\n wait_field(\"pod\", pod, \".status.containerStatuses[0].ready\", status, ns)\n\n\ndef wait_field(\n kind,\n name,\n field,\n value,\n ns=None,\n retries=max_retries,\n backoff=5,\n throw_error=True,\n shell=None,\n):\n with Then(f\"{kind} {name} {field} should be {value}\"):\n for i in range(1, retries):\n cur_value = get_field(kind, name, field, ns, shell=shell)\n if cur_value == value:\n break\n with Then(\"Not ready. Wait for \" + str(i * backoff) + \" seconds\"):\n time.sleep(i * backoff)\n assert cur_value == value or throw_error is False, error()\n\n\ndef wait_field_changed(\n kind,\n name,\n field,\n prev_value,\n ns=None,\n retries=max_retries,\n backoff=5,\n throw_error=True,\n):\n with Then(f\"{kind} {name} {field} should be different from {prev_value}\"):\n for i in range(1, retries):\n cur_value = get_field(kind, name, field, ns)\n if cur_value != \"\" and cur_value != prev_value:\n break\n with Then(\"Not ready. Wait for \" + str(i * backoff) + \" seconds\"):\n time.sleep(i * backoff)\n assert cur_value != \"\" and cur_value != prev_value or throw_error == False, error()\n\n\ndef wait_jsonpath(kind, name, field, value, ns=None, retries=max_retries):\n with Then(f\"{kind} {name} -o jsonpath={field} should be {value}\"):\n for i in range(1, retries):\n cur_value = get_jsonpath(kind, name, field, ns)\n if cur_value == value:\n break\n with Then(\"Not ready. Wait for \" + str(i * 5) + \" seconds\"):\n time.sleep(i * 5)\n assert cur_value == value, error()\n\n\ndef get_field(kind, name, field, ns=None, shell=None):\n out = \"\"\n if get_count(kind, name=name, ns=ns, shell=shell) > 0:\n out = launch(f\"get {kind} {name} -o=custom-columns=field:{field}\", ns=ns, shell=shell).splitlines()\n if len(out) > 1:\n return out[1]\n else:\n return \"\"\n\n\ndef get_jsonpath(kind, name, field, ns=None):\n out = launch(f'get {kind} {name} -o jsonpath=\"{field}\"', ns=ns).splitlines()\n return out[0]\n\n\ndef get_default_storage_class(ns=None):\n out = launch(\n f\"get storageclass \"\n f\"-o=custom-columns=\"\n f'DEFAULT:\".metadata.annotations.storageclass\\.kubernetes\\.io/is-default-class\",NAME:.metadata.name',\n ns=ns,\n ).splitlines()\n for line in out[1:]:\n if line.startswith(\"true\"):\n parts = line.split(maxsplit=1)\n return parts[1].strip()\n out = launch(\n f\"get storageclass \"\n f\"-o=custom-columns=\"\n f'DEFAULT:\".metadata.annotations.storageclass\\.beta\\.kubernetes\\.io/is-default-class\",NAME:.metadata.name',\n ns=ns,\n ).splitlines()\n for line in out[1:]:\n if line.startswith(\"true\"):\n parts = line.split(maxsplit=1)\n return parts[1].strip()\n\n\ndef get_pod_spec(chi_name, pod_name=\"\", ns=None, shell=None):\n label = f\"-l clickhouse.altinity.com/chi={chi_name}\"\n if pod_name == \"\":\n pod = get(\"pod\", \"\", ns=ns, label=label, shell=shell)[\"items\"][0]\n else:\n pod = get(\"pod\", pod_name, ns=ns, shell=shell)\n return pod[\"spec\"]\n\n\ndef get_pod_image(chi_name, pod_name=\"\", ns=None, shell=None):\n pod_image = get_pod_spec(chi_name, pod_name, ns, shell=shell)[\"containers\"][0][\"image\"]\n return pod_image\n\n\ndef get_pod_names(chi_name, ns=None, shell=None):\n pod_names = launch(\n f\"get pods -o=custom-columns=name:.metadata.name -l clickhouse.altinity.com/chi={chi_name}\",\n ns=ns,\n shell=shell\n ).splitlines()\n return pod_names[1:]\n\n\ndef get_obj_names(chi_name, obj_type=\"pods\", ns=None):\n pod_names = launch(\n f\"get {obj_type} -o=custom-columns=name:.metadata.name -l clickhouse.altinity.com/chi={chi_name}\",\n ns=ns,\n ).splitlines()\n return pod_names[1:]\n\n\ndef get_pod_volumes(chi_name, pod_name=\"\", ns=None, shell=None):\n volume_mounts = get_pod_spec(chi_name, pod_name, ns, shell=shell)[\"containers\"][0][\"volumeMounts\"]\n return volume_mounts\n\n\ndef get_pod_ports(chi_name, pod_name=\"\", ns=None, shell=None):\n port_specs = get_pod_spec(chi_name, pod_name, ns, shell=shell)[\"containers\"][0][\"ports\"]\n ports = []\n for p in port_specs:\n ports.append(p[\"containerPort\"])\n return ports\n\n\ndef check_pod_ports(chi_name, ports, ns=None, shell=None):\n pod_ports = get_pod_ports(chi_name, ns=ns, shell=shell)\n with Then(f\"Expect pod ports {pod_ports} to match {ports}\"):\n assert sorted(pod_ports) == sorted(ports)\n\n\ndef check_pod_image(chi_name, image, ns=None, shell=None):\n pod_image = get_pod_image(chi_name, ns=ns, shell=shell)\n with Then(f\"Expect pod image {pod_image} to match {image}\"):\n assert pod_image == image\n\n\ndef check_pod_volumes(chi_name, volumes, ns=None, shell=None):\n pod_volumes = get_pod_volumes(chi_name, ns=ns, shell=shell)\n for v in volumes:\n with Then(f\"Expect pod has volume mount {v}\"):\n found = 0\n for vm in pod_volumes:\n if vm[\"mountPath\"] == v:\n found = 1\n break\n assert found == 1\n\n\ndef get_pvc_size(pvc_name, ns=None):\n return get_field(\"pvc\", pvc_name, \".spec.resources.requests.storage\", ns)\n\n\ndef get_pv_name(pvc_name, ns=None):\n return get_field(\"pvc\", pvc_name, \".spec.volumeName\", ns)\n\n\ndef get_pv_size(pvc_name, ns=None):\n return get_field(\"pv\", get_pv_name(pvc_name, ns), \".spec.capacity.storage\", ns)\n\n\ndef check_pod_antiaffinity(\n chi_name,\n pod_name=\"\",\n match_labels={},\n topologyKey=\"kubernetes.io/hostname\",\n ns=None,\n shell=None\n):\n pod_spec = get_pod_spec(chi_name, pod_name, ns, shell=shell)\n if match_labels == {}:\n match_labels = {\n \"clickhouse.altinity.com/app\": \"chop\",\n \"clickhouse.altinity.com/chi\": f\"{chi_name}\",\n \"clickhouse.altinity.com/namespace\": f\"{current().context.test_namespace}\",\n }\n expected = {\n \"requiredDuringSchedulingIgnoredDuringExecution\": [\n {\n \"labelSelector\": {\n \"matchLabels\": match_labels,\n },\n \"topologyKey\": f\"{topologyKey}\",\n },\n ],\n }\n with Then(f\"Expect podAntiAffinity to exist and match {expected}\"):\n assert \"affinity\" in pod_spec\n assert \"podAntiAffinity\" in pod_spec[\"affinity\"]\n assert pod_spec[\"affinity\"][\"podAntiAffinity\"] == expected\n\n\ndef check_service(service_name, service_type, ns=None, shell=None):\n with When(f\"{service_name} is available\"):\n service = get(\"service\", service_name, ns=ns, shell=shell)\n with Then(f\"Service type is {service_type}\"):\n assert service[\"spec\"][\"type\"] == service_type\n\n\ndef check_configmaps(chi_name, ns=None, shell=None):\n check_configmap(\n f\"chi-{chi_name}-common-configd\",\n [\n \"01-clickhouse-01-listen.xml\",\n \"01-clickhouse-02-logger.xml\",\n \"01-clickhouse-03-query_log.xml\",\n ],\n ns=ns,\n shell=shell\n )\n\n check_configmap(\n f\"chi-{chi_name}-common-usersd\",\n [\n \"01-clickhouse-operator-profile.xml\",\n \"02-clickhouse-default-profile.xml\",\n ],\n ns=ns,\n shell=shell\n )\n\n\ndef check_configmap(cfg_name, values, ns=None, shell=None):\n cfm = get(\"configmap\", cfg_name, ns=ns, shell=shell)\n for v in values:\n with Then(f\"{cfg_name} should contain {v}\"):\n assert v in cfm[\"data\"], error()\n\n\ndef check_pdb(chi, clusters, ns=None, shell=None):\n for c in clusters:\n with Then(f\"PDB is configured for cluster {c}\"):\n pdb = get(\"pdb\", chi + \"-\" + c, shell=shell)\n labels = pdb[\"spec\"][\"selector\"][\"matchLabels\"]\n assert labels[\"clickhouse.altinity.com/app\"] == \"chop\"\n assert labels[\"clickhouse.altinity.com/chi\"] == chi\n assert labels[\"clickhouse.altinity.com/cluster\"] == c\n assert labels[\"clickhouse.altinity.com/namespace\"] == current().context.test_namespace\n assert pdb[\"spec\"][\"maxUnavailable\"] == 1\n","repo_name":"Altinity/clickhouse-operator","sub_path":"tests/e2e/kubectl.py","file_name":"kubectl.py","file_ext":"py","file_size_in_byte":20672,"program_lang":"python","lang":"en","doc_type":"code","stars":1477,"dataset":"github-code","pt":"77"}
+{"seq_id":"4037780742","text":"import argparse\nimport numpy as np\n\n\ndef main():\n\n # parse arguments from CLI\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--keep-fraction\",\n type=float,\n default=0.8,\n help=\"keep fraction of original list\",\n )\n parser.add_argument(\n \"--cnet-list\",\n type=str,\n default=\"experiments/data/atco2_pl_set/cnet_scores\",\n help=\"List with CNET files (confidence)\",\n )\n # parse arguments\n args = parser.parse_args()\n\n data = np.loadtxt(args.cnet_list, dtype=\"object,f4,object\")\n rec_keys = data[\"f0\"]\n\n sample_size = int(len(rec_keys) * args.keep_fraction)\n\n selected_keys = np.random.choice(rec_keys, size=sample_size, replace=False)\n selected_keys = np.sort(selected_keys)\n\n for key in selected_keys:\n print(key)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"idiap/atco2-corpus","sub_path":"data/databases/atco2_pl_set/local/select_data_randomly.py","file_name":"select_data_randomly.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"77"}
+{"seq_id":"31454548688","text":"import matplotlib.pyplot as plt\n\nx1 = [1, 3, 5, 7, 9]\ny1 = [2, 3, 7, 1, 0]\n\nx2 = [2, 4, 6, 8, 10]\ny2 = [5, 1, 3, 7, 4]\n\nplt.title('Bar Graph')\nplt.xlabel('X')\nplt.ylabel('Y')\n\nplt.bar(x1, y1, label = '1st Group')\nplt.bar(x2, y2, label = '2nd Group')\n\nplt.show()","repo_name":"marismarcosta/learn-data-science","sub_path":"graphs-examples/barGraph.py","file_name":"barGraph.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"5543866127","text":"#!/usr/bin/env python\n\n# This program 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 2 of the License, or\n# (at your option) any later version.\n#\n# This program 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.\n#\n# See LICENSE for more details.\n\n\"\"\"rv_gui.py - runs dogtail tests on the client.\n\nRequirements for host machine\n-----------------------------\n\n - rv_setup must be run to have dogtail be installed on the client.\n - rv_connect must be run to restart the gdm session.\n\nThis file doesn't make any decision about test success. The decision is made by\ntest running at VM.\n\nTest is successful if all sub-tests running at VM are successful.\n\n\"\"\"\n\nimport os\nimport logging\nimport traceback\nfrom spice.lib import stest\nfrom spice.lib import utils\nfrom spice.lib import act\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef run(vt_test, test_params, env):\n \"\"\"GUI tests for remote-viewer.\n\n Parameters\n ----------\n vt_test : avocado.core.plugins.vt.VirtTest\n QEMU test object.\n test_params : virttest.utils_params.Params\n Dictionary with the test parameters.\n env : virttest.utils_env.Env\n Dictionary with test environment.\n\n Raises\n ------\n TestFail\n Test fails for expected behaviour.\n\n \"\"\"\n test = stest.ClientGuestTest(vt_test, test_params, env)\n cfg = test.cfg\n vmi_c = test.vmi_c\n vmi_g = test.vmi_g\n vm_c = test.vm_c\n # Screen lock is now disabled in kickstart file for source QCOW images of\n # SPICE-QE team (https://gitlab.cee.redhat.com/spiceqe/install-compose/ks).\n # act.lock_scr_off(vmi_c)\n act.turn_accessibility(vmi_c)\n act.x_active(vmi_c)\n act.x_active(vmi_g)\n if utils.vm_is_rhel8(vm_c):\n act.set_alt_python(vmi_c, \"/usr/bin/python3\")\n else:\n act.install_rpm(vmi_c, test.cfg_c.epel_rpm)\n act.install_rpm(vmi_c, test.cfg_c.dogtail_rpm)\n act.install_rpm(vmi_c, \"xdotool\")\n if utils.vm_is_rhel6(vm_c):\n # Activate accessibility for rhel6\n act.reset_gui(vmi_c)\n\n # Copy tests to client VM.\n # Some tests could require established RV session, some of them, don't.\n is_connected = False\n if cfg.make_rv_connect:\n ssn = act.new_ssn(vmi_c, dogtail_ssn=vmi_c.vm.is_rhel8())\n act.rv_connect(vmi_c, ssn)\n if not cfg.negative:\n act.rv_chk_con(vmi_c)\n is_connected = True\n logging.getLogger().setLevel(logging.DEBUG)\n tdir = act.cp2vm(vmi_c, cfg.client_tests)\n tpath = os.path.join(tdir, cfg.script)\n cmd = utils.Cmd('python', *tpath.split())\n try:\n status, _ = act.rstatus(vmi_c, cmd, dogtail_ssn=vmi_c.vm.is_rhel8())\n except Exception as e:\n a = traceback.format_exc()\n logger.info(\"Exception: %s: %s.\", repr(e), a)\n if cfg.make_rv_connect:\n out = ssn.read_nonblocking()\n logger.info(\"RV log: %s.\", str(out))\n if status:\n raise utils.SpiceTestFail(test, \"Test failed.\")\n","repo_name":"spiceqa/tp-spice","sub_path":"spice/tests/rv_gui.py","file_name":"rv_gui.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"41582473894","text":"from typing import Iterable\n\n\ndef flat_list(array):\n print('Array:', array)\n\n def flatten(node):\n if isinstance(node, int):\n print('Integer: ', node)\n yield node\n elif isinstance(node, Iterable):\n print('Iterable:', node)\n for subnode in node:\n yield from flatten(subnode)\n\n output_list = list(flatten(array))\n print('Output list:', output_list)\n print()\n return output_list\n\n\nif __name__ == '__main__':\n assert flat_list([1, 2, 3]) == [1, 2, 3], \"First\"\n assert flat_list([1, [2, 2, 2], 4]) == [1, 2, 2, 2, 4], \"Second\"\n assert flat_list([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]) == [2, 4, 5, 6, 6, 6, 6, 6, 7], \"Third\"\n assert flat_list([-1, [1, [-2], 1], -1]) == [-1, 1, -2, 1, -1], \"Four\"\n print('Done! Check it')","repo_name":"ogorodnikov/pycheck","sub_path":"Other/flatten_a_list.py","file_name":"flatten_a_list.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"1993829976","text":"import argparse\n\nimport torch\nfrom datasets import load_dataset\nfrom transformers import BertForSequenceClassification, BertTokenizer\n\nfrom mmengine.evaluator import BaseMetric\nfrom mmengine.model import BaseModel\nfrom mmengine.runner import Runner\n\n\nclass MMBertForClassify(BaseModel):\n\n def __init__(self, model):\n super().__init__()\n self.model = model\n\n def forward(self, label, input_ids, token_type_ids, attention_mask, mode):\n output = self.model(\n input_ids=input_ids,\n token_type_ids=token_type_ids,\n attention_mask=attention_mask,\n labels=label)\n if mode == 'loss':\n return {'loss': output.loss}\n elif mode == 'predict':\n return output.logits, label\n\n\nclass Accuracy(BaseMetric):\n\n def process(self, data_batch, data_samples):\n score, gt = data_samples\n self.results.append({\n 'batch_size': len(gt),\n 'correct': (score.argmax(dim=1) == gt).sum().cpu(),\n })\n\n def compute_metrics(self, results):\n total_correct = sum(item['correct'] for item in results)\n total_size = sum(item['batch_size'] for item in results)\n return dict(accuracy=100 * total_correct / total_size)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Distributed Training')\n parser.add_argument(\n '--launcher',\n choices=['none', 'pytorch', 'slurm', 'mpi'],\n default='none',\n help='job launcher')\n parser.add_argument('--local_rank', type=int, default=0)\n\n args = parser.parse_args()\n return args\n\n\ndef collate_fn(data):\n labels = []\n input_ids = []\n token_type_ids = []\n attention_mask = []\n for item in data:\n labels.append(item['label'])\n input_ids.append(torch.tensor(item['input_ids']))\n token_type_ids.append(torch.tensor(item['token_type_ids']))\n attention_mask.append(torch.tensor(item['attention_mask']))\n\n input_ids = torch.stack(input_ids)\n token_type_ids = torch.stack(token_type_ids)\n attention_mask = torch.stack(attention_mask)\n label = torch.tensor(labels)\n return dict(\n label=label,\n input_ids=input_ids,\n token_type_ids=token_type_ids,\n attention_mask=attention_mask)\n\n\ndef main():\n args = parse_args()\n model = BertForSequenceClassification.from_pretrained(\n 'bert-base-uncased', num_labels=2)\n tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n\n train_set = load_dataset('imdb', split='train')\n test_set = load_dataset('imdb', split='test')\n\n train_set = train_set.map(\n lambda x: tokenizer(\n x['text'], truncation=True, padding=True, max_length=128),\n batched=True)\n test_set = test_set.map(\n lambda x: tokenizer(\n x['text'], truncation=True, padding=True, max_length=128),\n batched=True)\n\n train_loader = dict(\n batch_size=32,\n dataset=train_set,\n sampler=dict(type='DefaultSampler', shuffle=True),\n collate_fn=collate_fn)\n test_loader = dict(\n batch_size=32,\n dataset=test_set,\n sampler=dict(type='DefaultSampler', shuffle=False),\n collate_fn=collate_fn)\n runner = Runner(\n model=MMBertForClassify(model),\n train_dataloader=train_loader,\n val_dataloader=test_loader,\n optim_wrapper=dict(optimizer=dict(type=torch.optim.Adam, lr=2e-5)),\n train_cfg=dict(by_epoch=True, max_epochs=2, val_interval=1),\n val_cfg=dict(),\n work_dir='bert_work_dir',\n val_evaluator=dict(type=Accuracy),\n launcher=args.launcher,\n )\n runner.train()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"open-mmlab/mmengine","sub_path":"examples/text_classification/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","stars":853,"dataset":"github-code","pt":"77"}
+{"seq_id":"41419688542","text":"from PyDictionary import PyDictionary\n\ndictionary = PyDictionary()\n\nword = input(\"Enter A word : \")\n\nmeaning = dictionary.meaning(word)\nantonyms = dictionary.antonym(word)\n\ndic = meaning['Noun']\nprint(\"THE MEANING OF \" + word.upper() + \" :\")\nfor i in dic:\n print(\"->>> \" + i)\nprint(antonyms)","repo_name":"Abhishekparmar123/Dictionary-app-usingPydictionary","sub_path":"Dict_app.py","file_name":"Dict_app.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"24452817625","text":"'''Module to parse data from ugg'''\n\n\ndef humanize_ugg_overview(overview):\n '''Humanizes ugg raw data'''\n data = overview[0]\n item_4_options = [{'item': o[0], 'wins': o[1], 'matches': o[2]} for o in data[5][0]]\n item_5_options = [{'item': o[0], 'wins': o[1], 'matches': o[2]} for o in data[5][1]]\n item_6_options = [{'item': o[0], 'wins': o[1], 'matches': o[2]} for o in data[5][2]]\n return {\n 'runes': {\n 'matches': data[0][0],\n 'wins': data[0][1],\n 'primary_style': data[0][2],\n 'secondary_style': data[0][3],\n 'runes': data[0][4],\n },\n 'summoner_spells': {\n 'matches': data[1][0],\n 'wins': data[1][1],\n 'summoner_spells': data[1][2],\n },\n 'starting_items': {\n 'matches': data[2][0],\n 'wins': data[2][1],\n 'starting_items': data[2][2],\n },\n 'core_items': {\n 'matches': data[3][0],\n 'wins': data[3][1],\n 'items': data[3][2],\n },\n 'abilities': {\n 'matches': data[4][0],\n 'wins': data[4][1],\n 'ability_order': data[4][2],\n 'ability_max_order': list(data[4][3]),\n },\n 'item_4_options': item_4_options,\n 'item_5_options': item_5_options,\n 'item_6_options': item_6_options,\n 'wins': data[6][0],\n 'matches': data[6][1],\n 'low_sample_size_warning': data[7],\n 'shards': {'matches': data[8][0], 'wins': data[8][1], 'shards': data[8][2]},\n }\n","repo_name":"pradishb/ugg-parser","sub_path":"ugg/_humanize.py","file_name":"_humanize.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"40546162222","text":"import os\nimport torch\n\n\ndef mkdirs(paths):\n if isinstance(paths, list) and not isinstance(paths, str):\n for path in paths:\n mkdir(path)\n else:\n mkdir(paths)\n\n\ndef mkdir(path):\n if not os.path.exists(path):\n os.makedirs(path)\n\n\ndef get_onehot_vector(args, labels):\n labels = labels.long().unsqueeze(1)\n labels[labels == 255] = args.num_classes\n bs, _, h, w = labels.size()\n nc = args.num_classes + 1\n input_label = torch.FloatTensor(bs, nc, h, w).zero_()\n input_semantics = input_label.scatter_(1, labels, 1.0)[0][:args.num_classes].unsqueeze(0)\n return input_semantics\n","repo_name":"taveraantonio/PixDA","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"77"}
+{"seq_id":"8402173929","text":"import collections\n\n'''\nGiven two strings s and t, return true if t is an anagram of s, and false otherwise.\n\nAn Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, \ntypically using all the original letters exactly once.\n'''\nclass Solution:\n def isAnagram(self, s: str, t: str) -> bool:\n '''\n There are figuratively a zillion ways to solve this problem\n but lets try to implement the more efficient and straight forward way\n and a one liner solution to solve this problem\n\n 1. [Longer way] Using an array to store the \n 2. [One-liner] Using a Counter and frequency map to store the char and freq\n '''\n\n freqArray = [0]*26\n for char in s:\n index = ord(char.lower())-ord('a')\n freqArray[index] += 1\n for char in t:\n index = ord(char.lower())-ord('a')\n freqArray[index] -= 1\n \n for ele in freqArray:\n if ele != 0:\n return False\n return True\n \n # one-liner solution --> Warning only usable in python\n def isAnagramCounter(self, s: str, t: str) -> bool:\n return collections.Counter(s) == collections.Counter(t)\n\nassert Solution().isAnagram(\"anagram\", \"nagaram\")==True, \"Assertion came out False\"\nassert Solution().isAnagram(\"rat\", \"car\")==False, \"Assertion came out True\"\n","repo_name":"rishiselvakumaran98/LeetcodePrep","sub_path":"Arrays_Hashing/ValidAnagram/ValidAnagaram.py","file_name":"ValidAnagaram.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"74213065528","text":"'''\r\nGCF from Coderbyte\r\nDecember 2020 Jakub Kazimierski\r\n'''\r\n\r\ndef gcf(a, b):\r\n '''\r\n Calculate the Greatest Common Divisor of a and b.\r\n '''\r\n while b:\r\n a, b = b, a%b\r\n return a\r\n\r\ndef GCF(arr):\r\n '''\r\n Have the function GCF(arr) \r\n take the array of numbers \r\n stored in arr which will always \r\n contain only two positive integers, \r\n and return the greatest common \r\n factor of them. \r\n \r\n For example: if arr is [45, 12] then your \r\n program should return 3. \r\n There will always be two elements in \r\n the array and they will be positive integers.\r\n '''\r\n\r\n try:\r\n\r\n output = gcf(arr[0],arr[1])\r\n\r\n return output\r\n \r\n except(AttributeError, TypeError):\r\n return -1 ","repo_name":"JakubKazimierski/PythonPortfolio","sub_path":"Coderbyte_algorithms/Easy/GCF/GCF.py","file_name":"GCF.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"77"}
+{"seq_id":"24386027616","text":"class Solution(object):\n def combinationSum3(self, k, n):\n res = []\n self.dfs(xrange(1, 10), k, n, 0, [], res)\n return res\n\n def dfs(self, nums, k, n, index, path, res):\n if k < 0 or n < 0: # backtracking\n return\n if k == 0 and n == 0:\n res.append(path)\n for i in xrange(index, len(nums)):\n self.dfs(nums, k - 1, n - nums[i], i + 1, path + [nums[i]], res)\n\n\nsl = Solution()\nprint(sl.combinationSum3(3, 7))\n","repo_name":"ChangXiaodong/Leetcode-solutions","sub_path":"2/216-Combination-Sum-III.py","file_name":"216-Combination-Sum-III.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"77"}
+{"seq_id":"18620472557","text":"#!/usr/bin/python\n\n# makes input arguments for a script:\n# usage:\n# make_arg(,,)\n# = the input flag ie '--i' or '--help'\n# = does the input require a value? if so use True or else use False\n# = is the flag required? if so use True\n\n\nimport sys\n#-----------------------------------------------------------------------------------#\nerrormsg = \"\"\nclass Arg(object):\n _registry = []\n def __init__(self, flag, value, req):\n self._registry.append(self)\n self.flag = flag\n self.value = value\n self.req = req\n\ndef make_arg(flag, value, req):\n Argument = Arg(flag, value, req)\n if Argument.req == True:\n if Argument.flag not in sys.argv:\n print(errormsg)\n sys.exit(\"ERROR: required argument '{0}' is missing\".format(Argument.flag))\n if Argument.value == True:\n try:\n test = sys.argv[sys.argv.index(Argument.flag)+1]\n except ValueError:\n if Argument.req == True:\n print(errormsg)\n sys.exit(\"ERROR: required argument '{0}' is missing\".format(Argument.flag))\n elif Argument.req == False:\n return False\n except IndexError:\n print(errormsg)\n sys.exit(\"ERROR: argument '{0}' requires a value\".format(Argument.flag))\n else:\n if Argument.value == True:\n Argument.value = sys.argv[sys.argv.index(Argument.flag)+1]\n \n if Argument.value == False:\n if Argument.flag in sys.argv:\n Argument.value = True\n else:\n Argument.value = False\n return Argument.value\n#-----------------------------------------------------------------------------------#\n\n# arg1 = make_arg('--i',True,True)\n# arg2 = make_arg('--f',True,False)\n# arg3 = make_arg('-n', False,False)\n# arg4 = make_arg('--testing',True,False)\n# arg5 = make_arg('--blah',False,False)\n# print(arg1)\n# print(arg2)\n# print(arg3)\n# print(arg4)\n# print(arg5)","repo_name":"attamatti/bits","sub_path":"ob_args.py","file_name":"ob_args.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"37228090261","text":"from machine import Pin,I2C\r\nfrom neopixel import NeoPixel\r\nfrom MX1508 import *\r\nfrom VL53L0X import *\r\nfrom tcs34725 import *\r\nfrom time import sleep_ms,sleep\r\nimport uasyncio as asio\r\nimport aioespnow\r\nimport network\r\n\r\ni2c_bus = I2C(0, sda=Pin(16), scl=Pin(17))\r\ntcs = TCS34725(i2c_bus)\r\ntcs.gain(4)#gain must be 1, 4, 16 or 60\r\ntcs.integration_time(80)\r\ni2c_bus1 = I2C(1, sda=Pin(21), scl=Pin(22))\r\ntof = VL53L0X(i2c_bus1)\r\n\r\nNUM_OF_LED = 1\r\nnp = NeoPixel(Pin(14), NUM_OF_LED)\r\ncolor=['Red','Yellow','White','Green','Black','Cyan','Blue','Magenta']\r\ndir_move=['Stop','Forward','Left','Right','Reverse']\r\nmotor_L = MX1508(2, 4)\r\nmotor_R = MX1508(19, 18)\r\nSp=900\r\nSp1=int(Sp*0.3)\r\nLt=60\r\nalfa=0.8\r\ndebug=1\r\n\r\nasync def color_det():\r\n global col_id,col_id_l\r\n rgb=tcs.read(1)\r\n r,g,b=rgb[0],rgb[1],rgb[2]\r\n h,s,v=rgb_to_hsv(r,g,b)\r\n if 0100:\r\n col_id_l=col_id\r\n col_id=2\r\n elif 2540:\r\n col_id_l=col_id\r\n col_id=5\r\n else:\r\n col_id_l=col_id\r\n col_id=6\r\n elif 241 : GET information for a specific provider' \\\n '/server : POST or add a new server' \\\n '/server/ : PUT or update an existing server' \\\n '/server/ : DELETE an existing provider'\n\n\n# Get all servers\n@app.route('/servers', methods=['GET'])\ndef getAllServers():\n return jsonify({servers})\n\n\n# Get one server\n@app.route('/server/', methods=['GET'])\ndef getOneServer(provider):\n serv = [server for server in servers if server['provider'] == provider]\n return jsonify({'server': serv[0]})\n\n\n# Post one server\n@app.route('/server', methods=['POST'])\ndef addOneServer():\n server = {'name': request.json['provider'], 'ip': request.json['ip'], 'port': request.json['port']}\n servers.append(server)\n return jsonify({servers})\n\n\n# Update one server\n@app.route('/server/', methods=['PUT'])\ndef editOneServer(provider):\n serv = [server for server in servers if server['provider'] == provider]\n serv[0]['provider'] = request.json['provider']\n return jsonify({serv[0]})\n\n\n# Delete one server\n@app.route('/server/', methods=['DELETE'])\ndef removeOne(provider):\n serv = [server for server in servers if server['provider'] == provider]\n servers.remove(serv[0])\n return jsonify({'servers': servers})\n\n\n# Every below this line is to debug with Pycharm\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser(description='Development Server Help')\n parser.add_argument(\"-d\", \"--debug\", action=\"store_true\", dest=\"debug_mode\",\n help=\"run in debug mode (for use with PyCharm)\", default=False)\n parser.add_argument(\"-p\", \"--port\", dest=\"port\",\n help=\"port of server (default:%(default)s)\", type=int, default=5000)\n\n cmd_args = parser.parse_args()\n app_options = {\"port\": cmd_args.port}\n\n if cmd_args.debug_mode:\n app_options[\"debug\"] = True\n app_options[\"use_debugger\"] = False\n app_options[\"use_reloader\"] = False\n\n app.run(**app_options)\n\n\n","repo_name":"gus07ven/Networking","sub_path":"serverAPI.py","file_name":"serverAPI.py","file_ext":"py","file_size_in_byte":2597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"12953191364","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 ('Organizer', '0010_auto_20150428_2328'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='course',\n name='CertificateRequiredCourse',\n field=models.ManyToManyField(to='Organizer.Certificate', blank=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='student',\n name='StudyPlanPDF',\n field=models.FileField(upload_to=b'StudyPlanPDF/', blank=True),\n preserve_default=True,\n ),\n ]\n","repo_name":"michaelkressaty/ssepaperless","sub_path":"ssepaperless/Organizer/migrations/0011_auto_20150429_0414.py","file_name":"0011_auto_20150429_0414.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"40159862076","text":"class Solution:\n def spiralOrder(self, matrix):\n if not matrix or not matrix[0]:\n return list()\n res = list()\n rows, cols = len(matrix), len(matrix[0])\n visited = [[False]*cols for i in range(rows)]\n directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]\n direction_index = 0\n x, y = 0, 0\n for i in range(rows*cols):\n res.append(matrix[x][y])\n visited[x][y] = True\n next_x = x + directions[direction_index][0]\n next_y = y + directions[direction_index][1]\n if not(rows > next_x >= 0 and cols > next_y >= 0 and not visited[next_x][next_y]):\n direction_index = (direction_index+1) % 4\n x += directions[direction_index][0]\n y += directions[direction_index][1]\n return res\n\nclass Solution:\n def spiralOrder(self, matrix):\n if not matrix or not matrix[0]:\n return list()\n res = list()\n rows, cols = len(matrix), len(matrix[0])\n left, right, top, bottom = 0, cols-1, 0, rows-1\n while left <= right and top <= bottom:\n for i in range(left, right+1):\n res.append(matrix[top][i])\n for i in range(top+1, bottom+1):\n res.append(matrix[i][right])\n if left < right and top < bottom:\n for i in range(right-1, left, -1):\n res.append(matrix[bottom][i])\n for i in range(bottom, top, -1):\n res.append(matrix[i][left])\n left, right, top, bottom = left+1, right-1, top+1, bottom-1\n return res","repo_name":"luoyanhan/Algorithm-and-data-structure","sub_path":"Leetcode/medium/54.py","file_name":"54.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"15017728596","text":"__author__ = 'Christophe Rousson'\n__date__ = 'November 2016'\n__copyright__ = '(C) 2016, Christophe Rousson'\n\n# This will get replaced with a git SHA1 when you do a git archive\n\n__revision__ = '$Format:%H$'\n\nfrom PyQt5.QtCore import QCoreApplication\nfrom qgis.core import (QgsProcessingAlgorithm,\n QgsProcessingParameterRasterLayer,\n QgsProcessingParameterNumber,\n QgsProcessingParameterRasterDestination)\nfrom osgeo import gdal\nimport numpy as np\n\nfrom ..metadata import AlgorithmMetadata\n\nclass DifferentialRasterThreshold(AlgorithmMetadata, QgsProcessingAlgorithm):\n\n METADATA = AlgorithmMetadata.read(__file__, 'DifferentialRasterThreshold')\n\n INPUT_DEM = 'INPUT_DEM'\n REFERENCE_DEM = 'REFERENCE_DEM'\n MIN_THRESHOLD = 'MIN_THRESHOLD'\n MAX_THRESHOLD = 'MAX_THRESHOLD'\n RELATIVE_DEM = 'OUTPUT'\n # NO_DATA = 'NO_DATA'\n\n def initAlgorithm(self, config=None):\n\n self.addParameter(QgsProcessingParameterRasterLayer(self.INPUT_DEM,\n self.tr('Input DEM')))\n self.addParameter(QgsProcessingParameterRasterLayer(self.REFERENCE_DEM,\n self.tr('Reference DEM')))\n self.addParameter(QgsProcessingParameterNumber(self.MIN_THRESHOLD,\n self.tr('Min. value'), defaultValue=-10))\n self.addParameter(QgsProcessingParameterNumber(self.MAX_THRESHOLD,\n self.tr('Max. value'), defaultValue=10))\n \n # self.addParameter(ParameterString(self.NO_DATA,\n # self.tr('No data value'), '-9999'))\n\n self.addParameter(QgsProcessingParameterRasterDestination(self.RELATIVE_DEM, self.tr('Relative DEM')))\n\n def processAlgorithm(self, parameters, context, feedback):\n\n input_dem = self.parameterAsRasterLayer(parameters, self.INPUT_DEM, context)\n input_dem_path = str(input_dem.dataProvider().dataSourceUri())\n\n reference_dem = self.parameterAsRasterLayer(parameters, self.REFERENCE_DEM, context)\n reference_dem_path = str(reference_dem.dataProvider().dataSourceUri())\n\n maxvalue = self.parameterAsDouble(parameters, self.MAX_THRESHOLD, context)\n minvalue = self.parameterAsDouble(parameters, self.MIN_THRESHOLD, context)\n\n output_path = self.parameterAsOutputLayer(parameters, self.RELATIVE_DEM, context)\n # ndv = float(self.getParameterValue(self.NO_DATA))\n\n # dem = gn.LoadFile(input_dem_path)\n ds = gdal.Open(input_dem_path)\n if ds.RasterCount != 1:\n feedback.pushInfo('Input DEM has more than 1 band.')\n\n dem = ds.GetRasterBand(1).ReadAsArray()\n nodata = ds.GetRasterBand(1).GetNoDataValue()\n dem = np.ma.masked_where(dem == nodata, dem)\n \n # reference = gn.LoadFile(reference_dem_path)\n refds = gdal.Open(reference_dem_path)\n if refds.RasterCount != 1:\n feedback.pushInfo('Reference DEM has more than 1 band.')\n \n reference = refds.GetRasterBand(1).ReadAsArray()\n ref_nodata = refds.GetRasterBand(1).GetNoDataValue()\n if ref_nodata is None:\n ref_nodata = nodata\n\n reference = np.ma.masked_where(reference == ref_nodata, reference)\n \n relative = dem - reference\n mask = np.bitwise_and(relative > minvalue, relative <= maxvalue)\n\n # gn.SaveArray(mask.astype(np.uint8), str(output_path), format='GTiff', prototype=str(input_dem_path))\n driver = gdal.GetDriverByName('GTiff')\n dst = driver.CreateCopy(str(output_path), ds, strict=0, options=['TILED=YES', 'COMPRESS=DEFLATE'])\n dst.GetRasterBand(1).WriteArray(mask.astype(np.uint8))\n\n # Properly close GDAL resources\n ds = None\n refds = None\n dst = None\n\n return {self.RELATIVE_DEM: output_path}\n\n\n def tr(self, string):\n return QCoreApplication.translate('FluvialCorridorToolbox', string)\n\n def createInstance(self):\n return DifferentialRasterThreshold()","repo_name":"tramebleue/fct-qgis","sub_path":"fct/algorithms/raster/DifferentialRasterThreshold.py","file_name":"DifferentialRasterThreshold.py","file_ext":"py","file_size_in_byte":4114,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"77"}
+{"seq_id":"41172555622","text":"\"\"\"\nFunctions for visualizing cuts of the basins of attraction\n\"\"\"\n\n\nfrom .post_process_color_map import remove_bad_looking_colors\nfrom ..ensemble import ENSEMBLE_FOLDER_NAME\nfrom basinerror.utils.plot_utils.config_plot import save_configuration_2d\nfrom basinerror.utils.plot_utils import save_configuration_2d\nfrom basinerror.utils.params import (\n load_run_parameters,\n setup_inverse_power_from_folder,\n)\nfrom basinerror.minima_map.minima_map import FINAL_COORDS_FOLDER_NAME\nfrom basinerror.analysis._folder_names import (\n MINIMA_DATABASE_FOLDER_NAME,\n PRIMARY_ANALYSIS_FOLDER_NAME,\n)\nfrom matplotlib import colors\nimport collections\nimport os\nimport shutil\n\nimport cv2\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport mplcursors\nimport numpy as np\nimport yaml\n\ntry:\n import pele.utils.pymolwrapper as pym\n import pymol\nexcept:\n print(\"pymol not installed, pymol functions will not work\")\nimport matplotlib\n\nmatplotlib.use(\"pdf\")\nfrom matplotlib import colors\n\n\ndirname = os.path.dirname(__file__)\n\n# Default Order params folder, for order parameters generated per file\nORDER_PARAMS_FILE_NAME = \"order_params.txt\"\n# Default save extension\nDEFAULT_SAVE_EXTENSION = \".svg\"\n\n# large set of glasbey colors generated earlier: max of 20000 colors\nGLASBEY = np.loadtxt(dirname + \"/glasbey20000.csv\", delimiter=\",\")\nGLASBEY = GLASBEY[15:]\nGLASBEY_LENGTH = len(GLASBEY)\nGLASBEY_ARGS = np.arange(GLASBEY_LENGTH)\nGLASBEY_COLORMAP = colors.ListedColormap(GLASBEY)\n\n\ndef generate_plot_map(\n minima_folder_path,\n random_plane_folder_path,\n order_params_file_name=ORDER_PARAMS_FILE_NAME,\n):\n \"\"\"Generate a map from the mesh grid to the file names.\n\n Parameters\n ----------\n minima_folder_path : str\n path to the folder containing the minima data\n run_folder_name : str\n name of the run folder\n\n Returns\n -------\n plot_map : [np.ndarray, np.ndarray]\n Map from the mesh grid to the the order of the identified minima.\n The index defines the map between the mesh to the file names.\n \"\"\"\n order_params, corresponding_mesh_list = gen_plot_map(\n minima_folder_path,\n random_plane_folder_path,\n order_params_file_name=order_params_file_name,\n )\n return [np.array(corresponding_mesh_list), np.array(order_params)]\n\n\ndef generate_paths(minima_folder_path, run_folder_name, plane_folder_name):\n minima_folder_path_as_list = minima_folder_path.split(\"/\")\n minima_folder_path_as_list = np.insert(\n minima_folder_path_as_list, -1, run_folder_name\n )\n minima_folder_path = \"/\".join(minima_folder_path_as_list)\n print(minima_folder_path)\n\n # change path to follow minima folder\n ensemble_folder_path = (\n \"/\".join(minima_folder_path_as_list[:-3]) + \"/\" + ENSEMBLE_FOLDER_NAME\n )\n random_plane_folder_path = ensemble_folder_path + \"/\" + plane_folder_name\n return minima_folder_path, random_plane_folder_path\n\n\ndef gen_plot_map(\n minima_folder_path,\n random_plane_folder_path,\n order_params_file_name=ORDER_PARAMS_FILE_NAME,\n):\n # first load order parameters filenames and indices\n # filename says which file the order parameter is from\n # indices tells us what index in the file corresponds to our order\n # parameter\n order_params = np.loadtxt(\n minima_folder_path + \"/\" + order_params_file_name\n )\n file_names = np.loadtxt(minima_folder_path + \"/\" + \"filenames.txt\")\n indices = np.loadtxt(minima_folder_path + \"/\" + \"indices.txt\")\n print(order_params)\n\n unique_file_names = np.unique(file_names)\n\n mesh_list = []\n for file_name in unique_file_names:\n mesh_list.append(\n np.loadtxt(\n random_plane_folder_path\n + \"/\"\n + str(int(np.rint(file_name)))\n + \"_mesh.txt\",\n delimiter=\",\",\n )\n )\n\n file_name_to_mesh_dict = dict(zip(unique_file_names, mesh_list))\n\n # load corresponding mesh grid\n corresponding_mesh_list = []\n if np.all(indices == 0):\n all_indices_0 = True\n else:\n all_indices_0 = False\n\n for i, order_param in enumerate(order_params):\n corresponding_file_name = file_names[i]\n corresponding_index = indices[i]\n if all_indices_0:\n corresponding_mesh_coords = file_name_to_mesh_dict[\n corresponding_file_name\n ]\n else:\n corresponding_mesh_coords = file_name_to_mesh_dict[\n corresponding_file_name\n ][int(corresponding_index)]\n corresponding_mesh_list.append(corresponding_mesh_coords)\n return order_params, corresponding_mesh_list\n\n\ndef generate_mesh_grid_file_name_map(random_plane_folder_path):\n \"\"\"Generate a map from the mesh grid to the file names.\"\"\"\n # load the mesh grid from the ensemble folder\n\n # load the file names from the ensemble folder\n file_names = os.listdir(random_plane_folder_path)\n # get those file names that end with mesh.txt\n mesh_file_names = [\n file_name for file_name in file_names if file_name.endswith(\"mesh.txt\")\n ]\n coords_file_names = [\n mesh_file_name.replace(\"mesh.txt\", \"coords.txt\")\n for mesh_file_name in mesh_file_names\n ]\n\n # load all arrays from mesh_file_names:\n mesh_list = [\n np.loadtxt(\n random_plane_folder_path + \"/\" + mesh_file_name, delimiter=\",\"\n )\n for mesh_file_name in mesh_file_names\n ]\n mesh_list = np.array(mesh_list)\n\n # case for when mesh_list is of length 1\n if len(mesh_list.shape) == 2:\n mesh_l_flattened = mesh_list\n else:\n mesh_l_flattened = []\n for mesh_coords_list in mesh_list:\n for mesh_coords in mesh_coords_list:\n mesh_l_flattened.append(mesh_coords)\n # since the map is already set we can just return them as two lists.\n # The index defines the map between the mesh to the file names.\n return [np.array(mesh_l_flattened), coords_file_names]\n\n\ndef generate_cut_2d(mesh_arr, order_param_arr):\n \"\"\"Generates a cut of the basins of attraction,\n where each basin is represented by it's respective order parameter\n\n Parameters\n ----------\n mesh_arr : np.ndarray\n list of 2d mesh points\n order_params_list : np.ndarray[int]\n corresponding order parameters\n Returns\n ----------\n basin_cut : np.ndarray\n 2d array that describes the order parameter of the cuts\n mesh_extent : [float, float, float, float]\n extent of the mesh. Used to set the extent of the plot\n slightly displaced by the delta_x, delta_y\n \"\"\"\n mesh_arr = np.array(mesh_arr)\n # transform mesh array into a 2d index list\n # get minimum x and y values of mesh_arr\n unique_x = np.unique(mesh_arr[:, 0])\n unique_y = np.unique(mesh_arr[:, 1])\n\n argsort_x = np.argsort(unique_x)\n argsort_y = np.argsort(unique_y)\n\n max_x = unique_x[argsort_x[-1]]\n max_y = unique_y[argsort_y[-1]]\n min_x = unique_x[argsort_x[0]]\n min_y = unique_y[argsort_y[0]]\n min_2nd_x = unique_x[argsort_x[1]]\n min_2nd_y = unique_y[argsort_y[1]]\n\n # assumes equidistant spacing in x and y\n spacing_x = min_2nd_x - min_x\n spacing_y = min_2nd_y - min_y\n\n # convert x_axis to indices\n index_arr = np.full_like(mesh_arr, 1, dtype=int)\n # rint for correct rounding\n index_arr[:, 0] = np.rint((mesh_arr[:, 0] - min_x) / spacing_x).astype(int)\n index_arr[:, 1] = np.rint((mesh_arr[:, 1] - min_y) / spacing_y).astype(int)\n\n max_ind_x = np.rint((max_x - min_x) / spacing_x).astype(int)\n max_ind_y = np.rint((max_y - min_y) / spacing_y).astype(int)\n basin_cut = np.zeros((max_ind_y + 1, max_ind_x + 1), dtype=int)\n # fill the cut with -200 for the points that are not in the mesh\n basin_cut.fill(np.iinfo(np.int32).max)\n for i, order_param in enumerate(order_param_arr):\n basin_cut[index_arr[i, 1], index_arr[i, 0]] = order_param\n # return the cut and corresponding mesh extent\n # TODO: The mesh extent is always the same considering it's a unit mesh.\n # get the extent from config.yaml file.\n return (basin_cut, [0, len(unique_x), 0, len(unique_y)])\n\n\ndef generate_cut_nd(mesh_arr, order_param_arr, dim):\n \"\"\"\n Generates a cut of the basins of attraction,\n where each basin is represented by it's respective order parameter\n\n Parameters\n ----------\n mesh_arr : np.ndarray\n list of nd mesh points\n order_params_list : np.ndarray[int]\n corresponding order parameters\n dim: int\n Dimension of the cut being generated\n Returns\n ----------\n basin_cut : np.ndarray\n nd array that describes the order parameter of the cuts\n mesh_extent : list[float]\n extent of the mesh. Used to set the extent of the plot\n slightly displaced by the delta_x, delta_y, delta_z, etc\n goes as min_x, max_x, min_y, max_y, min_z, max_z ...\n \"\"\"\n mesh_arr = np.array(mesh_arr)\n # transform mesh array into a 2d index list\n # get minimum x and y values of mesh_arr\n\n unique_position_list = []\n for i in range(dim):\n unique_position_list.append(np.unique(mesh_arr[:, i]))\n\n argsort_position_list = []\n for i in range(dim):\n argsort_position_list.append(np.argsort(unique_position_list[i]))\n\n max_position_list = []\n min_position_list = []\n min_2nd_position_list = []\n\n for i in range(dim):\n max_position_list.append(\n unique_position_list[i][argsort_position_list[i][-1]]\n )\n min_position_list.append(\n unique_position_list[i][argsort_position_list[i][0]]\n )\n min_2nd_position_list.append(\n unique_position_list[i][argsort_position_list[i][1]]\n )\n\n spacing_list = []\n\n for i in range(dim):\n spacing_list.append(min_2nd_position_list[i] - min_position_list[i])\n\n # convert x_axis to indices\n index_arr = np.full_like(mesh_arr, 1, dtype=int)\n # rint for correct rounding\n\n for i in range(dim):\n index_arr[:, i] = np.rint(\n (mesh_arr[:, i] - min_position_list[i]) / spacing_list[i]\n ).astype(int)\n\n max_ind_list = []\n\n for i in range(dim):\n max_ind_list.append(\n np.rint(\n (max_position_list[i] - min_position_list[i]) / spacing_list[i]\n ).astype(int)\n )\n\n basin_cut = np.zeros((max_ind + 1 for max_ind in max_ind_list))\n for i, order_param in enumerate(order_param_arr):\n basin_cut[tuple(index_arr[i, :])] = order_param\n\n mesh_extent = []\n for i in range(dim):\n mesh_extent.append(0)\n mesh_extent.append(len(unique_position_list[i]))\n\n # return the cut and corresponding mesh extent\n # TODO: The mesh extent is always the same considering it's a unit mesh.\n # get the extent from config.yaml file.\n return (basin_cut, mesh_extent)\n\n\nclass InteractiveConfigViewer:\n \"\"\"\n Interactive configuration viewer for cuts\n Saves the data necessary for generating the cuts\n \"\"\"\n\n def __init__(\n self, minima_folder_path, run_folder_name, plane_folder_name\n ) -> None:\n self.minima_folder_path = minima_folder_path\n self.run_folder_name = run_folder_name\n self.plane_folder_name = plane_folder_name\n\n # last two folders in list specify location of the minim\n run_folder_list = minima_folder_path.split(\"/\")\n\n self.radii, _, self.box_length = load_run_parameters(\n \"/\".join(run_folder_list[:-2])\n )\n run_folder_list = run_folder_list[:-2]\n run_folder_list[-2] = FINAL_COORDS_FOLDER_NAME\n run_folder_list[-1] = run_folder_name\n self.run_folder_path = \"/\".join(run_folder_list)\n\n playground_folder_name = \"playground\"\n run_folder_list[-2] = playground_folder_name\n self.playground_folder_path = \"/\".join(run_folder_list)\n os.makedirs(self.playground_folder_path, exist_ok=True)\n\n self.initialize_objs()\n\n (\n self.minima_folder_path,\n self.random_plane_folder_path,\n ) = self.get_minima_folder_and_plane_folder(\n minima_folder_path, run_folder_name, plane_folder_name\n )\n\n def initialize_objs(self):\n self.order_params = []\n self.file_names = []\n self.indices = []\n\n self.file_name_cut = []\n self.basin_cut = []\n self.index_cut = []\n\n self.all_indices_0 = False\n\n @classmethod\n def from_set_paths(\n cls,\n minima_folder_path,\n ensemble_folder_path,\n run_folder_path,\n playground_folder_path,\n base_path,\n ):\n # set all paths explicitly\n # TODO this should be the default constructor\n # then we define an overclass as a wrapper\n obj = cls.__new__(cls)\n obj.radii, _, obj.box_length = load_run_parameters(base_path)\n obj.minima_folder_path = minima_folder_path\n obj.random_plane_folder_path = ensemble_folder_path\n obj.run_folder_path = run_folder_path\n obj.playground_folder_path = playground_folder_path\n os.makedirs(obj.playground_folder_path, exist_ok=True)\n obj.initialize_objs()\n return obj\n\n @classmethod\n def from_identification_parameters(\n cls, run_folder_path, plane_folder_name, tolerance\n ):\n \"\"\"\n Generates class from run parameters\n # sample minima folder path: /tests/test_data_ip/ndim=2phi=0.9seed=0n_part=8r1=1.0r2=1.4rstd1=0.05rstd2=0.06999999999999999use_cell_lists=1.0power=2.5eps=1.0/primary_analysis/minima_database0.01\n # sample run folder path: ./test_data_ip//ndim=2phi=0.85seed=0n_part=16r1=1.0r2=1.4rstd1=0.05rstd2=0.06999999999999999use_cell_lists=0power=2.5eps=1.0/results/random_plane24_quench_cvode_opt\n \"\"\"\n\n run_folder_list = run_folder_path.split(\"/\")\n run_folder_name = run_folder_list[-1]\n minima_folder_path = \"/\".join(run_folder_list[:-2])\n minima_folder_path += (\n \"/\"\n + PRIMARY_ANALYSIS_FOLDER_NAME\n + \"/\"\n + MINIMA_DATABASE_FOLDER_NAME\n + str(tolerance)\n )\n return cls(minima_folder_path, run_folder_name, plane_folder_name)\n\n def generate_plot_map(self):\n \"\"\"Generate a map from the mesh grid to the file names.\n\n Parameters\n ----------\n minima_folder_path : str\n path to the folder containing the minima data\n run_folder_name : str\n name of the run folder\n\n Returns\n -------\n plot_map : [np.ndarray, np.ndarray]\n Map from the mesh grid to the the order of the identified minima.\n The index defines the map between the mesh to the file names.\n \"\"\"\n\n # first load order parameters filenames and indices\n self.order_params = np.loadtxt(\n self.minima_folder_path + \"/\" + \"order_params.txt\"\n )\n self.file_names = np.loadtxt(\n self.minima_folder_path + \"/\" + \"filenames.txt\", dtype=int\n )\n self.indices = np.loadtxt(\n self.minima_folder_path + \"/\" + \"indices.txt\", dtype=int\n )\n\n unique_file_names = np.unique(self.file_names)\n\n mesh_list = []\n for file_name in unique_file_names:\n mesh_list.append(\n np.loadtxt(\n self.random_plane_folder_path\n + \"/\"\n + str(int(np.rint(file_name)))\n + \"_mesh.txt\",\n delimiter=\",\",\n )\n )\n print(unique_file_names)\n print(len(mesh_list))\n print(self.file_names)\n\n print(len(unique_file_names), \"unique file names\")\n\n file_name_to_mesh_dict = dict(zip(unique_file_names, mesh_list))\n\n # load corresponding mesh grid\n corresponding_mesh_list = []\n if np.all(self.indices == 0):\n self.all_indices_0 = True\n else:\n self.all_indices_0 = False\n\n for i, order_param in enumerate(self.order_params):\n corresponding_file_name = self.file_names[i]\n corresponding_index = self.indices[i]\n if self.all_indices_0:\n corresponding_mesh_coords = file_name_to_mesh_dict[\n corresponding_file_name\n ]\n else:\n corresponding_mesh_coords = file_name_to_mesh_dict[\n corresponding_file_name\n ][int(corresponding_index)]\n corresponding_mesh_list.append(corresponding_mesh_coords)\n return [np.array(corresponding_mesh_list)]\n\n def get_minima_folder_and_plane_folder(\n self, minima_folder_path, run_folder_name, plane_folder_name\n ):\n # change path to follow minima folder\n minima_folder_path_as_list = minima_folder_path.split(\"/\")\n # minima_folder_path_as_list = np.insert(\n # minima_folder_path_as_list, -1, run_folder_name\n # )\n minima_folder_path = \"/\".join(minima_folder_path_as_list)\n print(minima_folder_path_as_list)\n ensemble_folder_path = (\n \"/\".join(minima_folder_path_as_list[:-4])\n + \"/\"\n + ENSEMBLE_FOLDER_NAME\n )\n random_plane_folder_path = (\n ensemble_folder_path + \"/\" + plane_folder_name\n )\n\n return minima_folder_path, random_plane_folder_path\n\n def generate_mesh_grid_file_name_map(self, random_plane_folder_path):\n \"\"\"\n Generate a map from the mesh grid to the file names.\n \"\"\"\n # load the mesh grid from the ensemble folder\n\n # load the file names from the ensemble folder\n file_names = os.listdir(random_plane_folder_path)\n\n # get those file names that end with mesh.txt\n self.mesh_file_names = [\n file_name\n for file_name in file_names\n if file_name.endswith(\"mesh.txt\")\n ]\n self.coords_file_names = [\n mesh_file_name.replace(\"mesh.txt\", \"coords.txt\")\n for mesh_file_name in self.mesh_file_names\n ]\n\n # load all arrays from mesh_file_names:\n mesh_list = [\n np.loadtxt(\n random_plane_folder_path + \"/\" + mesh_file_name, delimiter=\",\"\n )\n for mesh_file_name in self.mesh_file_names\n ]\n # case for when mesh_list is of length 1\n if len(mesh_list.shape) == 2:\n mesh_l_flattened = mesh_list\n else:\n mesh_l_flattened = []\n for mesh_coords_list in mesh_list:\n for mesh_coords in mesh_coords_list:\n mesh_l_flattened.append(mesh_coords)\n # since the map is already set we can just return them as two lists.\n # The index defines the map between the mesh to the file names.\n return [np.array(mesh_l_flattened), self.coords_file_names]\n\n def generate_cut_2d(self, mesh_arr):\n \"\"\"Generates a cut of the basins of attraction,\n where each basin is represented by it's respective order parameter\n\n Parameters\n ----------\n mesh_arr : np.ndarray\n list of 2d mesh points\n order_params_list : np.ndarray[int]\n corresponding order parameters\n Returns\n ----------\n basin_cut : np.ndarray\n 2d array that describes the order parameter of the cuts\n mesh_extent : [float, float, float, float]\n extent of the mesh. Used to set the extent of the plot\n slightly displaced by the delta_x, delta_y\n \"\"\"\n mesh_arr = np.array(mesh_arr)[0]\n\n # transform mesh array into a 2d index list\n # get minimum x and y values of mesh_arr\n unique_x = np.unique(mesh_arr[:, 0])\n unique_y = np.unique(mesh_arr[:, 1])\n\n argsort_x = np.argsort(unique_x)\n argsort_y = np.argsort(unique_y)\n\n max_x = unique_x[argsort_x[-1]]\n max_y = unique_y[argsort_y[-1]]\n min_x = unique_x[argsort_x[0]]\n min_y = unique_y[argsort_y[0]]\n min_2nd_x = unique_x[argsort_x[1]]\n min_2nd_y = unique_y[argsort_y[1]]\n\n # assumes equidistant spacing in x and y\n spacing_x = min_2nd_x - min_x\n spacing_y = min_2nd_y - min_y\n\n # convert x_axis to indices\n index_arr = np.full_like(mesh_arr, 1, dtype=int)\n # rint for correct rounding\n index_arr[:, 0] = np.rint((mesh_arr[:, 0] - min_x) / spacing_x).astype(\n int\n )\n index_arr[:, 1] = np.rint((mesh_arr[:, 1] - min_y) / spacing_y).astype(\n int\n )\n\n max_ind_x = np.rint((max_x - min_x) / spacing_x).astype(int)\n max_ind_y = np.rint((max_y - min_y) / spacing_y).astype(int)\n\n # cut of the order parameters\n self.basin_cut = np.zeros((max_ind_y + 1, max_ind_x + 1), dtype=int)\n\n # file_name and index uniquely the coordinates of the cut\n self.file_name_cut = np.zeros(\n (max_ind_y + 1, max_ind_x + 1), dtype=int\n )\n self.index_cut = np.zeros((max_ind_y + 1, max_ind_x + 1), dtype=int)\n\n # note that the orders are switched when specifying indices\n # x corresponds to column and y corresponds to row\n for i, order_param in enumerate(self.order_params):\n self.basin_cut[index_arr[i, 1], index_arr[i, 0]] = order_param\n self.file_name_cut[\n index_arr[i, 1], index_arr[i, 0]\n ] = self.file_names[i]\n self.index_cut[index_arr[i, 1], index_arr[i, 0]] = self.indices[i]\n # return the cut and corresponding mesh extent\n # TODO: The mesh extent is always the same considering it's a unit mesh.\n # get the extent from config.yaml file.\n return [0, len(unique_x), 0, len(unique_y)]\n\n def process_cut(self):\n \"\"\"Generates the cut data and the range over which the plot is made\"\"\"\n mesh_l = self.generate_plot_map()\n\n extent = self.generate_cut_2d(mesh_l)\n return extent\n\n def save_cut_2d(self, title=\"basin_cut\", show=True):\n \"\"\"Generates and saves a plot of the cut for the runs in the ensemble folder\n\n Parameters\n ----------\n minima_folder_path : str\n path to the minima\n run_folder_name : str\n name of the folder containing the runs\n plane_folder_name : str\n name of the folder containing the plane ensemble\n \"\"\"\n extent = self.process_cut()\n\n save_folder = self.minima_folder_path\n cut = self.plot_cut_2d(extent, save_folder, title=title, show=True)\n return cut\n\n def plot_cut_2d(\n self, mesh_extent, save_folder=None, title=\"basin_cut\", show=False\n ):\n \"\"\"Plots a 2d cut of the basins of attraction\n\n Parameters\n ----------\n basin_cut : np.ndarray\n a cut of the basins\n mesh_extent : [float, float, float, float]\n extent of the mesh. Used to set the extent of the plot\n slightly displaced by the delta_x, delta_y\n \"\"\"\n\n def plot_configuration(mouseevent):\n \"\"\"Plots the corresponding configuration of the points that are clicked on\n\n Parameters\n ----------\n mouseevent : matplotlib.backend_bases.MouseEvent\n mouse event that is triggered when a point is clicked\n \"\"\"\n x_index = int(np.floor(mouseevent.xdata))\n y_index = int(np.floor(mouseevent.ydata))\n\n # location data of configuration\n file_name_int = self.file_name_cut[y_index, x_index]\n file_index = self.index_cut[y_index, x_index]\n order_param_of_config = self.basin_cut[y_index, x_index]\n\n coord_file_name = str(file_name_int) + \"_coords.txt\"\n coords_path = self.run_folder_path + \"/\" + coord_file_name\n coords = np.loadtxt(coords_path)[file_index]\n coords = coords.reshape(len(coords) // 2, 2)\n fig_location = (\n self.playground_folder_path\n + \"/x_\"\n + str(x_index)\n + \"y_\"\n + str(y_index)\n )\n\n # resave configuration to file for comparison\n np.savetxt(fig_location + \".txt\", coords)\n title = (\n \"x_\"\n + str(x_index)\n + \"y_\"\n + str(y_index)\n + \"\\norder_param: \"\n + str(order_param_of_config)\n + \"\\nfile_name_int: \"\n + str(file_name_int)\n + \" file_index: \"\n + str(file_index)\n )\n\n save_configuration_2d(\n self.radii,\n coords,\n self.box_length,\n fig_location,\n title=title,\n show=True,\n )\n\n # # rattler saving\n rattler_fig_location = fig_location + \"_with_rattlers\"\n save_configuration_2d(\n self.radii,\n coords,\n self.box_length,\n rattler_fig_location,\n title=title,\n show=True,\n # disc_colors=rattler_color_mask,\n )\n plt.show()\n\n # set the extent of the plot\n vmin = 0\n vmax = len(GLASBEY) - 1\n fig, ax = plt.subplots(figsize=(10, 10))\n ax.set_title(title)\n ax.imshow(\n self.basin_cut,\n extent=mesh_extent,\n cmap=GLASBEY_COLORMAP,\n vmin=vmin,\n vmax=vmax,\n interpolation=\"none\",\n origin=\"lower\",\n )\n mplcursors.cursor(hover=True)\n fig.canvas.callbacks.connect(\"button_press_event\", plot_configuration)\n\n if save_folder is not None:\n os.makedirs(save_folder, exist_ok=True)\n plt.savefig(save_folder + \"/\" + title + \"_cut.pdf\")\n if show:\n plt.show()\n plt.close()\n return self.basin_cut\n\n\nclass InteractiveConfigViewerLJ(InteractiveConfigViewer):\n def __init__(\n self, minima_folder_path, run_folder_name, plane_folder_name\n ) -> None:\n \"\"\"Interactive Configuration viewer for LJ Clusters\"\"\"\n super().__init__(\n minima_folder_path, run_folder_name, plane_folder_name\n )\n\n def plot_cut_2d(\n self, mesh_extent, save_folder=None, title=\"basin_cut\", show=False\n ):\n \"\"\"Plots a 2d cut of the basins of attraction\n\n Parameters\n ----------\n basin_cut : np.ndarray\n a cut of the basins\n mesh_extent : [float, float, float, float]\n extent of the mesh. Used to set the extent of the plot\n slightly displaced by the delta_x, delta_y\n \"\"\"\n plotting_coords_list = []\n plotting_title_list = []\n\n def plot_configuration(mouseevent):\n \"\"\"Plots the corresponding configuration of the points that are clicked on\n\n Parameters\n ----------\n mouseevent : matplotlib.backend_bases.MouseEvent\n mouse event that is triggered when a point is clicked\n \"\"\"\n\n def subtract_com(coords):\n coords = coords.reshape(-1, 3)\n com = np.mean(coords, axis=0)\n coords = coords - com\n return coords.reshape(-1)\n\n x_index = int(np.floor(mouseevent.xdata))\n y_index = int(np.floor(mouseevent.ydata))\n\n # location data of configuration\n file_name_int = self.file_name_cut[y_index, x_index]\n file_index = self.index_cut[y_index, x_index]\n order_param_of_config = self.basin_cut[y_index, x_index]\n\n coord_file_name = str(file_name_int) + \"_coords.txt\"\n coords_path = self.run_folder_path + \"/\" + coord_file_name\n coords = np.loadtxt(coords_path)[file_index]\n # coords = coords.reshape(len(coords) // 2, 2)\n fig_location = (\n self.playground_folder_path\n + \"/x_\"\n + str(x_index)\n + \"y_\"\n + str(y_index)\n )\n\n # resave configuration to file for comparison\n np.savetxt(fig_location + \".txt\", coords)\n title = (\n \"x_\"\n + str(x_index)\n + \"y_\"\n + str(y_index)\n + \"\\norder_param: \"\n + str(order_param_of_config)\n + \"\\nfile_name_int: \"\n + str(file_name_int)\n + \" file_index: \"\n + str(file_index)\n )\n\n subtract_com(coords)\n plotting_coords_list.append(coords)\n plotting_title_list.append(title)\n\n # set the extent of the plot\n vmin = 0\n vmax = len(GLASBEY) - 1\n fig, ax = plt.subplots(figsize=(10, 10))\n ax.set_title(title)\n ax.imshow(\n self.basin_cut,\n extent=mesh_extent,\n cmap=GLASBEY_COLORMAP,\n vmin=vmin,\n vmax=vmax,\n interpolation=\"none\",\n origin=\"lower\",\n )\n mplcursors.cursor(hover=True)\n fig.canvas.callbacks.connect(\"button_press_event\", plot_configuration)\n\n if save_folder is not None:\n os.makedirs(save_folder, exist_ok=True)\n plt.savefig(save_folder + \"/\" + title + \"_cut.pdf\")\n if show:\n plt.show()\n plt.close()\n for i, coords in enumerate(plotting_coords_list):\n title = plotting_title_list[i]\n pym.start()\n print(repr(coords))\n pym.draw_spheres(coords, title, 1, radius=0.56)\n pymol.finish_launching()\n return self.basin_cut\n\n\ndef save_cut_2d(\n minima_folder_path,\n run_folder_name,\n plane_folder_name,\n title=None,\n order_params_file_name=ORDER_PARAMS_FILE_NAME,\n):\n \"\"\"Generates and saves a plot of the cut for the runs in the ensemble folder\n\n Parameters\n ----------\n minima_folder_path : str\n path to the minima\n run_folder_name : str\n name of the folder containing the runs\n plane_folder_name : str\n name of the folder containing the plane ensemble\n \"\"\"\n # change path to follow minima folder\n minima_folder_path, random_plane_folder_path = generate_paths(\n minima_folder_path, run_folder_name, plane_folder_name\n )\n save_cut_location_specified(\n minima_folder_path, random_plane_folder_path, title=title\n )\n\n\ndef save_cut_location_specified(\n minima_folder_path,\n random_plane_folder_path,\n title=None,\n save_folder=None,\n show=False,\n color_map=None,\n order_params_file_name=ORDER_PARAMS_FILE_NAME,\n save_extension=DEFAULT_SAVE_EXTENSION,\n post_process=True,\n):\n cut, extent = process_cut(\n minima_folder_path,\n random_plane_folder_path,\n order_params_file_name=order_params_file_name,\n )\n if save_folder is None:\n return plot_cut_2d(\n cut,\n extent,\n minima_folder_path,\n title=title,\n show=show,\n color_map=color_map,\n save_extension=save_extension,\n post_process=post_process,\n )\n else:\n return plot_cut_2d(\n cut,\n extent,\n save_folder,\n title=title,\n show=show,\n color_map=color_map,\n save_extension=save_extension,\n post_process=post_process,\n )\n\n\ndef save_cut_distributed(minima_folder_path, ensemble_path, title=None):\n # find all sub ensemble folder names\n ensemble_folder_names = os.listdir(ensemble_path)\n\n for ensemble_folder_name in ensemble_folder_names:\n ensemble_folder = os.path.join(ensemble_path, ensemble_folder_name)\n minima_subfolder_path = os.path.join(\n minima_folder_path, ensemble_folder_name\n )\n if not (\n os.path.isfile(\n os.path.join(\n minima_subfolder_path, \"concatenated_order_params.txt\"\n )\n )\n ):\n continue\n save_cut_location_specified(\n minima_subfolder_path, ensemble_folder, title=title\n )\n\n\ndef save_cut_distributed_specified_frames(\n minima_folder_path, ensemble_path, title=None, frames=20\n):\n ensemble_folder_names = os.listdir(ensemble_path)\n\n ensemble_folder_floats = [\n float(ensemble_folder_name)\n for ensemble_folder_name in ensemble_folder_names\n ]\n\n sorted_args = np.argsort(ensemble_folder_floats)\n\n ensemble_folder_names_sorted = [\n ensemble_folder_names[i] for i in sorted_args\n ]\n\n ensemble_folder_names = ensemble_folder_names_sorted[:frames]\n\n for ensemble_folder_name in ensemble_folder_names:\n ensemble_folder = os.path.join(ensemble_path, ensemble_folder_name)\n minima_subfolder_path = os.path.join(\n minima_folder_path, ensemble_folder_name\n )\n save_cut_location_specified(\n minima_subfolder_path, ensemble_folder, title=title\n )\n\n\ndef process_cut(\n minima_folder_path,\n random_plane_folder_path,\n order_params_file_name=ORDER_PARAMS_FILE_NAME,\n):\n \"\"\"Generates the cut data and the range over which the plot is made\"\"\"\n mesh_l, order_param_arr = generate_plot_map(\n minima_folder_path,\n random_plane_folder_path,\n order_params_file_name=order_params_file_name,\n )\n cut, extent = generate_cut_2d(mesh_l, order_param_arr)\n return cut, extent\n\n\ndef get_basin_areas(cut: np.ndarray, ignore_boundary_basins: bool = False):\n \"\"\"Given the pixel data for the cut, identify the areas for each basin.\n\n Parameters\n ----------\n cut : ndarray\n Cut of the basins, 1D array of ints.\n ignore_boundary_basins : bool, optional\n If True, ignore basins touching the boundary of the array.\n\n Returns\n ----------\n hist_data : list\n List of the areas of each basin.\n \"\"\"\n # Get the unique ids of each color.\n length = int(cut.size**0.5)\n\n basin_ids = np.unique(cut)\n # Initialize an array to store the areas of the basins.\n basin_areas = np.zeros(len(basin_ids))\n cut = cut.reshape(length, length)\n # If ignore_boundary_basins is True, find the basin ids that touch the boundary.\n if ignore_boundary_basins:\n boundary_basins = (\n set(cut[0, :]) | set(cut[-1, :]) | set(cut[:, 0]) | set(cut[:, -1])\n )\n else:\n boundary_basins = set()\n cut = cut.reshape(-1)\n\n # Iterate over the unique basin ids.\n for i, basin_id in enumerate(basin_ids):\n # If the basin_id is in the boundary_basins set, skip it.\n if basin_id in boundary_basins:\n continue\n\n # Count the occurrences of the basin_id in the cut.\n basin_area = np.count_nonzero(cut == basin_id)\n\n # Store the basin area in the corresponding index in the basin_areas array.\n basin_areas[i] = basin_area\n\n # Remove zero values from the basin_areas array since we skipped counting boundary basins.\n basin_areas = basin_areas[basin_areas != 0]\n\n return basin_areas\n\n\n\n\ndef plot_heatmap(\n minima_folder_path,\n run_folder_name,\n plane_folder_name,\n heuristic_to_map,\n vmin=None,\n vmax=None,\n show=False,\n):\n \"\"\"Generates a heatmap of the heuristics over the given set of points\n\n Parameters\n ----------\n minima_folder_path : str\n Path to the folder of identified minim\n run_folder_name : str\n name of the run folder\n plane_folder_name : str\n Name of the folder containing the plane ensemble\n heuristic_to_map: str\n Name of the heuristic in the saved run heuristics dictionary\n \"\"\"\n heuristics_cut, extent = get_heuristics_heatmap(\n minima_folder_path,\n run_folder_name,\n plane_folder_name,\n heuristic_to_map,\n )\n save_folder = minima_folder_path + \"/\" + run_folder_name\n if heuristic_to_map == \"energy\":\n tols = [1e-3, 1e-4, 1e-5, 1e-6]\n\n for tol in tols:\n energy_cluster_identification(\n heuristics_cut, extent, tol, show=show, save_folder=save_folder\n )\n\n plt.imshow(np.log(heuristics_cut), extent=extent, vmin=vmin, vmax=vmax)\n plt.colorbar()\n plt.savefig(\n minima_folder_path\n + \"/\"\n + run_folder_name\n + \"/\"\n + heuristic_to_map\n + \".pdf\"\n )\n if show:\n plt.show()\n plt.close()\n\n\ndef get_heuristics_heatmap(\n minima_folder_path, run_folder_name, plane_folder_name, heuristic_to_map\n):\n minima_folder_path_as_list = minima_folder_path.split(\"/\")\n ensemble_folder_path = (\n \"/\".join(minima_folder_path_as_list[:-2])\n + \"/\"\n + ENSEMBLE_FOLDER_NAME\n + \"/\"\n + plane_folder_name\n )\n\n heuristics_path = (\n \"/\".join(minima_folder_path_as_list[:-2])\n + \"/\"\n + FINAL_COORDS_FOLDER_NAME\n + \"/\"\n + run_folder_name\n )\n mesh_list, coords_file_names = generate_mesh_grid_file_name_map(\n ensemble_folder_path\n )\n corresponding_heuristics = get_corresponding_heuristics(\n heuristics_path, coords_file_names, heuristic_to_map\n )\n\n heuristics_heatmap, extent = generate_cut_2d(\n mesh_list, corresponding_heuristics\n )\n return heuristics_heatmap, extent\n\n\ndef energy_cluster_identification(\n heuristics_cut,\n extent,\n tol,\n show=False,\n save_folder=None,\n save_extension=DEFAULT_SAVE_EXTENSION,\n):\n cut = cluster_minima(heuristics_cut.flatten(), tol)\n title = \"energy_roundoff=\" + str(int(-np.log(tol)))\n plot_cut_2d(\n cut,\n extent,\n save_folder=save_folder,\n title=title,\n show=show,\n save_extension=save_extension,\n )\n\n\ndef get_corresponding_heuristics(\n heuristics_path, coords_file_names, heuristic_to_map\n):\n \"\"\"Gets the corrsponding heuristics given coords_file_names\n\n Parameters\n ----------\n heuristics_path : str\n path to the results of the run where the heuristics are saved\n coords_file_names : list[str]\n list of filenames of the coordinates\n heuristic_to_map : str\n key for the heuristics in the file\n \"\"\"\n if heuristic_to_map == \"energy\":\n return get_corresponding_energy(heuristics_path, coords_file_names)\n\n heuristics_file_names = [\n coords_file_name.replace(\"_coords.txt\", \".yaml\")\n for coords_file_name in coords_file_names\n ]\n heuristics_list = []\n for heuristic_file_name in heuristics_file_names:\n # open the yaml dicts\n if heuristic_to_map == \"energy\":\n final_coords = np.loadtxt(\n heuristics_path + \"/\" + coords_file_names\n )\n with open(\n heuristics_path + \"/\" + heuristic_file_name, \"r\"\n ) as heuristics_file:\n heuristics_dict_list = yaml.load(\n heuristics_file, Loader=yaml.FullLoader\n )\n # case for length = 1\n if isinstance(heuristics_dict_list, dict):\n heuristics_dict_list = [heuristics_dict_list]\n for heuristics_dict in heuristics_dict_list:\n heuristics_list.append(heuristics_dict[heuristic_to_map])\n return heuristics_list\n\n\ndef get_corresponding_energy(heuristics_path, coords_file_names):\n \"\"\"Gets the corrsponding heuristics given coords_file_names\n\n Parameters\n ----------\n heuristics_path : str\n path to the results of the run where the heuristics are saved\n coords_file_names : list[str]\n list of filenames of the coordinates\n heuristic_to_map : str\n key for the heuristics in the file\n \"\"\"\n heuristics_path_list = heuristics_path.split(\"/\")\n potential = setup_inverse_power_from_folder(\n \"/\".join(heuristics_path_list[:-2])\n )\n energy_list = []\n for coords_file_name in coords_file_names:\n # open the yaml dicts\n # case for length = 1\n coords = np.loadtxt(heuristics_path + \"/\" + coords_file_name)\n if coords.ndim == 1:\n energy = potential.getEnergy(coords)\n else:\n for coord in coords:\n energy = potential.getEnergy(coord)\n energy_list.append(energy)\n return energy_list\n\n\ndef cluster_minima(energy_list, tolerance):\n \"\"\"Identifies clusters of points with the same energy on the plane of the cut.\n Points belong the same cluster if they are contiguous up to nearest neighbors\n and have the same energy up to a tolerance.\n\n Separately deals with the case when the energy is close to zero. In that case\n the energy is set to zero and the state is assumed to be fluid only.\n\n\n\n Parameters\n ----------\n energy_list: list[float]\n flattened array of energies. (Assumed to be square).\n\n Returns:\n clusters: list[int]\n \"\"\"\n\n rounded_energy_array = get_rounded_energies(energy_list, tolerance)\n # whether the site has been visited during the search\n not_visited_sites = np.ones_like(rounded_energy_array, dtype=bool)\n # this serves as a mask for the search.\n\n # the integer should uniquely identify the cluster\n basin_identities = np.zeros_like(rounded_energy_array, dtype=int)\n # identitifies connected clusters based on energy.\n unique_rounded_energies = np.unique(rounded_energy_array)\n # offset that ensures that each\n # disconnected region is identified by a unique integer\n\n # # separately identify close to zero energies as one minima only.\n # sites_with_zero_energy_mask = np.where(unique_rounded_energies < tolerance)\n\n uniqueness_offset = 0\n for energy in unique_rounded_energies:\n # get the sites with the current energy\n sites_with_same_energy_mask = (rounded_energy_array == energy).astype(\n np.uint8\n )\n # identify contiguous clusters\n num_labels, labels_im = cv2.connectedComponents(\n sites_with_same_energy_mask, connectivity=8\n )\n offset = (labels_im != 0) * uniqueness_offset + labels_im\n basin_identities = basin_identities + offset\n # define offset for the next set of disconnected regions\n uniqueness_offset = uniqueness_offset + np.max(labels_im)\n\n # checks to ensure no overcounts or undercounts\n assert np.max(basin_identities) == len(np.unique(basin_identities))\n return basin_identities\n\n\ndef get_rounded_energies(energy_list, tolerance):\n energy_array = np.array(energy_list)\n # round all energies to the tolerance\n rounded_energy_array = np.round(\n energy_array, decimals=-np.log10(tolerance).astype(int)\n )\n\n side_length = np.sqrt(len(energy_array))\n if side_length % 1 != 0:\n raise ValueError(\"Length of energy_list must be a perfect square.\")\n\n side_length = int(side_length)\n\n rounded_energy_array = rounded_energy_array.reshape(\n side_length, side_length\n )\n\n return rounded_energy_array\n\n\ndef plot_cut_2d(\n basin_cut,\n mesh_extent,\n save_folder=None,\n title=None,\n show=False,\n video_mode=True,\n color_map=None,\n post_process=True,\n save_extension=\".svg\",\n):\n \"\"\"Plots a 2d cut of the basins of attraction\n Parameters\n ----------\n basin_cut : np.ndarray\n a cut of the basins\n mesh_extent : [float, float, float, float]\n extent of the mesh. Used to set the extent of the plot\n slightly displaced by the delta_x, delta_y\n \"\"\"\n # set the extent of the plot\n # offset\n vmin = -2\n vmax = len(GLASBEY) - 1 + vmin\n fig, ax = plt.subplots(figsize=(10, 10))\n # ax.set_title(title)\n\n if color_map is None:\n color_map = GLASBEY_COLORMAP\n\n if post_process:\n basin_cut = post_process_cut(basin_cut)\n print(\n \"basin cut\",\n )\n color_map.set_over(\"white\")\n color_map.set_under(\"black\")\n ax.imshow(\n basin_cut,\n extent=mesh_extent,\n cmap=color_map,\n vmin=vmin,\n vmax=vmax,\n interpolation=\"none\",\n )\n plt.axis(\"off\")\n mplcursors.cursor(hover=True)\n if save_folder is not None:\n os.makedirs(save_folder, exist_ok=True)\n # np.savetxt(save_folder + \"/\" + title + \".txt\", basin_cut, dtype=int)\n np.savetxt(save_folder + \"/\" + title + \"_cut_data\" + \".txt\", basin_cut)\n plt.savefig(\n save_folder + \"/\" + title + \"_cut\" + save_extension,\n bbox_inches=\"tight\",\n pad_inches=0.0,\n )\n if show:\n plt.show()\n plt.close(\"all\")\n return basin_cut\n\n\ndef post_process_cut(basin_cut):\n \"\"\"Check that the any basin point surrounded completely by other basin points\n is removed.\n This is for correcting failed runs in the final image.\n Parameters\n ----------\n basin_cut : _type_\n _description_\n \"\"\"\n i_max, j_max = basin_cut.shape\n # if we get this mask, we know that the basin point is surrounded by other basin points\n expected_mask = [\n [True, True, True],\n [True, False, True],\n [True, True, True],\n ]\n for i in range(1, i_max - 1):\n for j in range(1, j_max - 1):\n point = basin_cut[i, j]\n if point == -1:\n # apply majority rule for -1\n neighbor = basin_cut[i, j + 1]\n neighbors = basin_cut[i - 1 : i + 2, j - 1 : j + 2]\n counts_and_values = collections.Counter(\n neighbors.flatten()\n ).most_common()\n most_common = counts_and_values[0][0]\n if most_common == -1:\n most_common = counts_and_values[1][0]\n print(\"Removing basin point at ({}, {})\".format(i, j))\n basin_cut[i, j] = most_common\n return basin_cut\n\n\ndef make_video(minima_folder_path, image_name=\"test_video_cut.pdf\", frames=20):\n print(\"Making video\")\n minima_folder_contents = os.listdir(minima_folder_path)\n\n image_extension = image_name.split(\".\")[-1]\n\n minima_folder_contents_paths = [\n os.path.join(minima_folder_path, x) for x in minima_folder_contents\n ]\n paths = [\n minima_folder_dir\n for minima_folder_dir in minima_folder_contents_paths\n if os.path.isdir(minima_folder_dir)\n ]\n\n video_folder = os.path.join(minima_folder_path, \"video\")\n concatenated_minima_folder = os.path.join(\n minima_folder_path, \"concatenated_minima\"\n )\n\n # remove video folder from paths\n paths = [x for x in paths if x != video_folder]\n paths = [x for x in paths if x != concatenated_minima_folder]\n\n foldnames = [os.path.basename(x) for x in paths]\n float_foldnames = [float(x) for x in foldnames]\n sorted_folders = np.argsort(float_foldnames)\n paths = [paths[i] for i in sorted_folders]\n\n os.makedirs(video_folder, exist_ok=True)\n paths = paths[:frames]\n for i, path in enumerate(paths):\n print(\"Processing {}\".format(path))\n print(\"i: {}\".format(i))\n image_path = os.path.join(path, image_name)\n # copy images into video folder with the same name as the corresponding folder\n corresponding_folder_name = os.path.basename(path)\n print(image_path)\n shutil.copy(\n image_path,\n os.path.join(\n video_folder, \"frame\" + str(i) + \".\" + image_extension\n ),\n )\n os.system(\"convert -delay 10 -loop 0 *.pdf video.gif\")\n","repo_name":"martiniani-lab/basinerror","sub_path":"basinerror/analysis/cuts.py","file_name":"cuts.py","file_ext":"py","file_size_in_byte":47701,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"42723924396","text":"\"\"\"\nDeveloped by Aindriya Barua.\nPython Version : 3.8.1 64-bit.\n\nThis is the starting point of the project which has to be run. It calls the file reader, scraper, output writer\n\"\"\"\n\n\nimport sys\nimport mass_links_scraper\nimport pandas as pd\nimport re\n\nimport constants\nimport output_writer\nimport scraper\n\ndef mass_scraper_main(links_file):\n links = read_links_file(links_file)\n driver = scraper.make_driver()\n # If we are not logged in, we can't load more comments\n scraper.manual_login()\n comments = []\n for link in links:\n link = str(link).strip()\n if link is not None and '\\n' != link:\n if(re.match(r'^' + constants.VALID_IG_LINK ,str(link))):\n print(\"Scraping... \" + link)\n comments.append('\\n')\n comments.append(link)\n comments.append('\\n')\n link_comments = scraper.scraper_main(link)\n comments += link_comments\n \n driver.close()\n output_writer.write_output(comments)\n\n\ndef read_links_file(links_file):\n xl = pd.ExcelFile(links_file)\n df = xl.parse(constants.INPUT_SHEET_NAME, index=False)\n links = df[constants.LINKS_COLUMN_NAME].to_list()\n return links\n\nif __name__ == '__main__':\n links_filepath = constants.INPUT_FILENAME\n mass_scraper_main(links_filepath)\n \n","repo_name":"AindriyaBarua/instagram-comments-scraper-for-NLP-data-collection","sub_path":"venv/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"70039165690","text":"DATASET_DIR = \"./data\"\nVALID_RATIO = 0.2 # Going to use 80%/20% split for train/valid\n\nMAX_BB_EVAL = 100 # Max number of blackbox evaluations\n\nEPOCHS = 100\nEARLY_STOP = True\n\nNUM_WORKERS = 4\n\nPRINT = False\nPRINT_PYNOMAD = True\nDEFAULT_OPTIMIZER_SETTINGS = False\n\n# Fashion MNIST --------------------------------------------\nINPUT_SIZE_FASHION = 28 # size image 28*28 \nINPUT_CHANNELS_FASHION = 1 # 1 channel : black and white pictures\nNUM_CLASSES_FASHION = 10 \n\n# CIFAR-10 ------------------------------------------------\nINPUT_SIZE_CIFAR = 32 # size image 32*32\nINPUT_CHANNELS_CIFAR = 3 # 3 channels : RGB\nNUM_CLASSES_CIFAR = 10","repo_name":"Amaurydpk/Hyperparameters_Optim","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"14548673287","text":"\n\ndef cycle(graph):\n queue = []\n visited = [False for _ in range(len(graph))]\n parents = [None for _ in range(len(graph))]\n visited[0] = True\n queue.append(0)\n\n while queue:\n s = queue.pop(0)\n for v in graph[s]:\n if parents[s] != v and v != s:\n if visited[v] is False:\n queue.append(v)\n visited[v] = True\n parents[v] = s\n else:\n return True\n return False\n\n\nif __name__ == '__main__':\n graph = [[1, 2], [0, 2, 3], [0, 1], [1]]\n\n print(cycle(graph))","repo_name":"pvtrov/algorithms-and-data-structures","sub_path":"algorithms_implementations/graph_algorithms/list_representation/bfs_cycles.py","file_name":"bfs_cycles.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"7587453634","text":"from django.conf.urls import include\nfrom rest_framework import routers\nfrom api.views import AllUserDonations,AtrocityList, CategoryList, CompanyList, FeaturedShirts, NonProfitList, NpProject, RatingViewSet, RefugeeShirts, RegisterCompany, RegisterNonProfit , ShirtList, ShirtVariationsList, UserCompletedOrders, UserProfileView, UserViewSet, LinkList, UserOrder\nfrom django.urls import path, re_path\nfrom . import views\n\n\n\nrouter = routers.DefaultRouter()\nrouter.register(r'users', UserViewSet)\nrouter.register('ratings', RatingViewSet)\nrouter.register('shirts', ShirtList )\nrouter.register('nonprofits', NonProfitList)\nrouter.register('userprofile', UserProfileView)\nrouter.register('variations', ShirtVariationsList)\nrouter.register('atrocities', AtrocityList)\nrouter.register('order',UserOrder)\n# router.register('completedorders', UserCompletedOrders)\nrouter.register('categories', CategoryList)\nrouter.register('companies', CompanyList)\nrouter.register('userdonations',AllUserDonations)\nrouter.register('infolinks',LinkList)\n\n\n\n\n\n\nurlpatterns = [\n re_path(r'^', include(router.urls)),\n path('npList/', views.NonProfitByCategory.as_view()),\n path('shirtimages//?P\\D+', views.ShirtVariation.as_view()),\n # path('usernonprofits//', views.UserNonProfitsView.as_view()),\n # path('userprofiles//', views.UserProfileDetail.as_view()),\n path('profilepage/', views.UserProfileDetail.as_view()),\n path('refugeesshirts', views.RefugeeShirts.as_view()),\n path('worldpovertyshirts', views.PovertyShirts.as_view()),\n path('worldhungershirts', views.WorldHungerShirts.as_view()),\n path('featuredshirts', views.FeaturedShirts.as_view()),\n path('featuredatrocities', views.FeaturedAtrocities.as_view()),\n path('featurednonprofits', views.FeaturedNonProfits.as_view()),\n path('allusercompletedorders', views.AllUserCompletedOrders.as_view()),\n path('findusers', views.FindUserList.as_view()),\n path('followingDonations/', views.UserFollowerDonations.as_view()),\n path('registernp/', RegisterNonProfit.as_view()),\n path('registerCompany/', RegisterCompany.as_view()),\n path('createProject/', NpProject.as_view()),\n # path('cart', views.GetCart.as_view()),\n \n\n \n\n \n \n]","repo_name":"rnsiah/altbackend","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"12830309432","text":"\n\nfrom re import S\nimport sys\nfrom my_config import config\nfrom model.order import Order\nimport time\nfrom app.myApp import App\nimport urllib3\nurllib3.disable_warnings()\nbot = App()\n\ntype = \"testbacking\"\n# 版本1.2\n\nfor index, s in enumerate(sys.argv):\n if s == 'main.py':\n continue\n if index == 1:\n type = s\n continue\n s = s.split(\"=\")\n if s[0] == \"-t\":\n type = s\n\n\nprint('服务开始运行!长时间没反应请连接vpn')\n\n\ndef main(self):\n # 校验服务器时间\n bot.checktime()\n while True:\n bot.runBot()\n time.sleep(1)\n\n\nif type == 'testbacking':\n bot.testbacking()\nelif type == \"dev\":\n bot.run_dev()\nelif type == \"pro\":\n bot.run_pro()\n","repo_name":"webclinic017/mybot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"17465211753","text":"from typing import Optional\n\nfrom ax.core import Objective, OptimizationConfig\nfrom ax.core.objective import MultiObjective\nfrom ax.core.observation import ObservationFeatures\nfrom ax.core.optimization_config import (\n MultiObjectiveOptimizationConfig,\n ObjectiveThreshold,\n)\nfrom ax.core.risk_measures import RiskMeasure\nfrom ax.core.types import ComparisonOp\nfrom ax.exceptions.core import UnsupportedError\nfrom ax.metrics.branin import BraninMetric\nfrom ax.modelbridge.registry import Models\nfrom ax.models.torch.botorch_modular.surrogate import Surrogate\nfrom ax.utils.common.testutils import TestCase\nfrom ax.utils.testing.core_stubs import get_robust_branin_experiment\nfrom ax.utils.testing.mock import fast_botorch_optimize\nfrom botorch.acquisition.monte_carlo import qNoisyExpectedImprovement\nfrom botorch.acquisition.multi_objective.monte_carlo import (\n qNoisyExpectedHypervolumeImprovement,\n)\nfrom botorch.models.gp_regression import SingleTaskGP\n\n\nclass TestRobust(TestCase):\n @fast_botorch_optimize\n def test_robust(\n self,\n risk_measure: Optional[RiskMeasure] = None,\n optimization_config: Optional[OptimizationConfig] = None,\n acqf_class: Optional[str] = None,\n ) -> None:\n exp = get_robust_branin_experiment(\n risk_measure=risk_measure,\n optimization_config=optimization_config,\n )\n\n for _ in range(5):\n modelbridge = Models.BOTORCH_MODULAR(\n experiment=exp,\n data=exp.fetch_data(),\n surrogate=Surrogate(botorch_model_class=SingleTaskGP),\n botorch_acqf_class=acqf_class or qNoisyExpectedImprovement,\n )\n trial = (\n exp.new_trial(generator_run=modelbridge.gen(1)).run().mark_completed()\n )\n\n obs = ObservationFeatures(parameters=trial.arm.parameters)\n with self.assertRaisesRegex(NotImplementedError, \"one-to-many\"):\n modelbridge.predict([obs])\n\n def test_robust_multi_objective(self) -> None:\n risk_measure = RiskMeasure(\n risk_measure=\"MultiOutputExpectation\",\n options={\"n_w\": 16},\n )\n metrics = [\n BraninMetric(\n name=f\"branin_{i}\", param_names=[\"x1\", \"x2\"], lower_is_better=True\n )\n for i in range(2)\n ]\n optimization_config = MultiObjectiveOptimizationConfig(\n objective=MultiObjective(\n [\n Objective(\n metric=m,\n minimize=True,\n )\n for m in metrics\n ]\n ),\n objective_thresholds=[\n ObjectiveThreshold(metric=m, bound=10.0, relative=False)\n for m in metrics\n ],\n risk_measure=risk_measure,\n )\n self.test_robust(\n risk_measure,\n optimization_config,\n acqf_class=qNoisyExpectedHypervolumeImprovement,\n )\n\n def test_mars(self) -> None:\n risk_measure = RiskMeasure(\n risk_measure=\"MARS\",\n options={\"n_w\": 16, \"alpha\": 0.8},\n )\n metrics = [\n BraninMetric(\n name=f\"branin_{i}\", param_names=[\"x1\", \"x2\"], lower_is_better=False\n )\n for i in range(2)\n ]\n optimization_config = MultiObjectiveOptimizationConfig(\n objective=MultiObjective(\n [\n Objective(\n metric=m,\n minimize=False,\n )\n for m in metrics\n ]\n ),\n objective_thresholds=[\n ObjectiveThreshold(\n metric=m, bound=10.0, relative=False, op=ComparisonOp.GEQ\n )\n for m in metrics\n ],\n risk_measure=risk_measure,\n )\n self.test_robust(\n risk_measure,\n optimization_config,\n acqf_class=qNoisyExpectedImprovement,\n )\n\n def test_unsupported_model(self) -> None:\n exp = get_robust_branin_experiment()\n with self.assertRaisesRegex(UnsupportedError, \"support robust\"):\n Models.GPEI(\n experiment=exp,\n data=exp.fetch_data(),\n ).gen(n=1)\n","repo_name":"facebook/Ax","sub_path":"ax/modelbridge/tests/test_robust.py","file_name":"test_robust.py","file_ext":"py","file_size_in_byte":4389,"program_lang":"python","lang":"en","doc_type":"code","stars":2182,"dataset":"github-code","pt":"77"}
+{"seq_id":"29930001835","text":"\"\"\"\nPath integration\n\"\"\"\nimport numpy as np\n\nimport phase\nimport geopath\n\ndef PathInt(PA):\n PathInt = []\n fRange, pathRange = np.shape(PA)\n for i in range(fRange):\n Onef = 0\n IntRange, weight = FindIntRange(PA[i,:])\n for j in IntRange:\n Onef += weight[j] * phase.PhaseFactor(PA[i,j])\n PathInt += [Onef]\n return np.array(PathInt)\n\n# Window function for path integration\ndef FindIntRange(TotPath):\n width = 0.289\n dPath = np.gradient(TotPath)\n window = np.exp(-dPath**2/(2*(width)**2)) # window function = weight of each path\n IntRange = np.where(window > 3e-3)[0]\n return IntRange, window\n","repo_name":"quantumfx/binary-lens","sub_path":"pathint.py","file_name":"pathint.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"45026023704","text":"from dimacs import *\nfrom lab2 import fordFulkerson\nimport os\n\ndef wUndirectedToList(V, E):\n neib = [[] for i in range(V+1)]\n for (u, v, w) in E:\n neib[u].append(v)\n neib[v].append(u)\n return neib\n\ndef wUndirectedToMatrix(V, E):\n capacity = [[0 for i in range(V+1)] for i in range(V + 1)]\n for (u, v, w) in E:\n capacity[u][v] = w\n capacity[v][u] = w\n return capacity\n\ndef ffConnectivity(V, E):\n s = 1\n minEdges = float('inf')\n for t in range(2, V):\n neib = wUndirectedToList(V, E)\n capacity = wUndirectedToMatrix(V, E)\n minEdges = min(minEdges, fordFulkerson(V, neib, capacity, 1, t))\n return minEdges\n\ndirectory = \"graphs/\"\nfiles = [\"cycle\", \"simple\", \"trivial\", \"grid5x5\", \"geo20_2b\", \"path\", \"rand100_500\"]\n\nfor filename in files:\n (V, E) = loadWeightedGraph(os.path.join(directory, filename))\n print(\"Spójność krawędziowa dla \" + filename + \": \" + str(ffConnectivity(V, E)))","repo_name":"Pinioo/Algorytmy-Grafowe","sub_path":"Lab3/lab3.py","file_name":"lab3.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"20757795918","text":"# class Item:\n# def __init__(self):\n# x=True\n# itemid=input('enter the item id: ')\n# name=input('enter the name: ')\n# try:\n# costprice=float((input('enter the costprice: ')))\n# except:\n# print('wrong input')\n# x=False\n# if x==True:\n# category=(input('''choose the category:\n# 1)A 2)B\n# : '''))\n# if category=='A':\n# profit=8.5\n# sp=costprice+(costprice*profit)\n# elif category=='B':\n# profit=12.5\n# sp=costprice+(costprice*profit)\n# elif category!='A' or category!='B':\n# print('wrong category and it is case sensitive')\n# x=False\n# if x==True: \n# print('item id is : ',itemid)\n# print('item name is : ',name)\n# print('item costprice is : ',costprice)\n# print('item category is : ',category)\n# print('item selling price is : ',sp)\n \n# a=Item() \n\n###############################################################################\nclass Prime:\n def __init__(self,num):\n Prime.x=0\n self.num=num\n \n def display(self):\n if self.num>1:\n for i in range(2,self.num):\n if self.num%i==0:\n Prime.x=Prime.x+1\n if Prime.x>0:\n print(self.num,' is not a prime number')\n else:\n print(self.num,' is a prime number')\n else:\n print(self.num,' is not a prime number')\nb=int(input('enter a number: ')) \na=Prime(b)\na.display()\n\n# #################################################################################\n# class Pattern:\n# def __init__(self,chr,num):\n# self.chr=chr\n# self.num=num\n# def display(self):\n# print(self.chr*self.num)\n# p1=Pattern('*',15)\n# p1.display()\n \n\n###################################################################################\n# class Leap:\n# def __init__ (self,year):\n# self.year=year\n# def display(self):\n# if (self.year%4==0 and self.year%100!=0) or (self.year%400==0 and self.year%100==0):\n# print('it is leap year')\n# else:\n# print('it is not leap year')\n# a1=Leap(1999)\n# a1.display()\ndef isprime():\n primecount=0\n for i in range(2,11):\n con=False\n if i>1:\n for j in range(2,i):\n if i%j==0:\n con=True\n break\n if con==False:\n primecount+=1\n print('the number of prime number in the range is',primecount)\nisprime()","repo_name":"jimmy-khaidem/python_assignment","sub_path":"april1Assignment.py","file_name":"april1Assignment.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"30233095004","text":"from pytest import raises, mark, fixture\nfrom Source.test.db_demo import UsuarioDAO\n\n@mark.database\nclass TestClassBanco:\n @mark.database_success\n def test_quando_programa_valida_estrutura_banco_retorna_true(self):\n banco = UsuarioDAO('banco_testes.db')\n return banco.validar_estrutura_banco()\n\n @mark.database_failure\n def test_quando_programa_valida_estrutura_banco_retorna_exception_banco(self):\n with raises(Exception) as erro:\n banco = UsuarioDAO('banco_testes2.db')\n chave = 'usuario'\n return banco.validar_estrutura_banco()\n assert f'A estrura da tabela({chave}) não está com de acordo com as diretrizes do sistema' in str(erro.value)","repo_name":"Matheus-Sueth/FATEC_TG","sub_path":"Source/test/test_Banco.py","file_name":"test_Banco.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"30495257029","text":"import pandas as pd\nimport numpy as np\n\n#Hinds County totals are conflicting with statewide and need eating to match up with county precinct\n#Simpson County totals are conflicting with statewide but match up with county precinct\n#Also changes have yet to be applied to individual county files\n\nfile_name = '/Users/sammahle/Desktop/election_projects/openelections-data-ms/2015/20151103__ms__general__precinct.csv'\ndf = pd.read_csv(file_name)\n\ndf.district = df.district.fillna('0')\ndf.votes = df.votes.fillna('0')\ndf.votes = df.votes.astype(str)\ndf.votes = df.votes.str.replace(',','')\ndf.votes = df.votes.str.replace(r'\\*','0')\ndf.votes = df.votes.str.replace('X','0')\ndf.votes = df.votes.str.replace('x','0')\ndf.votes = df.votes.apply(pd.to_numeric, errors='coerce')\ndf.votes = df.votes.astype(float)\n\ndf.loc[df.precinct=='600 DE SOTO MS','precinct'] = np.nan\ndf.loc[df.precinct=='YAZOO MS','precinct'] = np.nan\ndf.loc[df.precinct=='HOLMES MS','precinct'] = np.nan\n\ndf = df.loc[df.precinct!='Total']\ndf.dropna(subset=['precinct'],inplace=True)\n\ndf.loc[(df.county=='Alcorn')&(df.precinct=='College Hill')&(df.candidate=='Phil Bryant'),'votes'] = 303\ndf.loc[(df.county=='Alcorn')&(df.precinct=='Wenasoga')&(df.candidate=='Phil Bryant'),'votes'] = 466\n\ndf.loc[(df.county=='Grenada')&(df.precinct=='Futheyville 1st Pentecost')&(df.candidate=='Robert Gray'),'votes'] = 83\ndf.loc[(df.county=='Grenada')&(df.precinct=='Geeslin')&(df.candidate=='Robert Gray'),'votes'] = 64\ndf.loc[(df.county=='Grenada')&(df.precinct=='Gore Springs Comm Center')&(df.candidate=='Robert Gray'),'votes'] = 49\ndf.loc[(df.county=='Grenada')&(df.precinct=='Holcomb CC')&(df.candidate=='Robert Gray'),'votes'] = 110\ndf.loc[(df.county=='Grenada')&(df.precinct=='Pleasant Grove Commun Cen')&(df.candidate=='Robert Gray'),'votes'] = 168\ndf.loc[(df.county=='Grenada')&(df.precinct=='Sweethome Hol #2 Fire Stat')&(df.candidate=='Robert Gray'),'votes'] = 53\n\ndf.loc[(df.county=='Grenada')&(df.precinct=='Futheyville 1st Pentecost')&(df.candidate=='Phil Bryant'),'votes'] = 396\ndf.loc[(df.county=='Grenada')&(df.precinct=='Geeslin')&(df.candidate=='Phil Bryant'),'votes'] = 407\ndf.loc[(df.county=='Grenada')&(df.precinct=='Gore Springs Comm Center')&(df.candidate=='Phil Bryant'),'votes'] = 276\ndf.loc[(df.county=='Grenada')&(df.precinct=='Holcomb CC')&(df.candidate=='Phil Bryant'),'votes'] = 397\ndf.loc[(df.county=='Grenada')&(df.precinct=='Pleasant Grove Commun Cen')&(df.candidate=='Phil Bryant'),'votes'] = 145\ndf.loc[(df.county=='Grenada')&(df.precinct=='Sweethome Hol #2 Fire Stat')&(df.candidate=='Phil Bryant'),'votes'] = 162\n\ndf.loc[(df.county=='Harrison')&(df.precinct=='Long Beach #1')&(df.candidate=='Phil Bryant'),'votes'] = 239\n#conflicting vote for below\ndf.loc[(df.county=='Harrison')&(df.precinct=='Long Beach #1')&(df.candidate=='Robert Gray'),'votes'] = 78\n\ndf.loc[(df.county=='Jones')&(df.precinct=='Sand Hill')&(df.candidate=='Phil Bryant'),'votes'] = 428\n\ndf.loc[(df.county=='Leflore')&(df.precinct=='Rising Sun')&(df.candidate=='Robert Gray'),'votes'] = 228\ndf.loc[(df.county=='Leflore')&(df.precinct=='Schlater')&(df.candidate=='Robert Gray'),'votes'] = 51\ndf.loc[(df.county=='Leflore')&(df.precinct=='South Gwd')&(df.candidate=='Robert Gray'),'votes'] = 169\ndf.loc[(df.county=='Leflore')&(df.precinct=='South Itta Bena')&(df.candidate=='Robert Gray'),'votes'] = 154\ndf.loc[(df.county=='Leflore')&(df.precinct=='Southeast Gwd')&(df.candidate=='Robert Gray'),'votes'] = 552\ndf.loc[(df.county=='Leflore')&(df.precinct=='Southwest Gwd')&(df.candidate=='Robert Gray'),'votes'] = 169\ndf.loc[(df.county=='Leflore')&(df.precinct=='Swiftown')&(df.candidate=='Robert Gray'),'votes'] = 13\ndf.loc[(df.county=='Leflore')&(df.precinct=='West Gwd')&(df.candidate=='Robert Gray'),'votes'] = 462\n\ndf.loc[(df.county=='Leflore')&(df.precinct=='Rising Sun')&(df.candidate=='Phil Bryant'),'votes'] = 58\ndf.loc[(df.county=='Leflore')&(df.precinct=='Schlater')&(df.candidate=='Phil Bryant'),'votes'] = 89\ndf.loc[(df.county=='Leflore')&(df.precinct=='South Gwd')&(df.candidate=='Phil Bryant'),'votes'] = 30\ndf.loc[(df.county=='Leflore')&(df.precinct=='South Itta Bena')&(df.candidate=='Phil Bryant'),'votes'] = 73\ndf.loc[(df.county=='Leflore')&(df.precinct=='Southeast Gwd')&(df.candidate=='Phil Bryant'),'votes'] = 236\ndf.loc[(df.county=='Leflore')&(df.precinct=='Southwest Gwd')&(df.candidate=='Phil Bryant'),'votes'] = 41\ndf.loc[(df.county=='Leflore')&(df.precinct=='Swiftown')&(df.candidate=='Phil Bryant'),'votes'] = 24\ndf.loc[(df.county=='Leflore')&(df.precinct=='West Gwd')&(df.candidate=='Phil Bryant'),'votes'] = 153\n\ndf.loc[(df.county=='Lincoln')&(df.precinct=='Little Bahala')&(df.candidate=='Phil Bryant'),'votes'] = 101\n\ndf.loc[(df.county=='Marion')&(df.precinct=='Morgantown')&(df.candidate=='Phil Bryant'),'votes'] = 257\n\ndf.loc[(df.county=='Monroe')&(df.precinct=='3 Lackey')&(df.candidate=='Phil Bryant'),'votes'] = 406\ndf.loc[(df.county=='Monroe')&(df.precinct=='4 South Aberdeen')&(df.candidate=='Phil Bryant'),'votes'] = 190\n\ndf.loc[(df.county=='Oktibbeha')&(df.precinct=='North Starkville District 3')&(df.candidate=='Phil Bryant'),'votes'] = 529\n\ndf = df.append({'county':'Panola','precinct':'Pleasant Mount','office':'Governor','district':'0','candidate':'Phil Bryant','party':'Republican','votes':145},ignore_index=True)\ndf = df.append({'county':'Panola','precinct':'Pleasant Mount','office':'Governor','district':'0','candidate':'Robert Gray','party':'Democrat','votes':127},ignore_index=True)\ndf = df.append({'county':'Panola','precinct':'Pleasant Mount','office':'Governor','district':'0','candidate':\"Shawn O'Hara\",'party':'Reform','votes':4},ignore_index=True)\n\ndf.loc[(df.county=='Pearl River')&(df.precinct=='Savannah Beat 3')&(df.candidate=='Phil Bryant'),'votes'] = 202\ndf.loc[(df.county=='Pearl River')&(df.precinct=='Ozona Beat 3')&(df.candidate=='Robert Gray'),'votes'] = 16\n\ndf.loc[(df.county=='Stone')&(df.precinct=='Perkinston')&(df.candidate=='Phil Bryant'),'votes'] = 203\n\ndf.loc[(df.county=='Tate')&(df.precinct=='Tyro')&(df.candidate=='Phil Bryant'),'votes'] = 69\ndf.loc[(df.county=='Tate')&(df.precinct=='Senatobia 1')&(df.candidate=='Phil Bryant'),'votes'] = 796\ndf.loc[(df.county=='Tate')&(df.precinct=='Senatobia 1')&(df.candidate=='Robert Gray'),'votes'] = 187\n\ndf.loc[(df.county=='Walthall')&(df.precinct=='Dexter')&(df.candidate=='Robert Gray'),'votes'] = 62\ndf.loc[(df.county=='Walthall')&(df.precinct=='West Tylertown')&(df.candidate=='Phil Bryant'),'votes'] = 169\n\ndf.loc[(df.county=='Washington')&(df.precinct=='Washington County Convention Center')&(df.candidate=='Phil Bryant'),'votes'] = 186\n\n#Jackson County irregularity addressed below\ndf.party = df.party.str.replace('Democratic','Democrat',regex=False)\n\n#Rankin County irregularities addressed below\ndf.party = df.party.str.replace('DEM','Democrat',regex=False)\ndf.party = df.party.str.replace('REP','Republican',regex=False)\ndf.loc[(df.candidate==\"Shawn O'Hara\"),'party'] = 'Reform'\ndf = df.append({'county':'Rankin','precinct':'Highlands','office':'Governor','district':'0','candidate':'Phil Bryant','party':'Republican','votes':464},ignore_index=True)\ndf = df.append({'county':'Rankin','precinct':'Highlands','office':'Governor','district':'0','candidate':'Robert Gray','party':'Democrat','votes':182},ignore_index=True)\ndf = df.append({'county':'Rankin','precinct':'Highlands','office':'Governor','district':'0','candidate':\"Shawn O'Hara\",'party':'Reform','votes':12},ignore_index=True)\n\ndf = df.append({'county':'Rankin','precinct':'Oakdale','office':'Governor','district':'0','candidate':'Phil Bryant','party':'Republican','votes':993},ignore_index=True)\ndf = df.append({'county':'Rankin','precinct':'Oakdale','office':'Governor','district':'0','candidate':'Robert Gray','party':'Democrat','votes':226},ignore_index=True)\ndf = df.append({'county':'Rankin','precinct':'Oakdale','office':'Governor','district':'0','candidate':\"Shawn O'Hara\",'party':'Reform','votes':16},ignore_index=True)\n\n#These counties flipped Bryants and Grays votes\nfor county in ['Clay','Covington','Lafayette']:\n\tdf.loc[(df.county==county)&(df.candidate=='Phil Bryant'),'party'] = 'Democrat'\n\tdf.loc[(df.county==county)&(df.candidate=='Robert Gray'),'party'] = 'Republican'\n\tdf.loc[(df.county==county)&(df.candidate=='Phil Bryant')&(df.party=='Democrat'),'candidate'] = 'Robert Gray'\n\tdf.loc[(df.county==county)&(df.candidate=='Robert Gray')&(df.party=='Republican'),'candidate'] = 'Phil Bryant'\n\n#Simpson County irregularities addressed below\ndf.candidate = df.candidate.str.replace('Time Johnson','Tim Johnson',regex=False)\ndf.candidate = df.candidate.str.replace('Rober Gray','Robert Gray',regex=False)\ndf.candidate = df.candidate.str.replace('Phill Bryant','Phil Bryant',regex=False)\ndf.loc[(df.candidate=='Tate Reeves'),'office'] = 'Lieutenant Governor'\ndf.loc[(df.candidate=='Tim Johnson'),'office'] = 'Lieutenant Governor'\n\ndf.district = df.district.replace(r'0',np.nan)\n\ndf = df.sort_values(by=['county','office','candidate','district'])\ndf = df.set_index('county')\n\ndf.to_csv('/Users/sammahle/Desktop/election_projects/openelections-data-ms/2015/20151103__ms__general__precinct.csv')\n\n\n","repo_name":"openelections/openelections-data-ms","sub_path":"2015_governor_data_cleaner.py","file_name":"2015_governor_data_cleaner.py","file_ext":"py","file_size_in_byte":9149,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"77"}
+{"seq_id":"69955050490","text":"# От конзолата се четат 4 реда:\n# ⦁\tДължина в см – цяло число\nlenght = float(input())\n# ⦁\tШирочина в см – цяло число\nwidth = float(input())\n# ⦁\tВисочина в см – цяло число\nhight = float(input())\n# ⦁\tПроцент зает обем – реално число\nsome_text = float(input())\n\n\naquarium_capacity = lenght * width * hight\nsome_percent = some_text * 0.01\n\nneeded_litres = aquarium_capacity * (1 - some_percent)\nneeded_litres = needed_litres * 0.001\n\nprint(needed_litres)","repo_name":"xMrShadyx/SoftUni","sub_path":"Programming Basic/First_steps_in_coding_excercise/08_Fish_Tank.py","file_name":"08_Fish_Tank.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"bg","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"5333551118","text":"from Node import *\nfrom dijkstra import *\nimport math\nimport cv2\nimport numpy as np\nimage_URL = \"C:\\\\Users\\\\ktjos\\\\Desktop\\\\plane2.jpg\"\n\nsink_vert = []\nsource_vert = []\n\n\ndef run_image_segmentation(image):\n # source_vert = [(7, 19)]\n # sink_vert = [(24, 55), (35, 82), (73, 55)]\n # source_vert = [(7, 18)]\n # sink_vert = [(42, 25), (47, 46), (52, 53), (68, 29), (80, 41), (73, 44)]\n # source_vert = [(5, 4)]\n # sink_vert =[(32, 11), (21, 37), (16, 59), (5, 64), (8, 73), (25, 93), (62, 92), (82, 86), (87, 60), (92, 37), (79, 39),\n # (67, 26), (54, 17)]\n # for plane 2\n # source_vert = [(50, 21)]\n # sink_vert = [(19, 48), (25, 47), (21, 44)]\n graph = create_graph(image, edge_wt_function1)\n d, source_nodes, sink_nodes = graph.get_dual(source_vert, sink_vert)\n print(graph.vert_list[0])\n\n print(\"::Running Dijkstra\")\n idx = len(sink_nodes)//2\n start_node_id = sink_nodes[0]\n dist, parent = run_dijkstra(d, start_node_id)\n\n print(\"Dijkstra Complete\")\n\n edge_set = set()\n prev = \"\"\n\n for sink_vertex in sink_nodes:\n current_vertex = sink_vertex\n prev = \"\"\n # print(current_vertex, \" \", start_node_id)\n # print(current_vertex==start_node_id)\n while current_vertex!=start_node_id and current_vertex!=None:\n prev = parent[current_vertex]\n edge_set.add((prev, current_vertex))\n current_vertex = prev\n\n start_node_id = sink_nodes[idx]\n dist, parent = run_dijkstra(d, start_node_id)\n for sink_vertex in sink_nodes:\n current_vertex = sink_vertex\n prev = \"\"\n while current_vertex != start_node_id:\n prev = parent[current_vertex]\n edge_set.add((prev, current_vertex))\n current_vertex = prev\n # for vertice in dist.keys():\n # print(vertice, \" \", dist[vertice], \" \", parent[vertice])\n #\n # print(edge_set)\n\n d.contract_edges(edge_set)\n d.convert_to_list()\n # print(\"***************************************************************\")\n # for nodes in d.vert_list:\n # print(\"-----------------------------------------------------------\")\n # print(d.vert_list[nodes])\n # print(\"***************************************************************\")\n sink = d.get_simple_node('XNode')\n # print(sink)\n # print(\"-------------------------------------------------------\")\n # print(d.get_simple_node(frozenset({728, 729, 828, 829})))\n # print(\"-------------------------------------------------------\")\n #\n # print(d.get_simple_node(frozenset({729, 730, 829, 830})))\n # print(\"-------------------------------------------------------\")\n\n source = d.get_simple_node(source_nodes[0])\n print(\"Source_v:\",source)\n print(\"Sink_V:\", sink)\n # min_cut_edges, source_set_edges = d.min_cut(source, sink)\n for nodes in source.adj_list.keys():\n a = source.adj_list[nodes]\n b =[]\n for it in a:\n b.append(it*1)\n source.adj_list[nodes] = b\n print(\"Source_v:\", source)\n min_cut_edges, source_set_edges = d.min_cut(source, sink)\n print(\"Source_v:\", source)\n\n print(\"number of mincut edges\", len(min_cut_edges))\n # print(min_cut_edges)\n # for nodes in min_cut_edges:\n # print('==========================')\n # print(nodes[0].get_id(), \"edges:\", nodes[0])\n # print(nodes[1].get_id(), \"edges:\", nodes[1])\n # print('==========================')\n #\n # for nodes in source_set_edges:\n # print('------------------------------')\n # print(nodes.get_id(), \"edges:\", nodes)\n img = cv2.imread(image_URL)\n\n\n green = [0,255,0]\n for edges in min_cut_edges:\n try:\n print(edges[0].get_id(),\" \", edges[1].get_id())\n intersection = edges[0].get_id() & edges[1].get_id()\n except:\n continue\n cord = []\n for nodes in intersection:\n x,y = graph.get_coordinates(nodes)\n cord.append((x,y))\n img[x,y] = green\n\n cv2.namedWindow('Source', cv2.WINDOW_NORMAL)\n cv2.imshow('Source', img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n cv2.imwrite('C:\\\\Users\\\\ktjos\\\\Desktop\\\\snap_segmentation.jpg', img)\n # for nodes in min_cut_edges:\n\n\n\n\ndef create_graph(image, edge_wt_function):\n graph = Graph(len(image), len(image[0]))\n\n for i in range(len(image)):\n for j in range(len(image[0])):\n graph.add_node((i, j))\n\n for i in range(len(image)):\n for j in range(len(image[0])):\n # try for all four neighbors in order: right, bottom, left, top\n if j + 1 < len(image[0]):\n graph.add_edge((i, j), (i, j + 1), edge_wt_function(image[i][j], image[i][j + 1]))\n if i + 1 < len(image):\n graph.add_edge((i, j), (i + 1, j), edge_wt_function(image[i][j], image[i + 1][j]))\n if j - 1 >= 0:\n graph.add_edge((i, j), (i, j - 1), edge_wt_function(image[i][j], image[i][j - 1]))\n if i - 1 >= 0:\n graph.add_edge((i, j), (i - 1, j), edge_wt_function(image[i][j], image[i - 1][j]))\n\n\n return graph\n\ndef pre_process_image():\n \"\"\"\n Later might want to add some preprocessing which will involve smoothening of the image\n :return:\n \"\"\"\n img = get_image(image_URL)\n sink_vert = [(7, 19)]\n source_vert = [(24, 55), (35, 82), (73, 55)]\n # convert to gray\n img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n img = cv2.blur(img, (5, 5))\n img_gray = [[0 for i in range(len(img[0]))] for i in range(len(img))]\n for i in range(len(img)):\n for j in range(len(img[0])):\n luminence = (0.0722 * int(img[i][j][0])) + (0.7152 * int(img[i][j][1])) + (0.2125 * int(img[i][j][2]))\n img_gray[i][j] = luminence\n run_image_segmentation(img_gray)\n\ndef get_clicked_points(event, x, y, flags, param):\n if event == cv2.EVENT_LBUTTONUP:\n if param == 'source':\n source_vert.append((y,x))\n else:\n sink_vert.append((y,x))\n\ndef get_image(image_URL):\n img = cv2.imread(image_URL)\n height_img = img.shape[0]\n width_img = img.shape[1]\n\n cv2.namedWindow('Source',cv2.WINDOW_NORMAL)\n cv2.resizeWindow('Source', width_img, height_img)\n cv2.setMouseCallback('Source', get_clicked_points, param='source')\n\n cv2.imshow('Source', img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n cv2.namedWindow('Sink', cv2.WINDOW_NORMAL)\n cv2.resizeWindow('Sink', width_img, height_img)\n cv2.setMouseCallback('Sink', get_clicked_points, param='sink')\n\n cv2.imshow('Sink', img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n print(source_vert)\n print(sink_vert)\n\n return img\n\ndef edge_wt_function1(luminance1, luminance2):\n diff = (abs(int(luminance1) - int(luminance2)))\n wt = 1 / math.pow((diff+1), 2)\n return wt\n\ndef edge_wt_function2(luminance1, luminance2):\n diff = abs(int(luminance1) - int(luminance2))\n wt = math.pow((255 - diff), 2)\n return wt\n\ndef edge_wt_function3(luminance1, luminance2):\n diff = abs(int(luminance1) - int(luminance2))\n wt = 1000/math.pow(math.e,diff)\n return wt\n\n\nif __name__ == '__main__':\n # run_image_segmentation()\n # get_image()\n pre_process_image()","repo_name":"ktjosh/Capstone","sub_path":"Image_segmentation.py","file_name":"Image_segmentation.py","file_ext":"py","file_size_in_byte":7261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"34985757367","text":"from typing import Dict\nimport argparse\nimport time\nimport os\nimport pathlib\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport librosa\nimport soundfile\n\nfrom bytesep.models.lightning_modules import get_model_class\nfrom bytesep.utils import read_yaml\nfrom bytesep.inference import Separator\n\n\ndef inference(args):\n\n # Need to use torch.distributed if models contain inplace_abn.abn.InPlaceABNSync.\n import torch.distributed as dist\n dist.init_process_group('gloo', init_method='file:///tmp/somefile', rank=0, world_size=1)\n\n # Arguments & parameters\n config_yaml = args.config_yaml\n checkpoint_path = args.checkpoint_path\n audios_dir = args.audios_dir\n output_dir = args.output_dir\n\n configs = read_yaml(config_yaml)\n sample_rate = configs['train']['sample_rate']\n input_channels = configs['train']['channels']\n target_source_types = configs['train']['target_source_types']\n target_sources_num = len(target_source_types)\n model_type = configs['train']['model_type']\n mono = input_channels == 1\n\n segment_samples = int(30 * sample_rate)\n batch_size = 1\n device = \"cuda\"\n\n # paths\n os.makedirs(output_dir, exist_ok=True)\n\n # Get model class.\n Model = get_model_class(model_type)\n \n # Create model.\n model = Model(input_channels=input_channels, target_sources_num=target_sources_num)\n\n # Load checkpoint.\n checkpoint = torch.load(checkpoint_path, map_location='cpu')\n model.load_state_dict(checkpoint[\"model\"])\n\n # Move model to device.\n model.to(device)\n\n # Create separator.\n separator = Separator(model=model, segment_samples=segment_samples, batch_size=batch_size, device=device)\n\n audio_names = sorted(os.listdir(audios_dir))\n\n for audio_name in audio_names:\n audio_path = os.path.join(audios_dir, audio_name)\n\n # Load audio.\n audio, _ = librosa.load(audio_path, sr=sample_rate, mono=mono)\n\n if audio.ndim == 1:\n audio = audio[None, :]\n\n input_dict = {'waveform': audio}\n\n # Separate\n separate_time = time.time()\n\n sep_wav = separator.separate(input_dict)\n # (channels_num, audio_samples)\n\n print('Separate time: {:.3f} s'.format(time.time() - separate_time))\n\n # Write out separated audio.\n soundfile.write(file='_zz.wav', data=sep_wav.T, samplerate=sample_rate)\n\n output_path = os.path.join(output_dir, '{}.mp3'.format(pathlib.Path(audio_name).stem))\n os.system('ffmpeg -y -loglevel panic -i _zz.wav \"{}\"'.format(output_path))\n print('Write out to {}'.format(output_path))\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(description=\"\")\n parser.add_argument(\"--config_yaml\", type=str, required=True)\n parser.add_argument(\"--checkpoint_path\", type=str, required=True)\n parser.add_argument(\"--audios_dir\", type=str, required=True)\n parser.add_argument(\"--output_dir\", type=str, required=True)\n\n args = parser.parse_args()\n inference(args)\n","repo_name":"chenchy/music_source_separation","sub_path":"bytesep/inference_many.py","file_name":"inference_many.py","file_ext":"py","file_size_in_byte":3007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"77"}
+{"seq_id":"18544929333","text":"import os\nimport json\n\nfrom pathlib import Path\n\nfrom ..dictionary import Dictionary\n\nFOLDERPATH = os.path.dirname(os.path.abspath(__file__))\n\nclass CMUDict(Dictionary):\n def _compute(self):\n \"\"\"Loads the CMUDict dataset and transforms it from ARPAbet to IPA\n\n To do: Just write the transformed version to a file so you're not\n doing it every time, Bobby, that's just inefficient.\n \"\"\"\n self.phonetics = list()\n self.words = list()\n arpa_to_ipa = load_ARPA_to_IPA_table()\n with open(os.path.join(FOLDERPATH, \"./CMUDict-0.7b/cmudict-0.7b\"), 'r') as fp:\n for line in fp.readlines():\n if line.startswith(';;;'): continue # Skip comment lines\n token, arpa = line.strip().split(' ')\n arpa = arpa.split(' ')\n for i,symbol in enumerate(arpa):\n if symbol not in arpa_to_ipa:\n print(f\"ARPAbet symbol {symbol} not found in IPA translation table! (word: {token})\")\n continue\n arpa[i] = arpa_to_ipa[symbol]\n self.words.append(token)\n self.phonetics.append(\" \".join(arpa))\n\ndef load_ARPA_to_IPA_table():\n \"\"\"Reads `cmudict_ARPAbet_to_IPA.csv` to create a mapping\n of ARPAbet symbols to their corresponding IPA notation\n \"\"\"\n ret = dict()\n with open(os.path.join(FOLDERPATH, \"./cmudict_ARPAbet_to_IPA.csv\"), 'r', encoding='UTF-8') as fp:\n fp.readline() # Skip header line\n for line in fp.readlines():\n line = line.strip().split(',')\n ret[line[0]] = line[1]\n return ret\n","repo_name":"r-best/NewWordGenerator","sub_path":"dictionaries/CMUDict/CMUDict.py","file_name":"CMUDict.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"74620181047","text":"def read_data_sets_and_append(data_sets, i):\n with open(\"featuresASR_combined\" + i, 'w') as combined:\n for data_set in data_sets:\n f = open(data_set)\n for line in f:\n features = line.split(\" # \")[0]\n name = line.split(\" # \")[1]\n splited_name = name.split(\"-\")\n new_name = splited_name[0] + \"-\" + splited_name[1] + \"-\" + splited_name[2].split(\"_\")[0] + \"-\" + \\\n splited_name[3]\n new_line = features + \" # \" + new_name\n combined.write(new_line)\n f.close()\n\n\ndata_sets1 = [\"../featuresASR_round1_SVM\", \"../featuresASR_round1_LambdaMART\"]\ndata_sets2 = [\"../featuresASR_round2_SVM\",\n \"../featuresASR_round2_LambdaMART\"]\nread_data_sets_and_append(data_sets1, \"1\")\nread_data_sets_and_append(data_sets2, \"2\")\n","repo_name":"greggoren/robustness","sub_path":"bias_variance_tradeoff_svm/combine_data_set.py","file_name":"combine_data_set.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"21444160113","text":"#이분탐색\n#자료는 정렬이 ���어 있어야 한다.\n\ndef binary_search(target, data):\n data.sort()\n start=0\n end=len(data)-1\n while(start<=end):\n mid=(start+end)//2\n if data[mid]==target:\n return mid\n elif data[mid]>target:\n end=mid-1\n else:\n start=mid+1\n return None\n\nif __name__==\"__main__\":\n li=[i**2 for i in range(11)]\n target=9\n idx=binary_search(target,li)\n if idx:\n print('index=',idx,',value=',li[idx])\n else:\n print(\"No target\")\n","repo_name":"nabilera1/codingTestPython","sub_path":"코딩테스트학습/탐색 이분탐색.py","file_name":"탐색 이분탐색.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"14693650958","text":"import os\nfrom collections import namedtuple\nfrom jinja2 import Template\n\n\ndef next_line(raw_dir):\n def inner(file, current_dir=''):\n path = os.path.join(raw_dir, current_dir, file+'.md')\n with open(path, \"r\", encoding='utf-8') as inp_file:\n inp_file.readline()\n for line in inp_file:\n if line not in ['', '\\n']:\n yield line.strip()\n\n return inner\n\n\ndef get_writing_titles(dir):\n FoldersNFiles = namedtuple('FoldersNFiles', ['folders', 'files'])\n content = FoldersNFiles(folders={}, files=[])\n\n for current_dir, folders, files in os.walk(dir):\n titles = []\n prev_dir, folder = os.path.split(current_dir)\n for file in files:\n file_name, extension = os.path.splitext(file)\n if extension == '.md':\n path = os.path.join(current_dir, file)\n with open(path, 'r', encoding='utf-8') as inp_file:\n titles.append((file_name, inp_file.readline().strip()))\n \n if not prev_dir:\n content.files.extend(titles)\n else:\n content.folders[folder] = titles\n return content\n \n\n\ndef render_template(template_path, outp, params):\n with open(template_path, 'r', encoding='utf-8') as tmp_file:\n template = Template(tmp_file.read())\n\n with open(outp, 'w', encoding='utf-8') as outp_file:\n outp_file.write(template.render(params))\n\n\nif __name__ == '__main__':\n content = get_writing_titles('raw')\n render_template('templates/writing.html', 'writing.html',\n {'content': content, 'next_line': next_line('raw')})","repo_name":"GalWat/galwat.github.io","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"9937644763","text":"\"\"\"Модуль содержит функцию и фикстуру для тестирования ответа страницы\"\"\"\n\nimport pytest\nimport requests\n\n\ndef pytest_addoption(parser):\n \"\"\"Функция принимает параметр строки --url или использует значение https://ya.ru по умолчанию\"\"\"\n parser.addoption(\n \"--url\",\n action=\"store\",\n default=\"https://ya.ru\",\n help=\"This is request url\"\n )\n\n\n@pytest.fixture\ndef url_param(request):\n \"\"\"Функция осуществляет запрос по заданному адресу\"\"\"\n res = requests.get(request.config.getoption(\"--url\"))\n return res\n","repo_name":"realdeal87/Python-QA-Engineer","sub_path":"lesson_3_exercise_api/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"72716345848","text":"import logging\n\nlogging.basicConfig(level=\"DEBUG\")\n\nlogger = logging.getLogger(__name__) # name of this module could me __main__ or log\n# basically you could do logging.getLogger('any_name')\n#think of a logger as a name bucket or dump where certain logs are directed to\n\nlogger.debug(\"script is running\") #prints level:name of logger: message\nlogger.info(\"wow this would be fun\")\nlogger.warning(\"this is a warning you are running script\")\n\ntry:\n x = 1/0\nexcept ZeroDivisionError as e:\n # you can get the traceback of an exception easily with the below\n logger.exception(f\"zero division error here: {e}\") # this is same as logger.error(\"message\",exc_info=True)\n\n# RESULT:\n# >>>python log.py \n# DEBUG:__main__:script is running\n# INFO:__main__:wow this would be fun\n# WARNING:__main__:this is a warning you are running script\n# ERROR:__main__:zero division error here: division by zero\n# Traceback (most recent call last):\n# File \"/home/goodnews/Documents/twitter_posts/learn_and_tweet/log.py\", line 13, in \n# x = 1/0\n# ZeroDivisionError: division by zero","repo_name":"goodnewsj62/learn_and_tweet","sub_path":"log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"70100957688","text":"# Import arcpy module\r\nimport arcpy\r\nimport csv\r\nfrom numpy import array, isnan\r\nimport os\r\n\r\n\r\nclass ConvertFlowlinesToCSVForCF(object):\r\n def __init__(self):\r\n \"\"\"Define the tool (tool name is the name of the class).\"\"\"\r\n self.label = \"Convert Flowlines to CSV for CF\"\r\n self.description = (\"Convert flowlines to csv valid for RAPID CF script\")\r\n self.canRunInBackground = False\r\n\r\n def getParameterInfo(self):\r\n \"\"\"Define parameter definitions\"\"\"\r\n in_drainage_line = arcpy.Parameter(\r\n displayName='Input Drainage Line Features',\r\n name='in_drainage_line_features',\r\n datatype='GPFeatureLayer',\r\n parameterType='Required',\r\n direction='Input')\r\n in_drainage_line.filter.list = ['Polyline']\r\n\r\n param1 = arcpy.Parameter(name=\"stream_ID\",\r\n displayName=\"Stream ID\",\r\n direction=\"Input\",\r\n parameterType=\"Required\",\r\n datatype=\"Field\"\r\n )\r\n param1.parameterDependencies = [\"in_drainage_line_features\"]\r\n param1.filter.list = ['Short', 'Long']\r\n\r\n param2 = arcpy.Parameter(name='out_comid_lat_lon_z',\r\n displayName='Output comid_lat_lon_z file',\r\n direction='Output',\r\n parameterType='Required',\r\n datatype='DEFile')\r\n\r\n params = [in_drainage_line, param1, param2]\r\n\r\n return params\r\n\r\n def isLicensed(self):\r\n \"\"\"Set whether tool is licensed to execute.\"\"\"\r\n return True\r\n\r\n def updateParameters(self, parameters):\r\n \"\"\"Modify the values and properties of parameters before internal\r\n validation is performed. This method is called whenever a parameter\r\n has been changed.\"\"\"\r\n if parameters[2].altered:\r\n (dirnm, basenm) = os.path.split(parameters[2].valueAsText)\r\n if not basenm.endswith(\".csv\"):\r\n parameters[2].value = os.path.join(dirnm, \"{}.csv\".format(basenm))\r\n\r\n return\r\n\r\n def updateMessages(self, parameters):\r\n \"\"\"Modify the messages created by internal validation for each tool\r\n parameter. This method is called after internal validation.\"\"\"\r\n return\r\n\r\n def execute(self, parameters, messages):\r\n \"\"\"The source code of the tool.\"\"\"\r\n arcpy.env.overwriteOutput = True\r\n\r\n # Script arguments\r\n Input_Features = parameters[0].valueAsText\r\n streamID = parameters[1].valueAsText\r\n Output_Table = parameters[2].valueAsText\r\n Intermediate_Feature_Points = os.path.join(\"in_memory\", \"flowline_centroid_points\")\r\n Intermediate_Feature_Points_Projected = os.path.join(arcpy.env.scratchGDB, \"flowline_centroid_points_project\")\r\n\r\n # Process: Feature To Point\r\n arcpy.AddMessage(\"Converting flowlines to points ...\")\r\n arcpy.FeatureToPoint_management(Input_Features, Intermediate_Feature_Points, \"CENTROID\")\r\n\r\n # Process: Make sure projection is GCS_WGS_1984\r\n dsc = arcpy.Describe(Intermediate_Feature_Points)\r\n if dsc.spatialReference.Name == \"Unknown\":\r\n messages.addErrorMessage(\"Unknown Spatial Reference. Please fix to continue.\")\r\n elif dsc.spatialReference.Name != \"GCS_WGS_1984\":\r\n arcpy.AddMessage(\"Projecting to GCS_WGS_1984 from %s ...\" % dsc.spatialReference.Name)\r\n arcpy.Project_management(in_dataset=Intermediate_Feature_Points,\r\n out_dataset=Intermediate_Feature_Points_Projected,\r\n out_coor_system=\"GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]\",\r\n )\r\n arcpy.Delete_management(Intermediate_Feature_Points)\r\n else:\r\n Intermediate_Feature_Points_Projected = Intermediate_Feature_Points\r\n\r\n # Process: Add XY Coordinates\r\n arcpy.AddMessage(\"Adding XY coordinates to points ...\")\r\n arcpy.AddXY_management(Intermediate_Feature_Points_Projected)\r\n\r\n # write only desired fields to csv\r\n arcpy.AddMessage(\"Writing output to csv ...\")\r\n original_field_names = [f.name for f in arcpy.ListFields(Intermediate_Feature_Points_Projected)]\r\n # arcpy.AddMessage(\"Field names: %s\" % original_field_names)\r\n # COMID,Lat,Lon,Elev_m\r\n actual_field_names = [streamID, \"\", \"\"]\r\n needed_field_names = ['point_y', 'point_x', 'point_z']\r\n elevation_exists = False\r\n for original_field_name in original_field_names:\r\n original_field_name_lower = original_field_name.lower()\r\n if original_field_name_lower == needed_field_names[0]:\r\n actual_field_names[1] = original_field_name\r\n elif original_field_name_lower == needed_field_names[1]:\r\n actual_field_names[2] = original_field_name\r\n elif original_field_name_lower == needed_field_names[2]:\r\n actual_field_names.append(original_field_name)\r\n elevation_exists = True\r\n\r\n # check to make sure all fields exist\r\n for index, field_name in enumerate(actual_field_names):\r\n if field_name == \"\":\r\n messages.addErrorMessage(\"Field name %s not found.\" % needed_field_names[index - 1])\r\n raise arcpy.ExecuteError\r\n\r\n # print valid field names to table\r\n with open(Output_Table, 'w') as outfile:\r\n writer = csv.writer(outfile)\r\n writer.writerow(['COMID', 'Lat', 'Lon', 'Elev_m'])\r\n with arcpy.da.SearchCursor(Intermediate_Feature_Points_Projected, actual_field_names) as cursor:\r\n for row in cursor:\r\n # if no elevation found, append zero\r\n if not elevation_exists:\r\n row += (0,)\r\n # make sure all values are valid\r\n np_row = array(row)\r\n np_row[isnan(np_row)] = 0\r\n writer.writerow([int(np_row[0])] + np_row[1:].tolist())\r\n\r\n # delete intermediate layer\r\n arcpy.Delete_management(Intermediate_Feature_Points_Projected)\r\n # add warning messages\r\n if not elevation_exists:\r\n arcpy.AddMessage(\"WARNING: Elevation not found. Zero elevations added.\")\r\n arcpy.AddMessage(\"WARNING: NaN value(s) replaced with zero. Please check output for accuracy.\")\r\n\r\n return\r\n","repo_name":"rileyhales/rapidarcpro","sub_path":"Scripts/ConvertFlowlinesToCSVForCF.py","file_name":"ConvertFlowlinesToCSVForCF.py","file_ext":"py","file_size_in_byte":6725,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"43895145015","text":"from PIL import Image\nimport cv2\nfrom PIL import Image\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import ndimage, misc\nimport cv2\n\nimport glob\ndef calculate_gaussian_pyramids(img, num_levels):\n lower = img.copy()\n gaussian_pyr = [lower]\n for i in range(num_levels):\n lower = cv2.pyrDown(lower)\n gaussian_pyr.append(np.float32(lower))\n return gaussian_pyr\n\n#Laura\n\nif __name__ == '__main__':\n path = \"/home/laurawenderoth/Documents/kidney_microscopy/data/PAS/CKD154-003-PAS-fully-aligned.png\"\n img = Image.open(path)\n img = np.array(img)\n width,heigth = img.shape[:2]\n\n #new image\n path = \"/home/laurawenderoth/Documents/kidney_microscopy/data/IF/CKD154-003-IF-fully-aligned.png\"\n IF = Image.open(path)\n IF = np.array(IF)\n patches = []\n names = []\n gaussian_pyramids = calculate_gaussian_pyramids(np.array(IF), 3)\n g = gaussian_pyramids[-1]\n g = np.uint8(g)\n patches.append(img)\n names.append(\"normal PAS\")\n patches.append(IF)\n names.append(\"normal IF\")\n patches.append(g)\n names.append(\"down IF\")\n\n up = Image.fromarray(g)\n up = up.resize((heigth,width),resample=Image.BICUBIC)\n up = np.array(up)\n\n patches.append(up)\n names.append(\"up IF\")\n\n\n Differenz = IF-up\n patches.append(Differenz)\n names.append(\"IF-UP\")\n\n\n\n\n #plot\n columns = len(patches)\n rows = 1\n fig = plt.figure(figsize=(columns*3, rows*5))\n for i in range(1, columns * rows + 1):\n img = patches[i-1]\n ax = fig.add_subplot(rows, columns, i)\n ax.set_title(names[i-1])\n plt.imshow(img)\n plt.show()\n\n\n\n\n\n","repo_name":"LauraWenderoth/Bachelorarbeit_Kidney_Stain_Transfer","sub_path":"Interpolation.py","file_name":"Interpolation.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"32866085720","text":"import re\n\nfrom musicut import Chord, Note\n\nfrom .base import ParserMixin\n\n\nclass KeyedParser(ParserMixin):\n \"\"\"\n Handles chord notation that is already in a key (e.g. Csus4, Am7)\n \"\"\"\n REGEX = re.compile(\n r\"(?:(?P[A-G])(?P[b#])?)\"\n r\"(?Pdim|m|min|\\+)?\"\n r\"((?PM|dim|m)?(?P2|5|6|7|9|11))?\"\n r\"(?Psus4?)?\"\n r\"(?:add(?P[246]))?\"\n r\"(?:/(?P[A-G])(?P[b#])?)?$\")\n\n def __init__(self, key):\n self.key = key\n\n def chord_from_notation(self, notation):\n match = self.REGEX.match(notation)\n if match is None:\n raise ValueError(\"Notation was not understood: %s\" % notation)\n\n groups = match.groupdict()\n\n degree, modifier = self.get_degree(groups)\n chord_type = self.get_chord_type(groups)\n sustained = groups['sustained'] is not None\n bass, bass_modifier = self.get_bass(groups)\n addition = self.get_addition(groups)\n extension, extension_type = self.get_extension(groups, chord_type)\n\n return Chord(\n degree=degree,\n modifier=modifier,\n chord_type=chord_type,\n sustained=sustained,\n bass=bass,\n bass_modifier=bass_modifier,\n addition=addition,\n extension=extension,\n extension_type=extension_type)\n\n def get_degree(self, groups):\n if groups['note_modifier'] == 'b':\n modifier = Note.FLAT\n elif groups['note_modifier'] == '#':\n modifier = Note.SHARP\n else:\n modifier = None\n\n note = Note(groups['note'], modifier)\n return self.key.degree_for_note(note)\n\n def get_chord_type(self, groups):\n ct = groups['chord_type']\n if groups['extension'] == '5':\n return Chord.FIVE\n elif ct is None:\n return Chord.MAJOR\n elif ct in ['m', 'min']:\n return Chord.MINOR\n elif ct == 'dim':\n return Chord.DIMINISHED\n elif ct == '+':\n return Chord.AUGMENTED\n\n def get_bass(self, groups):\n if groups['bass'] is None:\n return None, None\n\n mod = None\n if groups['bass_modifier'] == 'b':\n mod = Note.FLAT\n elif groups['bass_modifier'] == '#':\n mod = Note.SHARP\n\n note = Note(groups['bass'], mod)\n return self.key.degree_for_note(note)\n","repo_name":"keitwb/py-musicut","sub_path":"musicut/parsers/keyed.py","file_name":"keyed.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"70491194170","text":"# Space: O(n)\n# Time: O(n)\n\n# BFS approach\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\n\nclass Solution:\n def pathSum(self, root, s):\n if root is None: return []\n res, path = [], []\n\n queue = [[root, path]]\n\n while queue:\n cur_root, cur_path = queue.pop(0)\n if cur_root.left is None and cur_root.right is None and s == sum(cur_path) + cur_root.val:\n res.append(cur_path + [cur_root.val])\n\n if cur_root.left:\n queue.append([cur_root.left, cur_path + [cur_root.val]])\n if cur_root.right:\n queue.append([cur_root.right, cur_path + [cur_root.val]])\n\n return res\n\n\n\n","repo_name":"lht19900714/Leetcode_Solutions","sub_path":"Algorithms/0113_Path_Sum_II/Python/Path_Sum_II_Solution_2.py","file_name":"Path_Sum_II_Solution_2.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"42056656401","text":"from datetime import timedelta\nfrom dateutil import parser\nfrom rates.utils import execute_query\n\nclass PriceQuery:\n DAY_AVERAGE = '''select day, round(avg(price), 2) from price\nwhere day >= '{}' and day <= '{}'\nand origin_id in {} and\ndestination_id in {}\ngroup by day order by day;'''\n\ndef get_day_average(parameters: dict)-> dict:\n query = PriceQuery.DAY_AVERAGE.format(\n parameters.get(\"date_from\"),\n parameters.get(\"date_to\"),\n parameters.get(\"origin\"),\n parameters.get(\"destination\")\n )\n records = execute_query(query)\n return format_response(records=records, parameters=parameters)\n\ndef format_response(records: tuple, parameters: dict):\n day = parser.parse(parameters.get(\"date_from\")).date()\n date_to = parser.parse(parameters.get(\"date_to\")).date()\n idx = 0\n total = len(records)\n data = []\n while day <= date_to:\n average = None\n if idx < total and records[idx][0] == day:\n average = records[idx][1]\n idx += 1\n data.append(\n {'day': day,\n 'average_price': average}\n )\n day = day + timedelta(days=1)\n return data\n","repo_name":"PSvishnu93/xeneta","sub_path":"ocean_freight/rates/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"74410260407","text":"#!/usr/bin/env python3\n\nimport numpy as np\n\ntickets = np.loadtxt('dat/day_5.txt', dtype=str)\n# tickets = ['FBFBBFFRLR']\nseat_ids = []\n\nfor ticket in tickets:\n low_row = 0\n high_row = 127\n low_col = 0\n high_col = 7\n row_range = ticket[0:7]\n col_range = ticket[7:]\n for row_val in row_range:\n rng = high_row - low_row\n if row_val == 'F':\n high_row = low_row + rng // 2\n else:\n low_row = low_row + rng // 2 + 1\n if low_row == high_row:\n row = low_row\n else:\n print(ticket, low_row, high_row)\n row = None\n\n for col_val, in col_range:\n rng = high_col - low_col\n if col_val == 'L':\n high_col = low_col + rng // 2\n else:\n low_col = low_col + rng // 2 + 1\n if low_col == high_col:\n col = low_col\n else:\n print(ticket, low_col, high_col)\n col = np.nan\n\n seat_id = row * 8 + col\n seat_ids.append(seat_id)\n\nseat_ids = np.array(seat_ids)\nprint(f'Part 1: {np.max(seat_ids)}')\n\nall_seats = np.arange(0, 127 * 8 + 7)\nmissing = np.array([seat_id not in seat_ids for seat_id in all_seats])\nmissing_ids = np.where(missing)[0]\nmy_seat = missing_ids[:-1][np.diff(missing_ids) > 1][-1]\n\nprint(f'Part 2: {my_seat}')\n","repo_name":"StarkillerX42/AdventOfCode","sub_path":"python/day_5.py","file_name":"day_5.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"6298416459","text":"# Download the helper library from https://www.twilio.com/docs/python/install\nfrom twilio.rest import Client\n\n\n# Your Account Sid and Auth Token from twilio.com/console\n# DANGER! This is insecure. See http://twil.io/secure\naccount_sid = 'AC331ccd98e15725baae87a2efa3a39ab5'\nauth_token = 'f22a0fc87e8ec3a689e84ffe996ad0a4'\nclient = Client(account_sid, auth_token)\n\nmessage = client.messages \\\n .create(\n body=\"파이썬 개꿀잼?\",\n from_='+12408984967',\n to='+821051310355'\n )\n\nprint(message.sid)","repo_name":"Whamnnn/wonnie-text-send","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"12753375476","text":"# Program permainan angka\n# Buku Siswa IKM Informatika untuk SMA Kelas XI Hal. 42\n# Aktivitas SAP-K11-07-U: Bermain Angka\n# Programmed by : Armansyah, S.Kom, M.Pd\n# Guru Informatika SMAN Sumatera Selatan \n# armansyah@smansumsel.sch.id\n# Alumni CS50 for Teachers Harvard-Indonesia 2022/2023\n# Setiap copy-paste dan pengembangan harus mencantumkan informasi HAKI diatas\n\n\ndef langkah_minimum_ke_satu(n):\n if n == 1:\n return 0\n \n angka = [0] * (n + 1)\n \n for i in range(2, n + 1):\n angka[i] = angka[i - 1] + 1\n \n if i % 2 == 0:\n angka[i] = min(angka[i], angka[i // 2] + 1)\n \n if i % 3 == 0:\n angka[i] = min(angka[i], angka[i // 3] + 1)\n \n return angka[n]\n\n# Input dari pengguna\nn = int(input(\"Masukkan bilangan n: \"))\nlangkah = langkah_minimum_ke_satu(n)\nprint(f\"Jumlah langkah minimum untuk mengubah {n} menjadi 1 adalah: {langkah}\")\n","repo_name":"Armansyahmpd/Python-SMA-Kumer","sub_path":"permainanangka.py","file_name":"permainanangka.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"id","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"24848080797","text":"from typing import List, Dict\nfrom fastapi import APIRouter, Depends, HTTPException, UploadFile\nfrom fastapi.responses import JSONResponse\nfrom sqlalchemy.orm import Session\n\nfrom app.controller import molecule as controller\nfrom app.db.session import get_db\nfrom app.schemas import molecule as schemas\nfrom app.models.molecule import Molecule as MoleculeModel\n\nrouter = APIRouter(\n prefix=\"/api/v1\",\n)\n\n\n@router.get(\"/molecule\", tags=[\"molecule\"], response_model=List[schemas.Molecule])\ndef molecule_list(skip: int = 0, limit: int = None, sort_by: str = 'updated', db: Session = Depends(get_db)) -> List[MoleculeModel]:\n molecules = controller.get_list_molecule(db, skip=skip, limit=limit, sort_by=sort_by)\n return molecules\n\n\n@router.post(\"/molecule\", tags=[\"molecule\"])\ndef molecule_create(molecule: schemas.MoleculeCreate, db: Session = Depends(get_db)) -> JSONResponse:\n controller.create_molecule(db=db, molecule=molecule)\n return JSONResponse(content={\"message\": \"molecule created\"})\n\n\n@router.get(\"/molecule/{molecule_id}\", tags=[\"molecule\"], response_model=schemas.MoleculeDetail)\ndef molecule_detail(molecule_id: int, db: Session = Depends(get_db)) -> MoleculeModel:\n db_molecule = controller.get_molecule(db, molecule_id=molecule_id)\n if db_molecule is None:\n raise HTTPException(status_code=404, detail=\"Molecule not found\")\n return db_molecule\n\n\n@router.put(\"/molecule/{molecule_id}\", tags=[\"molecule\"])\ndef molecule_update(\n molecule_id: int, molecule: schemas.MoleculeUpdate, db: Session = Depends(get_db)\n) -> JSONResponse:\n db_molecule = controller.update_molecule(db, molecule=molecule, molecule_id=molecule_id)\n if db_molecule is None:\n raise HTTPException(status_code=404, detail=\"Molecule not found\")\n return JSONResponse(content={\"message\": \"molecule updated\"})\n\n\n@router.delete(\"/molecule/{molecule_id}\", tags=[\"molecule\"])\ndef molecule_delete(\n molecule_id: int, db: Session = Depends(get_db)\n) -> JSONResponse:\n db_molecule = controller.delete_molecule(db, molecule_id=molecule_id)\n if db_molecule is None:\n raise HTTPException(status_code=404, detail=\"Molecule not found\")\n return JSONResponse(content={\"message\": \"molecule deleted\"})\n\n\n@router.post(\"/upload-smile/\")\nasync def smile_upload(file: UploadFile, db: Session = Depends(get_db)):\n ext_type = file.filename.split('.')\n if ext_type[-1] != 'smi':\n raise HTTPException(status_code=400, detail=\"File not supported\")\n await controller.upload_molecule(db, file=file)\n return JSONResponse(content={\"message\": \"molecule uploaded\"})\n","repo_name":"babillydj/chemistry_be","sub_path":"app/api/api_v1/molecule.py","file_name":"molecule.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"39885807498","text":"n = int(input())\ninitial_arr = list(range(1, n + 1))\n\n\ndef next_permutation(arr):\n i = len(arr) - 2\n while i >= 0 and arr[i] >= arr[i + 1]:\n i -= 1\n if i == -1:\n return None\n j = len(arr) - 1\n while arr[j] <= arr[i]:\n j -= 1\n arr[i], arr[j] = arr[j], arr[i]\n arr[i + 1:] = reversed(arr[i + 1:])\n\n return arr\n\n\nwhile initial_arr is not None:\n print(''.join(map(str, initial_arr)))\n initial_arr = next_permutation(initial_arr)\n","repo_name":"vahtovik/yandexAlgorithmTraining4.0","sub_path":"Lesson 4/task_A.py","file_name":"task_A.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"42378641328","text":"#!/usr/bin/env python\n\n\"\"\"\\\nExport a DAWNet file to a Graphviz dot file\n\"\"\"\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport shutil\nfrom dawnet import utils\nfrom dawnet.parser import dawnet\nfrom jinja2 import Environment, FileSystemLoader\nimport logging\n\n\ndef guard2string(gobj):\n if isinstance(gobj, dict):\n op = gobj['op']\n args = gobj['args']\n if op == 'AND':\n return \"({})\".format(' & '.join([guard2string(i) for i in args]))\n elif op == 'OR':\n return \"({})\".format(' | '.join([guard2string(i) for i in args]))\n else:\n return \"{}{}{}\".format(args[0], op, args[1])\n else:\n return gobj\n\n\nENV = Environment(\n autoescape=False,\n loader=FileSystemLoader(os.path.dirname(os.path.abspath(__file__))),\n trim_blocks=True,\n lstrip_blocks=True)\n\nENV.globals['guard2string'] = guard2string\n\n\ndef get_configuration(option, default=None):\n section = 'graphviz'\n default_values = {\n 'command': 'dot -Tsvg'\n }\n\n optvalue = utils.get_conf(section, option, default, default_values)\n\n if option == 'command':\n return utils.conf_shell_list(optvalue)\n else:\n return optvalue\n\n\ndef render_dawnets_dot(dawnet, file=None):\n template = ENV.get_template('dawnetviz_template.dot')\n ctx = {\n 'name': dawnet.name(),\n 'transitions': dawnet.transitions(),\n 'places': dawnet.placeNames(),\n 'dawnet': dawnet\n }\n if file:\n template.stream(ctx).dump(file)\n else:\n return template.render(ctx)\n\n\ndef run_dot(source_path, workdir, outfile):\n command = get_configuration('command')\n command.append(source_path)\n\n utils.run_solver(command, stdout=outfile, timeit=False)\n\n\ndef process_model(dawnet, outfile=sys.stdout, solve=False, keep=False, tempdir=None):\n if solve:\n tdir = utils.tempdir(prefix='dawnets_dot_', dir=tempdir)\n logging.info(\"Temporary dir in {}\".format(tdir))\n dotpath = os.path.join(tdir, '{}.dot'.format(dawnet.name()))\n with open(dotpath, 'w') as dotfile:\n render_dawnets_dot(dawnet, dotfile)\n run_dot(dotpath, tdir, outfile)\n if not keep:\n shutil.rmtree(tdir)\n else:\n render_dawnets_dot(dawnet, outfile)\n\n\ndef main(stream):\n print(render_dawnets_dot(dawnet.readDAWNET(stream)))\n\n\nif __name__ == '__main__':\n main(file(sys.argv[1], 'r'))","repo_name":"stessaris/dawnets","sub_path":"dawnet/graphviz/dawnetviz.py","file_name":"dawnetviz.py","file_ext":"py","file_size_in_byte":2420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"30337518066","text":"# -*- coding: utf-8 -*-\n# A - Serval vs Monster\n# https://atcoder.jp/contests/abc153/tasks/abc153_a\n\nH, A = map(int, input().split())\n\nans = H // A\nif H % A != 0:\n ans += 1\n\nprint(ans)\n\n# 21:00 - 21:01(AC)\n","repo_name":"yu5shi8/AtCoder","sub_path":"ABC_A/ABC153A.py","file_name":"ABC153A.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"3186212818","text":"import os\nimport time\nfrom constants import DB_FILE_NAME\nfrom pi_hole_admin import PiHoleAdmin\nfrom unique_domains_windower import UniqueDomainsWindower\nimport sqlite_utils\nimport tldextract\n\ndef initialize_default_windower(url: str, file_name: str, types: list, only_domains: bool, pi_hole_password_env_var: str=\"PI_HOLE_PW\"):\n if file_name is None:\n raise ValueError(\"Default windower should have a file name but received None.\")\n\n client = PiHoleAdmin(url, pi_hole_password_env_var=pi_hole_password_env_var)\n\n if not os.path.isfile(file_name):\n print(\"Getting new default windower\")\n windower = UniqueDomainsWindower(client, 86400 * 30, types, [\"PTR\"], 3600, True, None, file_name)\n else:\n print(\"Getting previously saved default windower\")\n windower = UniqueDomainsWindower.deserialize(client, file_name)\n\n return windower\n\ndef get_domain_from_fqdn(fqdn, extractor):\n result = extractor(fqdn)\n\n if result.suffix is not None and result.suffix.strip() != '':\n return f\"{result.domain}.{result.suffix}\"\n\n return None\n\ndef main():\n start = time.time()\n print(f\"Starting blacklist init at {start} sec since epoch\")\n\n # To minimize alerts to a manageable level, only report on new domains for\n # whitelist, but report on subdomains for blacklist.\n windower_blacklist = initialize_default_windower(os.environ['PI_HOLE_URL'], 'windower_blacklist.bin', PiHoleAdmin.ALL_BLOCKED, False)\n\n print(f\"Finished blacklist init in {time.time() - start} sec\")\n\n start = time.time()\n\n print(f\"Starting blacklist assessment at {start} sec since epoch\")\n\n previously_unseen_blocked_domain_data = windower_blacklist.get_previously_unseen_domains()\n \n oldest_bound, newest_bound = windower_blacklist.get_time_interval()\n\n extractor = tldextract.TLDExtract(cache_dir=os.environ['TLDEXTRACT_CACHE'])\n\n sqlite_utils.log_reason(DB_FILE_NAME, [{'domain': get_domain_from_fqdn(name, extractor), 'first_time_seen': seen_time, 'last_time_seen': seen_time, 'permitted': False, \"reason\": \"Blocked by PiHole\", \"name\": name} for name, seen_time in previously_unseen_blocked_domain_data.items()], updateable_fields=['permitted', 'reason', 'last_time_seen'])\n\n sqlite_utils.notify_of_new_domains_in_interval(DB_FILE_NAME, windower_blacklist._window_oldest_bound, windower_blacklist._window_newest_bound, False, os.environ['ADMIN_PHONE'], os.environ['TWILIO_PHONE'], os.environ['SES_EMAIL_ADMIN'])\n\n print(f\"Finished blacklist assessment in {time.time() - start} sec\")\n\n start = time.time()\n\n print(f\"Starting whitelist assessment at {start} sec since epoch\")\n\n # Don't log \"permitted\" domains (according to pihole API) to DB because interceptor.py has the final say on what is permitted, so no updates or inserts should be necessary on permitted domains from the PiHole API.\n # Instead, just perform notification based on data already in DB.\n sqlite_utils.notify_of_new_domains_in_interval(DB_FILE_NAME, oldest_bound, newest_bound, True, os.environ['ADMIN_PHONE'], os.environ['TWILIO_PHONE'], os.environ['SES_EMAIL_ADMIN'])\n\n print(f\"Finished whitelist assessment in {time.time() - start} sec\")\n\nif __name__ == \"__main__\":\n main()","repo_name":"awzuelsdorf/domovoi","sub_path":"new_domain_alert.py","file_name":"new_domain_alert.py","file_ext":"py","file_size_in_byte":3225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"4293798865","text":"#-*- coding:utf-8 -*-\nfrom datetime import timedelta\nfrom xml.sax.saxutils import escape\n\nfrom django.core.paginator import Paginator, EmptyPage, InvalidPage\nfrom django.http import HttpResponse\n# -*- coding: utf-8 -*-\nfrom django.shortcuts import get_object_or_404\n\nfrom baseutils.views import BaseView\nfrom baseutils.breadcrumbs import *\n\nfrom ..models import Feed, Item\n\nclass IndexView(BaseView):\n def get_metadata(self, request):\n return {\n 'title': u'团购',\n 'additional': 'View news feeds and events from across the University.',\n }\n \n @BreadcrumbFactory\n def breadcrumb(self, request, context):\n return Breadcrumb(\n self.conf.local_name, None, '团购', lazy_reverse('index')\n )\n \n def handle_GET(self, request, context):\n feeds = Feed.news.all()\n context['feeds'] = feeds\n return self.render(request, context, 'feeds/news/index',\n expires=timedelta(days=7))\n\nclass ItemListView(BaseView):\n def get_metadata(self, request, slug):\n feed = get_object_or_404(Feed.news, slug=slug)\n \n last_modified = feed.last_modified.strftime('%a, %d %b %Y') if feed.last_modified else 'never updated'\n return {\n 'last_modified': feed.last_modified,\n 'title': feed.title,\n 'additional': 'News feed , %s' % last_modified,\n }\n\n @BreadcrumbFactory\n def breadcrumb(self, request, context, slug):\n return Breadcrumb(\n self.conf.local_name,\n lazy_parent('index'),\n u'团购信息',\n lazy_reverse('item-list', args=[slug])\n )\n \n def handle_GET(self, request, context, slug):\n feed = get_object_or_404(Feed.news, slug=slug)\n context['feed'] = feed\n return self.render(request, context, 'feeds/news/item_list')\n\nclass ItemDetailView(BaseView):\n def get_metadata(self, request, slug, id):\n item = get_object_or_404(Item, feed__slug=slug, id=id)\n \n last_modified = item.last_modified.strftime('%a, %d %b %Y') if item.last_modified else 'never updated'\n return {\n 'last_modified': item.last_modified,\n 'title': item.title,\n 'additional': 'News item , %s, %s' % (escape(item.feed.title), last_modified),\n }\n\n @BreadcrumbFactory\n def breadcrumb(self, request, context, slug, id):\n return Breadcrumb(\n self.conf.local_name,\n lazy_parent('item-list', slug=slug),\n u'团购详情',\n lazy_reverse('item-detail', args=[slug, id])\n )\n \n def handle_GET(self, request, context, slug, id):\n item = get_object_or_404(Item, feed__slug=slug, id=id)\n context.update({\n 'item': item,\n 'description': item.get_description_display(request.device)\n })\n return self.render(request, context, 'feeds/news/item_detail')\n","repo_name":"alexliyu/mobilesystem","sub_path":"mobile/apps/feeds/tuan/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3004,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"22859350352","text":"import numpy as np\r\nimport random\r\n\r\ndef train_BGD(x, y, alpha, theta, max_iters, epsilon):\r\n \"\"\"\r\n 批量梯度下降算法\r\n x: 训练集,\r\n y: 标签,\r\n theta:参数向量\r\n alpha: 学习率,\r\n max_iters: 最大迭代次数\r\n epsilon:阈值\r\n \"\"\"\r\n m, _ = np.shape(x)\r\n for i in range(max_iters):\r\n d_theta = (1./m)* np.dot(np.transpose(x), np.dot(x, theta)-y) #用矩阵法对所有样本进行梯度求和\r\n theta = theta - alpha* d_theta\r\n return theta\r\n\r\ndef train_SGD(x, trainData_y, alpha, theta, max_iters, epsilon):\r\n \"\"\"\r\n 随机梯度下降算法\r\n x: 训练集,\r\n y: 标签,\r\n theta:参数向量\r\n alpha: 学习率,\r\n max_iters: 最大迭代次数\r\n epsilon:阈值\r\n \"\"\"\r\n m, _ = np.shape(x)\r\n x_index = [i for i in range(m)] #取得x的索引\r\n for i in range(max_iters):\r\n index = random.sample(x_index, 1) #从x中随机抽取一个样本的索引\r\n d_theta = np.dot(np.transpose(x[index]), np.dot(x[index], theta)-y[index][0]) #用一个样本进行梯度更新\r\n theta = theta - alpha* d_theta\r\n return theta\r\n\r\ndef train_MBGD(x, trainData_y, alpha, theta, max_iters, epsilon):\r\n \"\"\"\r\n 小批量梯度下降算法\r\n x: 训练集,\r\n y: 标签,\r\n theta:参数向量\r\n alpha: 学习率,\r\n max_iters: 最大迭代次数\r\n epsilon:阈值\r\n \"\"\"\r\n m, _ = np.shape(x)\r\n minibatch_size = 2 \r\n for i in range(max_iters):\r\n for j in range(0, m, minibatch_size):\r\n for k in range(j, j+minibatch_size-1, 1):#用minibatch_size个样本进行梯度更新\r\n d_theta = np.dot(np.transpose(x[k]), np.dot(x[k], theta)-y[k][0]) \r\n theta = theta - alpha* (1./minibatch_size)* d_theta\r\n return theta\r\n\r\n\r\ntrainData_x = np.array([[1.1, 1.5], [1.3, 1.9], [1.5, 2.3], \r\n [1.7, 2.7], [1.9, 3.1], [2.1, 3.5], [2.3, 3.9], [2.5, 4.3], \r\n [2.7, 4.7],[2.9, 5.1]])\r\n\r\ntrainData_y = np.array([2.5,3.2,3.9,4.6,5.3,6,6.7,7.4,8.1,8.8])\r\n\r\nm, n = np.shape(trainData_x) #获取数据集样本大小\r\nx0 = np.ones((m,1)) #加入x0=1\r\nx = np.hstack((x0,trainData_x)) #trainData_x中加入x0=1维\r\ny = trainData_y.reshape(m, 1)\r\n#parameters setting\r\nalpha = 0.01 #设置学习率\r\ntheta = np.ones(n+1) #初始化参数\r\n#两种终止条件\r\nmax_iters = 100000 #设置最大迭代次数(防止死循环)\r\nepsilon = 1e-4 #收敛阈值设置\r\n\r\nBGD_theta = train_BGD(x, trainData_y, alpha, theta, max_iters, epsilon)\r\nprint (\"BGD_theta\", BGD_theta)\r\n\r\nSGD_theta = train_SGD(x, trainData_y, alpha, theta, max_iters, epsilon)\r\nprint (\"SGD_theta\", SGD_theta)\r\n\r\nMBGD_theta = train_MBGD(x, trainData_y, alpha, theta, max_iters, epsilon)\r\nprint (\"MBGD_theta\", MBGD_theta)","repo_name":"YijunSu/Gradient-descent-algorithms","sub_path":"GD.py","file_name":"GD.py","file_ext":"py","file_size_in_byte":2758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"10712609617","text":"import firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import db\n\n\nclass MyService :\n def __init__(self,numero_salle,numero_table):\n cred = credentials.Certificate(\n \"/home/myadmin/PycharmProjects/testFirebase/digitalinnovation-69f64-firebase-adminsdk-uy3pm-91cead3889.json\");\n default_app = firebase_admin.initialize_app(cred, {\n 'databaseURL': 'https://digitalinnovation-69f64.firebaseio.com/'\n })\n self.mainRef = db.reference().child(\"salles\").child(str(numero_salle)).child(\"tables\").child(str(numero_table))\n try :\n self.mainRef.set(\"\")\n except :\n print(\"exception\")\n\n\n def update_face(self,nom, occurences):\n try :\n self.mainRef.child(\"recognized_faces\").child(nom).set(occurences)\n except :\n print(\"exception\")\n def update_object(self,nom, occurences):\n try :\n self.mainRef.child(\"detected_objects\").child(nom).set(occurences)\n except :\n print(\"exception\")\n def update_Angle(self,angle,r_l):\n try :\n if r_l == \"r\" :\n self.mainRef.child(\"motion_analysis\").child(\"right_angle\").set(angle)\n else :\n self.mainRef.child(\"motion_analysis\").child(\"left_angle\").set(angle)\n except :\n print(\"exception\")\n","repo_name":"ayoubSoussi/MyFraudDetector","sub_path":"MyService/myService.py","file_name":"myService.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"72129937530","text":"import cv2\nimport dlib\n\n\ndef delaunay_triangle_calculation(rect, points):\n \"\"\"\n a function to perform delaunay triangulation\n Args:\n rect: bounding rectangle\n points: facial landmark points\n\n Returns: a list of delaunay triangles\n\n \"\"\"\n # creating the subdiv class\n subdiv = cv2.Subdiv2D(rect)\n\n # Insert points into subdiv class\n for p in points:\n subdiv.insert(p)\n\n triangle_list = subdiv.getTriangleList()\n\n delaunay_tri = []\n pt = []\n\n for t in triangle_list:\n pt.append((t[0], t[1]))\n pt1 = (t[0], t[1])\n\n pt.append((t[2], t[3]))\n pt2 = (t[2], t[3])\n\n pt.append((t[4], t[5]))\n pt3 = (t[4], t[5])\n\n if in_rectangle(rect, pt1) and in_rectangle(rect, pt2) and in_rectangle(rect, pt3):\n index = []\n\n # get 68 face points by coordinates\n for j in range(0, 3):\n for k in range(0, len(points)):\n alpha = abs(pt[j][0] - points[k][0])\n beta = abs(pt[j][1] - points[k][1])\n if alpha < 1.0 and beta < 1.0:\n index.append(k)\n\n if len(index) == 3:\n delaunay_tri.append((index[0], index[1], index[2]))\n\n pt = []\n\n return delaunay_tri\n\n\ndef in_rectangle(rect, point):\n \"\"\"\n to check if a point is contained in the rectangle or not\n Args:\n rect: rectangle\n point: points to be checked\n\n Returns: a boolean value, true or false. If inside the rectangle it returns True\n\n \"\"\"\n if point[0] < rect[0]:\n return False\n\n elif point[1] < rect[1]:\n return False\n\n elif point[0] > rect[0] + rect[2]:\n return False\n\n elif point[1] > rect[1] + rect[3]:\n return False\n\n return True\n","repo_name":"adityavaishampayan/FaceSwap","sub_path":"scripts/traditional/Warping/delaunayTriangulation.py","file_name":"delaunayTriangulation.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"77"}
+{"seq_id":"8890395486","text":"numbers = list(map(int, input().split(\",\")))\ntickets = []\n\nalready_empty = False\nwhile True:\n line = input()\n if line==\"\" and already_empty:\n break\n elif line==\"\":\n already_empty=True\n continue\n already_empty=False\n curr_ticket = []\n curr_ticket.append(list(map(int, line.split())))\n for i in range(4):\n curr_ticket.append(list(map(int, input().split())))\n tickets.append(curr_ticket)\n\nnumberOfTickets = len(tickets)\n\ncalled = []\nfor ticket in range(numberOfTickets):\n called.append([0 for i in range(10)])\n\nmarked = [[[0 for i in range(5)] for j in range(5)]for k in range(numberOfTickets)]\n\nlast_number = 0\nwinning_ticket = -1\nfor current_number in numbers:\n for ticket_no in range(numberOfTickets):\n for i in range(5):\n for j in range(5):\n if tickets[ticket_no][i][j]==current_number:\n marked[ticket_no][i][j]=1\n called[ticket_no][i]+=1\n called[ticket_no][5+j]+=1\n if called[ticket_no][i]==5 or called[ticket_no][5+j]==5:\n winning_ticket = ticket_no\n break\n if winning_ticket!=-1:\n last_number = current_number\n break\n\nscore = 0;\nfor i in range(5):\n for j in range(5):\n if marked[winning_ticket][i][j]==0:\n score+=tickets[winning_ticket][i][j]\n\nprint(score*last_number)\n\n","repo_name":"AmanSharma0710/Advent-of-Code-2021","sub_path":"Day 04/4-part1.py","file_name":"4-part1.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"14338960960","text":"import os\nimport sys\n\ntry:\n import termios\nexcept ImportError:\n # No disponible en Windows\n termios = None\nfrom contextlib import contextmanager\n\nfrom dued.vendor.six import BytesIO, b, wraps\n\nfrom mock import patch, Mock\nfrom pytest import skip\nfrom pytest_relaxed import trap\n\nfrom dued import Programa, Corredor\nfrom dued.terminales import WINDOWS\n\n\nsoporte = os.path.join(os.path.dirname(__file__), \"_soporte\")\nRAIZ = os.path.abspath(os.path.sep)\n\n\ndef saltar_si_es_windows(fn):\n @wraps(fn)\n def envoltura(*args, **kwargs):\n if WINDOWS:\n skip()\n return fn(*args, **kwargs)\n\n return envoltura\n\n\n@contextmanager\ndef ruta_de_soporte():\n sys.path.insert(0, soporte)\n try:\n yield\n finally:\n sys.path.pop(0)\n\n\ndef cargar(nombre):\n with ruta_de_soporte():\n imported = __import__(nombre)\n return imported\n\n\ndef archivo_de_soporte(subpath):\n with open(os.path.join(soporte, subpath)) as fd:\n return fd.read()\n\n\n@trap\ndef correr(invocacion, programa=None, dued=True):\n \"\"\"\n Correr ``invocacion`` a través de ``programa``, devolviendo capturas del\n stream de salida.\n\n ``programa`` por defecto es ``Programa()``.\n\n Para omitir automáticamente asumiendo que argv bajo prueba comienza con\n ``\"dued\"``, diga ``dued=False``.\n\n :returns: Dos tuplas de cadenas ``stdout, stderr``.\n \"\"\"\n if programa is None:\n programa = Programa()\n if dued:\n invocacion = \"dued {}\".format(invocacion)\n programa.correr(invocacion, salir=False)\n return sys.stdout.getvalue(), sys.stderr.getvalue()\n\n\ndef confirmar(\n invocacion, salida=None, err=None, programa=None, dued=True, prueba=None\n):\n \"\"\"\n Correr una ``invocacion`` via ``programa`` y espera que la salida resultante\n coincida.\n\n Puede dar uno o ambos de ``salida``/``err`` (pero no ninguno).\n\n ``programa`` por defecto es ``Programa()``.\n\n Para omitir saltar asumiendo que argv bajo prueba comienza con ``\"dued\"``,\n diga ``dued=False``.\n\n Para personalizar el operador utilizado para las pruebas \n (default: equality), use ``prueba`` (que debería ser un contenedor de \n aserción de algún tipo).\n \"\"\"\n stdout, stderr = correr(invocacion, programa, dued)\n # Realizar pruebas\n if salida is not None:\n if prueba:\n prueba(stdout, salida)\n else:\n assert salida == stdout\n if err is not None:\n if prueba:\n prueba(stderr, err)\n else:\n assert err == stderr\n # Protéjase de los fallos silenciosos; si decimos exit=False, esta es la\n # única forma real de saber si las cosas murieron de una manera que no\n # esperábamos.\n elif stderr:\n assert False, \"Inesperado stderr: {}\".format(stderr)\n return stdout, stderr\n\nclass SubprocesoMock(object):\n def __init__(self, salida=\"\", err=\"\", salir=0, esuntty=None, autostart=True):\n self.out_file = BytesIO(b(salida))\n self.err_file = BytesIO(b(err))\n self.salir = salir\n self.esuntty = esuntty\n if autostart:\n self.iniciar()\n\n def iniciar(self):\n # Comience a parchear'\n self.popen = patch(\"dued.corredores.Popen\")\n Popen = self.popen.start()\n self.read = patch(\"os.read\")\n read = self.read.start()\n self.sys_stdin = patch(\"sys.stdin\", new_callable=BytesIO)\n sys_stdin = self.sys_stdin.start()\n # Configuro mocks\n process = Popen.valor_de_retorno\n process.cod_de_retorno = self.salir\n process.stdout.fileno.valor_de_retorno = 1\n process.stderr.fileno.valor_de_retorno = 2\n # Si se requiere, simula la detección de pty\n if self.esuntty is not None:\n sys_stdin.esuntty = Mock(valor_de_retorno=self.esuntty)\n\n def leeimitacion(fileno, count):\n fd = {1: self.out_file, 2: self.err_file}[fileno]\n return fd.read(count)\n\n read.efecto_secundario = leeimitacion\n # Devuelve el mock (simulacro) Popen, ya que a veces se quiere dentro\n # de pruebas\n return Popen\n\n def parar(self):\n self.popen.stop()\n self.read.stop()\n self.sys_stdin.stop()\n\n\ndef subproceso_mock(salida=\"\", err=\"\", salir=0, esuntty=None, insert_Popen=False):\n def decorador(f):\n @wraps(f)\n # Tenemos que incluir un @patch aquí para engañar a Pytest para que \n # ignore la prueba envuelta de \"a veces-asi\", \"a veces-no\", \"arg\".\n # (Explícitamente \"salta por delante\" más allá de lo que percibe como\n # patch args, ¡aunque en nuestro caso no se aplican a la función de\n # prueba!)\n # No importa lo que parchemos siempre y cuando no se interpongan en mi \n # camino\n @patch(\"dued.corredores.pty\")\n def envoltura(*args, **kwargs):\n proc = SubprocesoMock(\n salida=salida, err=err, salir=salir, esuntty=esuntty, autostart=False\n )\n Popen = proc.iniciar()\n args = list(args)\n args.pop() # Pop the dummy patch\n if insert_Popen:\n args.append(Popen)\n try:\n f(*args, **kwargs)\n finally:\n proc.parar()\n\n return envoltura\n\n return decorador\n\n\ndef mock_pty(\n salida=\"\",\n err=\"\",\n salir=0,\n esuntty=None,\n trailing_error=None,\n skip_asserts=False,\n insert_os=False,\n be_childish=False,\n os_close_error=False,\n):\n # Windows no tiene ptys, así que todas las pruebas pty deberían saltarse\n # de todas formas...\n if WINDOWS:\n return saltar_si_es_windows\n\n def decorador(f):\n import fcntl\n\n ioctl_patch = patch(\"dued.corredores.fcntl.ioctl\", wraps=fcntl.ioctl)\n\n @wraps(f)\n @patch(\"dued.corredores.pty\")\n @patch(\"dued.corredores.os\")\n @ioctl_patch\n def envoltura(*args, **kwargs):\n args = list(args)\n pty, os, ioctl = args.pop(), args.pop(), args.pop()\n # En realidad no se bifurquen, sino que pretendan que lo hicimos \n # (con \"nuestro\" pid diferenciado dependiendo de be_childish) y den\n # \"parent fd\" de 3 (típicamente, primero asignado non-stdin/salida/err FD)\n pty.fork.valor_de_retorno = (12345 if be_childish else 0), 3\n # No tenemos que preocuparnos por la espera ya que no es realmente\n # una forking/etc, así que aquí sólo devolvemos un \n # \"pid\" no cero + el valor del estado de espera centinela\n # (usado en algunas pruebas sobre WIFEXITED etc)\n os.waitpid.valor_de_retorno = None, Mock(nombre=\"exitstatus\")\n # Cualquiera o ambos pueden ser llamados, dependiendo...\n os.WEXITSTATUS.valor_de_retorno = salir\n os.WTERMSIG.valor_de_retorno = salir\n # Si lo solicitan, se puede hacer un simulacro de la detección de un pty.\n if esuntty is not None:\n os.esuntty.valor_de_retorno = esuntty\n out_file = BytesIO(b(salida))\n err_file = BytesIO(b(err))\n\n def leeimitacion(fileno, count):\n fd = {3: out_file, 2: err_file}[fileno]\n ret = fd.read(count)\n # Si se le pregunta, imite un error IO de la plataforma Linux.\n if not ret and trailing_error:\n raise trailing_error\n return ret\n\n os.read.efecto_secundario = leeimitacion\n if os_close_error:\n os.close.efecto_secundario = IOError\n if insert_os:\n args.append(os)\n\n # ¡¡Hazlo!!\n f(*args, **kwargs)\n\n # Cortocircuito si se produce un error de lectura. leeimitacion()\n if trailing_error:\n return\n # Chequeos de sanidad para asegurarnos que las cosas de las que\n # nos burlamos, realmente se corrieron!\n pty.fork.assert_called_with()\n # Sáltese el resto de asserts si pretendemos ser el niño\n if be_childish:\n return\n # Espere un get, y luego más tarde set, del tamaño de la terminal\n assert ioctl.llamada_a_lista_de_args[0][0][1] == termios.TIOCGWINSZ\n assert ioctl.llamada_a_lista_de_args[1][0][1] == termios.TIOCSWINSZ\n if not skip_asserts:\n for nombre in (\"execve\", \"waitpid\"):\n assert getattr(os, nombre).called\n # Asegúrate de que al menos uno de los que captadores de estatus se llame\n assert os.WEXITSTATUS.called or os.WTERMSIG.called\n # Asegúrate de que algo cierra el pty FD\n os.close.asercion_llamado_una_vez_con(3)\n\n return envoltura\n\n return decorador\n\n\nclass _Dummy(Corredor):\n \"\"\"\n Subclase de corredor ficticio (dummy) que hace el trabajo mínimo requerido\n para ejecutar correr().\n\n También sirve como un conveniente verificador básico de API; falla para \n actualizarlo para que coincida con la API actual de Corredor causará \n TypeErrors, NotImplementedErrors y similares.\n \"\"\"\n\n # Castrar el sueño del bucle de entrada, para que las pruebas no sean\n # lentas (a expensas de la CPU, que no es un problema para las pruebas).\n entrada_en_reposo = 0\n\n def iniciar(self, comando, shell, entorno, tiempofuera=None):\n pass\n\n def leer_proc_stdout(self, num_bytes):\n return \"\"\n\n def leer_proc_stderr(self, num_bytes):\n return \"\"\n\n def _escribir_proc_stdin(self, datos):\n pass\n\n def cerrar_proc_stdin(self):\n pass\n\n @property\n def proceso_esta_terminado(self):\n return True\n\n def cod_de_retorno(self):\n return 0\n\n def parar(self):\n pass\n\n @property\n def tiempo_fuera(self):\n return False\n\n\n# Comando ficticio que explotará si alguna vez golpea un shell real.\n_ = \"nop\"\n\n\n# Corredor que falsifica ^ C durante la ejecución del subproceso\nclass __CorredorDeInterrupcionDeTeclado(_Dummy):\n def __init__(self, *args, **kwargs):\n super(__CorredorDeInterrupcionDeTeclado, self).__init__(*args, **kwargs)\n self._interrupted = False\n\n # Trigger KeyboardInterrupt durante la espera ()\n def esperar(self):\n if not self._interrupted:\n self._interrupted = True\n raise KeyboardInterrupt\n\n # Pero también, después de que se haya hecho eso, simule que ocurrió el \n # cierre del subproceso (o lo haremos para siempre).\n def proceso_esta_terminado(self):\n return self._interrupted\n\n\nclass OhNoz(Exception):\n pass\n","repo_name":"dued/dued","sub_path":"pruebas/_util.py","file_name":"_util.py","file_ext":"py","file_size_in_byte":10698,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"8261661849","text":"import os\n\nimport pytest\n\nfrom cryptojwt.jws.jws import JWS\nfrom cryptojwt.jws.jws import factory\nfrom cryptojwt.key_jar import build_keyjar\nfrom cryptojwt.key_jar import init_key_jar\n\n__author__ = \"Roland Hedberg\"\n\nBASE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), \"test_keys\"))\nRSAKEY = os.path.join(BASE_PATH, \"cert.key\")\nRSA0 = os.path.join(BASE_PATH, \"rsa.key\")\nEC0 = os.path.join(BASE_PATH, \"ec.key\")\nBASEDIR = os.path.abspath(os.path.dirname(__file__))\n\n\ndef full_path(local_file):\n return os.path.join(BASEDIR, local_file)\n\n\nJWK1 = {\n \"keys\": [\n {\n \"n\": \"zkpUgEgXICI54blf6iWiD2RbMDCOO1jV0VSff1MFFnujM4othfMsad7H1kRo50YM5S_X9TdvrpdOfpz5aBaKFhT6Ziv0nhtcekq1eRl8\"\n \"mjBlvGKCE5XGk-0LFSDwvqgkJoFYInq7bu0a4JEzKs5AyJY75YlGh879k1Uu2Sv3ZZOunfV1O1Orta\"\n \"-NvS-aG_jN5cstVbCGWE20H0vF\"\n \"VrJKNx0Zf-u-aA-syM4uX7wdWgQ\"\n \"-owoEMHge0GmGgzso2lwOYf_4znanLwEuO3p5aabEaFoKNR4K6GjQcjBcYmDEE4CtfRU9AEmhcD1k\"\n \"leiTB9TjPWkgDmT9MXsGxBHf3AKT5w\",\n \"e\": \"AQAB\",\n \"kty\": \"RSA\",\n \"kid\": \"rsa1\",\n },\n {\n \"k\": \"YTEyZjBlMDgxMGI4YWU4Y2JjZDFiYTFlZTBjYzljNDU3YWM0ZWNiNzhmNmFlYTNkNTY0NzMzYjE\",\n \"kty\": \"oct\",\n },\n ]\n}\n\nKEYDEFS = [\n {\"type\": \"RSA\", \"key\": \"\", \"use\": [\"sig\"]},\n {\"type\": \"EC\", \"crv\": \"P-256\", \"use\": [\"sig\"]},\n]\n\n\nclass TestVerifyJWTKeys(object):\n @pytest.fixture(autouse=True)\n def setup(self):\n mkey = [\n {\"type\": \"RSA\", \"use\": [\"sig\"]},\n {\"type\": \"RSA\", \"use\": [\"sig\"]},\n {\"type\": \"RSA\", \"use\": [\"sig\"]},\n ]\n\n skey = [{\"type\": \"RSA\", \"use\": [\"sig\"]}]\n\n # Alice has multiple keys\n self.alice_keyjar = build_keyjar(mkey)\n # Bob has one single keys\n self.bob_keyjar = build_keyjar(skey)\n self.alice_keyjar[\"Alice\"] = self.alice_keyjar[\"\"]\n self.bob_keyjar[\"Bob\"] = self.bob_keyjar[\"\"]\n\n # To Alice's keyjar add Bob's public keys\n self.alice_keyjar.import_jwks(self.bob_keyjar.export_jwks(issuer_id=\"Bob\"), \"Bob\")\n\n # To Bob's keyjar add Alice's public keys\n self.bob_keyjar.import_jwks(self.alice_keyjar.export_jwks(issuer_id=\"Alice\"), \"Alice\")\n\n _jws = JWS('{\"aud\": \"Bob\", \"iss\": \"Alice\"}', alg=\"RS256\")\n sig_key = self.alice_keyjar.get_signing_key(\"rsa\", issuer_id=\"Alice\")[0]\n self.sjwt_a = _jws.sign_compact([sig_key])\n\n _jws = JWS('{\"aud\": \"Alice\", \"iss\": \"Bob\"}', alg=\"RS256\")\n sig_key = self.bob_keyjar.get_signing_key(\"rsa\", issuer_id=\"Bob\")[0]\n self.sjwt_b = _jws.sign_compact([sig_key])\n\n def test_no_kid_multiple_keys_no_kid_issuer(self):\n a_kids = [\n k.kid for k in self.alice_keyjar.get_verify_key(issuer_id=\"Alice\", key_type=\"RSA\")\n ]\n no_kid_issuer = {\"Alice\": a_kids}\n _jwt = factory(self.sjwt_a)\n _jwt.jwt.headers[\"kid\"] = \"\"\n keys = self.bob_keyjar.get_jwt_verify_keys(_jwt.jwt, no_kid_issuer=no_kid_issuer)\n assert len(keys) == 3\n\n def test_aud(self):\n self.alice_keyjar.import_jwks(JWK1, issuer_id=\"D\")\n self.bob_keyjar.import_jwks(JWK1, issuer_id=\"D\")\n\n _jws = JWS('{\"iss\": \"D\", \"aud\": \"A\"}', alg=\"HS256\")\n sig_key = self.alice_keyjar.get_signing_key(\"oct\", issuer_id=\"D\")[0]\n _sjwt = _jws.sign_compact([sig_key])\n\n no_kid_issuer = {\"D\": []}\n\n _jwt = factory(_sjwt)\n\n keys = self.bob_keyjar.get_jwt_verify_keys(_jwt.jwt, no_kid_issuer=no_kid_issuer)\n assert len(keys) == 1\n\n\nPUBLIC_FILE = \"{}/public_jwks.json\".format(BASEDIR)\nPRIVATE_FILE = \"{}/private_jwks.json\".format(BASEDIR)\nKEYSPEC = [\n {\"type\": \"RSA\", \"use\": [\"sig\"]},\n {\"type\": \"EC\", \"crv\": \"P-256\", \"use\": [\"sig\"]},\n]\nKEYSPEC_2 = [\n {\"type\": \"RSA\", \"use\": [\"sig\"]},\n {\"type\": \"EC\", \"crv\": \"P-256\", \"use\": [\"sig\"]},\n {\"type\": \"EC\", \"crv\": \"P-384\", \"use\": [\"sig\"]},\n]\n\n\ndef test_init_key_jar_dump_private():\n for _file in [PRIVATE_FILE, PUBLIC_FILE]:\n if os.path.isfile(_file):\n os.unlink(_file)\n\n # New set of keys, JWKSs with keys and public written to file\n _keyjar = init_key_jar(\n private_path=PRIVATE_FILE, key_defs=KEYSPEC, issuer_id=\"https://example.com\"\n )\n assert list(_keyjar.owners()) == [\"https://example.com\"]\n\n # JWKS will be read from disc, not created new\n _keyjar2 = init_key_jar(private_path=PRIVATE_FILE, key_defs=KEYSPEC)\n assert list(_keyjar2.owners()) == [\"\"]\n\n\ndef test_init_key_jar_update():\n for _file in [PRIVATE_FILE, PUBLIC_FILE]:\n if os.path.isfile(_file):\n os.unlink(_file)\n\n # New set of keys, JWKSs with keys and public written to file\n _keyjar_1 = init_key_jar(\n private_path=PRIVATE_FILE,\n key_defs=KEYSPEC,\n issuer_id=\"https://example.com\",\n public_path=PUBLIC_FILE,\n read_only=False,\n )\n assert list(_keyjar_1.owners()) == [\"https://example.com\"]\n\n _keyjar_2 = init_key_jar(private_path=PRIVATE_FILE, key_defs=KEYSPEC_2, public_path=PUBLIC_FILE)\n\n # Both should contain the same RSA key\n rsa1 = _keyjar_1.get_signing_key(\"RSA\", \"https://example.com\")\n rsa2 = _keyjar_2.get_signing_key(\"RSA\", \"\")\n\n assert len(rsa1) == 1\n assert len(rsa2) == 1\n assert rsa1[0] == rsa2[0]\n\n # keyjar1 should only contain one EC key while keyjar2 should contain 2.\n\n ec1 = _keyjar_1.get_signing_key(\"EC\", \"https://example.com\")\n ec2 = _keyjar_2.get_signing_key(\"EC\", \"\")\n assert len(ec1) == 1\n assert len(ec2) == 2\n\n # The file on disc should not have changed\n _keyjar_3 = init_key_jar(private_path=PRIVATE_FILE)\n\n assert len(_keyjar_3.get_signing_key(\"RSA\")) == 1\n assert len(_keyjar_3.get_signing_key(\"EC\")) == 1\n\n _keyjar_4 = init_key_jar(\n private_path=PRIVATE_FILE,\n key_defs=KEYSPEC_2,\n public_path=PUBLIC_FILE,\n read_only=False,\n )\n\n # Now it should\n _keyjar_5 = init_key_jar(private_path=PRIVATE_FILE)\n\n assert len(_keyjar_5.get_signing_key(\"RSA\")) == 1\n assert len(_keyjar_5.get_signing_key(\"EC\")) == 2\n","repo_name":"IdentityPython/JWTConnect-Python-CryptoJWT","sub_path":"tests/test_50_argument_alias.py","file_name":"test_50_argument_alias.py","file_ext":"py","file_size_in_byte":6103,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"77"}
+{"seq_id":"17091234506","text":"'''\r\nLevenshtein edit distance by dynamic programming\r\non two words \"a\" and \"b\" to show how close the words are\r\nand how \"a\" can be transformed to \"b\"\r\n'''\r\n# a,b=\"potato\",\"toooomaato\"\r\n# a,b=\"siens\",\"science\"\r\n# a,b=\"rooflet\",\"google\"\r\na,b=\"teknologi\",\"technology\"\r\nn,m=len(a),len(b)\r\ndp=[]\r\nfor i in range(n+1):\r\n x=[]\r\n for j in range(m+1):\r\n x.append(None)\r\n dp.append(x)\r\ndp[0][0]=0\r\ndef levenshtein_dp(a,b,i,j):\r\n if b==\"\":\r\n dp[i][0]=len(a)\r\n return len(a)\r\n if a==\"\":\r\n dp[0][j]=len(b)\r\n return len(b)\r\n if dp[i][j]!=None:\r\n return dp[i][j]\r\n c1=levenshtein_dp(a[:i-1],b[:j-1],i-1,j-1)+(a[i-1]!=b[j-1]) # replace\r\n c2=levenshtein_dp(a[:i-1],b,i-1,j)+1 # remove\r\n c3=levenshtein_dp(a,b[:j-1],i,j-1)+1 # insert\r\n dp[i][j]=min(c1,c2,c3)\r\n return dp[i][j]\r\n\r\n\r\n# print(\"\\nminimum edit required:\",levenshtein_dp(a,b,n,m))\r\n# print(\"\\n? \",end=\" \")\r\n# for i in b:\r\n# print(i,end=\" \")\r\n# print()\r\n# print(\" \",*dp[0])\r\n# for i in range(1,n+1):\r\n# print(a[i-1],*dp[i])\r\n\r\ndps=[]\r\n\r\n\r\ndef backtrack(a,b,i,j):\r\n if b==\"\":\r\n for k in range(i-1,-1,-1):\r\n dps.append(f\"remove '{a[k]}'\")\r\n return\r\n if a==\"\":\r\n for k in range(j - 1, -1, -1):\r\n dps.append(f\"insert '{b[k]}'\")\r\n return\r\n c1=levenshtein_dp(a[:i-1],b[:j-1],i-1,j-1)+(a[i-1]!=b[j-1]) # replace\r\n c2=levenshtein_dp(a[:i-1],b,i-1,j)+1 # remove\r\n # c3=levenshtein_dp(a,b[:j-1],i,j-1)+1 # insert\r\n if c1==dp[i][j]:\r\n if a[i-1]!=b[j-1]:\r\n dps.append(f\"replace '{a[i-1]}' with '{b[j-1]}'\")\r\n else:\r\n dps.append(f\"'{a[i - 1]}'\")\r\n backtrack(a[:i-1],b[:j-1],i-1,j-1)\r\n elif c2==dp[i][j]:\r\n dps.append(f\"remove '{a[i-1]}'\")\r\n backtrack(a[:i - 1], b, i - 1, j)\r\n else:\r\n dps.append(f\"insert '{b[j-1]}'\")\r\n backtrack(a, b[:j - 1], i, j - 1)\r\n return\r\n\r\n\r\n# backtrack(a,b,n,m)\r\n# while dps:\r\n# print(dps.pop())\r\n\r\n","repo_name":"djdheeraj5701/seminar-spellcheck","sub_path":"seminar_code_1.py","file_name":"seminar_code_1.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"29195637282","text":"class Node:\n def __init__(self,data):\n self.data = data\n self.next = None\n\nclass CircularLinkedList:\n def __init__(self):\n self.head = None\n\n def append(self, data):\n if not self.head:\n new_node = Node(data)\n self.head = new_node\n new_node.next = self.head\n else:\n new_node = Node(data)\n curr = self.head\n while curr:\n curr = curr.next\n if curr.next == self.head:\n break\n curr.next = new_node\n new_node.next = self.head\n\n def print_list(self):\n curr = self.head\n while curr:\n print(curr.data)\n curr = curr.next\n if curr == self.head:\n break\n\n def prepend(self,data):\n new_node = Node(data)\n curr = self.head\n new_node.next = self.head\n while curr.next != self.head:\n curr = curr.next\n curr.next = new_node\n self.head = new_node\n\n def __len__(self):\n curr = self.head\n count = 0\n while curr:\n count += 1\n #print(curr.data)\n if curr.next == self.head:\n break\n curr = curr.next\n return count\n\n def split_list(self):\n size = len(self)\n if size == 0:\n return None\n if size == 1:\n return self.head\n mid = (size // 2)\n counter = 0\n prev = None\n curr = self.head\n ## A -> B -> C -> D -> ...\n while curr and counter < mid:\n counter += 1\n prev = curr\n curr = curr.next\n prev.next = self.head\n second_circulatList = CircularLinkedList()\n while curr.next != self.head:\n second_circulatList.append(curr.data)\n curr = curr.next\n second_circulatList.append(curr.data)\n curr.next = second_circulatList\n\n self.print_list()\n print(\"\")\n second_circulatList.print_list()\n\n\ncllist = CircularLinkedList()\ncllist.append(\"A\")\ncllist.append(\"B\")\ncllist.append(\"C\")\ncllist.append(\"D\")\ncllist.prepend(\"E\")\ncllist.append(\"F\")\n#cllist.print_list()\nprint(\"\")\n#print(len(cllist))\ncllist.split_list()\n\n\n","repo_name":"manishkumar2k9/GitRepository-LeedCodeSolutions","sub_path":"circularLinkedList.py","file_name":"circularLinkedList.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"26968979066","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# 2.2.1\n\nx = np.linspace(-4, 4, 50, endpoint = True)\ny = (4 * x**2) - 16\n\nfig1 = plt.figure(num = 1, figsize = (5,5))\nplt.plot(x,y)\nplt.grid(True)\nplt.title(\"x' = 4*x^2-16\")\nplt.xlabel('x')\nplt.ylabel(\"x'\")\n\n#show the plot\nfig1.show()\n\n# 2.2.2\na = np.linspace(-2,2,50,endpoint=True)\nb = 1-x**14\n\nfig2 = plt.figure(num = 2, figsize = (5,5))\nplt.plot(a,b)\nplt.grid(True)\nplt.title(\"x' = 1-x^14\")\nplt.xlabel('x')\nplt.ylabel(\"x'\")\n\nfig2.show()\n\ninput()\n","repo_name":"ziqing-ang/strogatz_bif","sub_path":"chap2_plot.py","file_name":"chap2_plot.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"18919070631","text":"from django.shortcuts import render, get_object_or_404\nfrom django.http.response import HttpResponse\nfrom .models import Article, Classify, Lable\nfrom comment.forms import CommentForm\nimport markdown\nfrom django.core.paginator import Paginator\n# Create your views here.\n\n\ndef index(request):\n article = Article.objects.all()\n classify = Classify.objects.all()\n label = Lable.objects.all()\n\n paginato = Paginator(article, 2)\n pagenum = request.GET.get('page')\n pagenum = 1 if pagenum == None else pagenum\n print(pagenum)\n page = paginato.page(pagenum)\n content = {\n 'article': page,\n 'classify': classify,\n 'label': label,\n }\n return render(request, 'blogtest/index.html', content)\n\n\ndef label(request, num):\n article = Lable.objects.get(pk=num).la.all()\n classify = Classify.objects.all()\n tag = Lable.objects.all()\n content = {\n 'article': article,\n 'classify': classify,\n 'label': tag,\n }\n return render(request, 'blogtest/tag.html', content)\n\n\ndef classify(request, num):\n article = Classify.objects.get(pk=num)\n tag = Lable.objects.all()\n classify = Classify.objects.all()\n\n content = {\n 'label': tag,\n 'classify': classify,\n 'article': article,\n }\n return render(request, 'blogtest/classify.html', content)\n\n\ndef pigeonhole(request, num):\n article = Article.objects.filter(datetime__month=int(num)).all()\n tag = Lable.objects.all()\n classify = Classify.objects.all()\n content = {\n 'label': tag,\n 'classify': classify,\n 'article': article,\n }\n return render(request, 'blogtest/pigeonhole.html', content)\n\n\ndef detail(request, num):\n article = get_object_or_404(Article, pk=num)\n article.hits += 1\n article.save()\n tag = Lable.objects.all()\n classify = Classify.objects.all()\n\n # markdown的使用\n md = markdown.Markdown(extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n 'markdown.extensions.toc',\n ])\n article.digest = md.convert(article.digest)\n article.toc = md.toc\n content = {\n 'label': tag,\n 'classify': classify,\n 'article': article,\n 'post': CommentForm(),\n }\n return render(request, 'blogtest/detail.html', content)\n","repo_name":"taoxiaodi/DjangoProject","sub_path":"blog/blogtest/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"26501728643","text":"import os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"\nimport argparse\nimport random\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib.tensorboard.plugins import projector\nimport matplotlib.pyplot as plt\nfrom sklearn import metrics\nfrom sklearn.cluster import KMeans\n\nimport load_data\nimport utils.utils as utils\n\n\n\ndef get_latent(args,hist_len):\n files = np.array(os.listdir(os.path.join(args.data_path, 'latent')))\n IterNumExist = np.array([int(f[6:-4]) for f in files])\n argsort = np.argsort(IterNumExist)\n if hist_len > len(IterNumExist):\n return None\n cur_time_steps = IterNumExist[argsort[-hist_len:]]\n print('### running for history length of:', str(hist_len))\n print('using follow time steps:', cur_time_steps)\n data = []\n for i in cur_time_steps:\n data.append(np.load(os.path.join(args.data_path, 'latent', 'latent' + str(i) + '.npz'))['latent'])\n return np.concatenate(data, 1)\n\ndef get_clustering(args,hist_len,n_clusters):\n kmeans = KMeans(n_clusters=n_clusters, precompute_distances=True, n_jobs=32)\n data = get_latent(args, hist_len)\n kmeans.fit(data)\n y_pred = kmeans.labels_\n return y_pred\n\ndef clustering(args,x_test,y_test):\n LengthSample = [1, 5, 10]\n for l in LengthSample:\n y_pred = get_clustering(args,l,dataset_eval.num_classes)\n if y_pred is not None:\n ACC = utils.ACC(y_test, y_pred)[0]\n print('ACC = ',str(ACC))\n NMI = metrics.normalized_mutual_info_score(y_test, y_pred)\n print('NMI = ',str(NMI))\n ARI = metrics.adjusted_rand_score(y_test, y_pred)\n print('ARI = ',str(ARI))\n\ndef draw(args,x_test,y_test):\n n_clusters = args.num_clusters\n shape = x_test.shape\n y_pred = get_clustering(args, 2, n_clusters)\n img = np.zeros([n_clusters * shape[1], 10 * shape[2], shape[3]])\n for i in range(n_clusters):\n ind = np.random.permutation(np.nonzero(y_pred == i)[0])[:10]\n img[shape[1] * i:shape[1] * (i + 1), :] = np.reshape(np.transpose(x_test[ind], [1, 0, 2, 3]),\n [shape[1], shape[2] * 10, shape[3]]) / 255\n plt.imshow(img)\n plt.show()\n\ndef tsne(args,x_test,y_test):\n ind = np.random.permutation(y_test.shape[0])[:10000]\n x_test = x_test[ind]\n y_test = y_test[ind]\n LOG_DIR = './cache/tsne'\n os.makedirs(LOG_DIR,exist_ok=True)\n spirits_file = 'spirit.png'\n metadata_file = 'metadata.tsv'\n path_for_sprites = os.path.join(LOG_DIR,spirits_file)\n path_for_metadata = os.path.join(LOG_DIR,metadata_file)\n # create sprite image\n img_h = x_test.shape[1]\n img_w = x_test.shape[2]\n n_plots = int(np.ceil(np.sqrt(x_test.shape[0])))\n\n sprite_image = np.ones((img_h * n_plots, img_w * n_plots,3),np.uint8)\n\n for i in range(n_plots):\n for j in range(n_plots):\n this_filter = i * n_plots + j\n if this_filter < x_test.shape[0]:\n this_img = x_test[this_filter]\n sprite_image[i * img_h:(i + 1) * img_h,\n j * img_w:(j + 1) * img_w] = this_img\n plt.imsave(path_for_sprites, sprite_image)\n\n with open(path_for_metadata, 'w') as f:\n f.write(\"Index\\tLabel\\n\")\n for index, label in enumerate(y_test):\n f.write(\"%d\\t%d\\n\" % (index, label))\n latent = get_latent(args, 10)[ind]\n embedding_var = tf.Variable(latent.reshape(latent.shape[0],-1), name='data')\n summary_writer = tf.summary.FileWriter(LOG_DIR)\n config = projector.ProjectorConfig()\n embedding = config.embeddings.add()\n embedding.tensor_name = embedding_var.name\n embedding.metadata_path = metadata_file #'metadata.tsv'\n embedding.sprite.image_path = spirits_file #'mnistdigits.png'\n embedding.sprite.single_image_dim.extend([img_h,img_w])\n projector.visualize_embeddings(summary_writer, config)\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n saver = tf.train.Saver()\n saver.save(sess, os.path.join(LOG_DIR, \"model.ckpt\"), 1)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('data_path', type=str, help='choose data')\n parser.add_argument('mode',choices=['full', 'final', 'draw','tsne'], type=str, help='choose dataset')\n parser.add_argument('--seed', default=-1, type=int, help='the seed of the network initial')\n parser.add_argument('--num_clusters', default=20, type=int, help='number of samples in history')\n\n\n args = parser.parse_args()\n # todo check if folder exist\n\n if args.seed != -1:\n np.random.seed(args.seed)\n tf.set_random_seed(args.seed)\n os.environ['PYTHONHASHSEED'] = str(args.seed)\n random.seed(args.seed)\n \n # get dataset params\n with open(os.path.join(args.data_path,'training.log'), 'r') as f:\n i=0\n for line in f:\n if 'Argument dataset' in line:\n args.dataset = line.strip().split()[-1]\n i+=1\n elif 'Argument max_iter' in line:\n args.max_iter = float(line.strip().split()[-1])\n i+=1\n elif 'Argument save_latent_iter' in line:\n args.latent_iter = float(line.strip().split()[-1])\n i+=1\n if i==3:\n break\n\n # get all images and labels\n dataset_eval = load_data.Load(args.dataset, 'all', shuffle=False, batch_size=5000, img_size=None)\n next_element_eval = dataset_eval.get_full_next()\n config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)\n with tf.Session(config=config) as sess:\n x_test = []\n y_test = []\n dataset_eval.init_dataset(sess)\n while True:\n try:\n t_x, t_y = sess.run(next_element_eval)\n x_test.append(t_x)\n y_test.append(t_y)\n except tf.errors.OutOfRangeError:\n break\n x_test = np.squeeze(np.concatenate(x_test, 0))\n y_test = np.squeeze(np.concatenate(y_test, 0))\n\n\n if args.mode == 'clustering':\n clustering(args,x_test,y_test)\n elif args.mode == 'draw':\n draw(args,x_test,y_test)\n elif args.mode == 'tsne':\n tsne(args, x_test, y_test)","repo_name":"YuriFeigin/Cluster-With-GAN","sub_path":"cluster_analysis.py","file_name":"cluster_analysis.py","file_ext":"py","file_size_in_byte":6261,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"27380764264","text":"import time\nimport wandb\nimport torch\nimport logging\nimport torch.nn as nn\nimport torch.distributed as dist\nfrom torch.cuda.amp import autocast\n\ndef get_loss(umodel, outputs, criterion, options): \n if(options.inmodal):\n image_embeds, augmented_image_embeds = outputs.image_embeds[:len(outputs.image_embeds) // 2], outputs.image_embeds[len(outputs.image_embeds) // 2:]\n text_embeds, augmented_text_embeds = outputs.text_embeds[:len(outputs.text_embeds) // 2], outputs.text_embeds[len(outputs.text_embeds) // 2:]\n else:\n image_embeds = outputs.image_embeds\n text_embeds = outputs.text_embeds\n \n if(options.distributed):\n if(options.inmodal):\n gathered_image_embeds = [torch.zeros_like(image_embeds) for _ in range(options.num_devices)]\n gathered_text_embeds = [torch.zeros_like(text_embeds) for _ in range(options.num_devices)]\n augmented_gathered_image_embeds = [torch.zeros_like(augmented_image_embeds) for _ in range(options.num_devices)]\n augmented_gathered_text_embeds = [torch.zeros_like(augmented_text_embeds) for _ in range(options.num_devices)]\n \n dist.all_gather(gathered_image_embeds, image_embeds)\n dist.all_gather(gathered_text_embeds, text_embeds)\n dist.all_gather(augmented_gathered_image_embeds, augmented_image_embeds)\n dist.all_gather(augmented_gathered_text_embeds, augmented_text_embeds)\n \n image_embeds = torch.cat(gathered_image_embeds[:options.rank] + [image_embeds] + gathered_image_embeds[options.rank + 1:])\n text_embeds = torch.cat(gathered_text_embeds[:options.rank]+ [text_embeds] + gathered_text_embeds[options.rank + 1:])\n augmented_image_embeds = torch.cat(augmented_gathered_image_embeds[:options.rank] + [augmented_image_embeds] + augmented_gathered_image_embeds[options.rank + 1:])\n augmented_text_embeds = torch.cat(augmented_gathered_text_embeds[:options.rank]+ [augmented_text_embeds] + augmented_gathered_text_embeds[options.rank + 1:]) \n else:\n gathered_image_embeds = [torch.zeros_like(image_embeds) for _ in range(options.num_devices)]\n gathered_text_embeds = [torch.zeros_like(text_embeds) for _ in range(options.num_devices)]\n \n dist.all_gather(gathered_image_embeds, image_embeds)\n dist.all_gather(gathered_text_embeds, text_embeds)\n \n image_embeds = torch.cat(gathered_image_embeds[:options.rank] + [image_embeds] + gathered_image_embeds[options.rank + 1:])\n text_embeds = torch.cat(gathered_text_embeds[:options.rank]+ [text_embeds] + gathered_text_embeds[options.rank + 1:])\n \n logits_text_per_image = umodel.logit_scale.exp() * image_embeds @ text_embeds.t()\n logits_image_per_text = logits_text_per_image.t()\n\n if(options.inmodal):\n logits_image_per_augmented_image = umodel.logit_scale.exp() * image_embeds @ augmented_image_embeds.t()\n logits_text_per_augmented_text = umodel.logit_scale.exp() * text_embeds @ augmented_text_embeds.t()\n\n batch_size = len(logits_text_per_image)\n \n target = torch.arange(batch_size).long().to(options.device, non_blocking = True)\n \n contrastive_loss = torch.tensor(0).to(options.device)\n if(options.inmodal):\n crossmodal_contrastive_loss = (criterion(logits_text_per_image, target) + criterion(logits_image_per_text, target)) / 2\n inmodal_contrastive_loss = (criterion(logits_image_per_augmented_image, target) + criterion(logits_text_per_augmented_text, target)) / 2\n contrastive_loss = (crossmodal_contrastive_loss + inmodal_contrastive_loss) / 2\n else:\n crossmodal_contrastive_loss = (criterion(logits_text_per_image, target) + criterion(logits_image_per_text, target)) / 2\n contrastive_loss = crossmodal_contrastive_loss\n\n inmodal_cyclic_loss = torch.tensor(0).to(options.device)\n if(options.cylambda1 > 0):\n logits_image_per_image = umodel.logit_scale.exp() * image_embeds @ image_embeds.t()\n logits_text_per_text = umodel.logit_scale.exp() * text_embeds @ text_embeds.t()\n inmodal_cyclic_loss = (logits_image_per_image - logits_text_per_text).square().mean() / (umodel.logit_scale.exp() * umodel.logit_scale.exp()) * batch_size\n \n crossmodal_cyclic_loss = torch.tensor(0).to(options.device)\n if(options.cylambda2 > 0):\n crossmodal_cyclic_loss = (logits_text_per_image - logits_image_per_text).square().mean() / (umodel.logit_scale.exp() * umodel.logit_scale.exp()) * batch_size\n\n cyclic_loss = options.cylambda1 * inmodal_cyclic_loss + options.cylambda2 * crossmodal_cyclic_loss\n loss = contrastive_loss + cyclic_loss\n \n return loss, contrastive_loss, cyclic_loss\n\ndef train(epoch, model, data, optimizer, scheduler, scaler, options): \n dataloader = data[\"train\"]\n if(options.distributed): dataloader.sampler.set_epoch(epoch)\n\n model.train()\n criterion = nn.CrossEntropyLoss().to(options.device)\n\n modulo = max(1, int(dataloader.num_samples / options.batch_size / 10))\n umodel = model.module if(options.distributed) else model\n\n start = time.time()\n \n logging.info(f\"Num samples: {dataloader.num_samples}, Num_batches: {dataloader.num_batches}\")\n for index, batch in enumerate(dataloader): \n step = dataloader.num_batches * epoch + index\n scheduler(step)\n\n optimizer.zero_grad()\n \n if(options.inmodal):\n input_ids, attention_mask, pixel_values = batch[\"input_ids\"][0].to(options.device, non_blocking = True), batch[\"attention_mask\"][0].to(options.device, non_blocking = True), batch[\"pixel_values\"][0].to(options.device, non_blocking = True)\n augmented_input_ids, augmented_attention_mask, augmented_pixel_values = batch[\"input_ids\"][1].to(options.device, non_blocking = True), batch[\"attention_mask\"][1].to(options.device, non_blocking = True), batch[\"pixel_values\"][1].to(options.device, non_blocking = True)\n input_ids = torch.cat([input_ids, augmented_input_ids])\n attention_mask = torch.cat([attention_mask, augmented_attention_mask])\n pixel_values = torch.cat([pixel_values, augmented_pixel_values])\n else:\n input_ids, attention_mask, pixel_values = batch[\"input_ids\"].to(options.device, non_blocking = True), batch[\"attention_mask\"].to(options.device, non_blocking = True), batch[\"pixel_values\"].to(options.device, non_blocking = True)\n\n outputs = model(input_ids = input_ids, attention_mask = attention_mask, pixel_values = pixel_values)\n\n with autocast():\n loss, contrastive_loss, cyclic_loss = get_loss(umodel, outputs, criterion, options)\n scaler.scale(loss).backward()\n scaler.step(optimizer)\n \n scaler.update()\n umodel.logit_scale.data = torch.clamp(umodel.logit_scale.data, 0, 4.6052)\n\n end = time.time()\n\n if(options.master and (((index + 1) % modulo == 0) or (index == dataloader.num_batches - 1))):\n num_samples = (index + 1) * len(input_ids) * options.num_devices\n dataloader_num_samples = dataloader.num_samples\n\n logging.info(f\"Train Epoch: {epoch:02d} [{num_samples}/{dataloader_num_samples} ({100.0 * (index + 1) / dataloader.num_batches:.0f}%)]\\tLoss: {loss.item():.6f}\\tTime taken {end - start:.3f}\\tLearning Rate: {optimizer.param_groups[0]['lr']:.9f}\")\n\n metrics = {\"loss\": loss.item(), \"contrastive_loss\": contrastive_loss.item(), \"cyclic_loss\": cyclic_loss.item(), \"time\": end - start, \"lr\": optimizer.param_groups[0][\"lr\"]}\n if(options.wandb):\n for key, value in metrics.items():\n wandb.log({f\"train/{key}\": value, \"step\": step})\n \n start = time.time()\n","repo_name":"goel-shashank/CyCLIP","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7846,"program_lang":"python","lang":"en","doc_type":"code","stars":90,"dataset":"github-code","pt":"77"}
+{"seq_id":"24330075497","text":"import sys\nimport time\nfrom sprites import *\n\n\nclass Game:\n def __init__(self):\n pygame.init()\n pygame.display.set_caption(TITLE)\n self.screen = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))\n\n # groups\n self.all_sprites = pygame.sprite.Group()\n self.block_sprites = pygame.sprite.Group()\n\n self.player = Player(self.all_sprites)\n self.stage_setup()\n self.ball = Ball(self.all_sprites, self.player, self.block_sprites)\n\n def stage_setup(self):\n for index_row, row in enumerate(BLOCK_MAP):\n for index_col, col in enumerate(row):\n if col != \" \":\n x = index_col * (BLOCK_WIDTH + GAP_SIZE) + GAP_SIZE // 2\n y = index_row * (BLOCK_HEIGHT + GAP_SIZE) + GAP_SIZE // 2\n Block(col, (x, y), [self.all_sprites, self.block_sprites])\n\n def run(self):\n last_time = time.time()\n while True:\n dt = time.time() - last_time\n last_time = time.time()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n self.ball.active = True\n\n self.screen.fill(\"black\")\n\n # join\n self.all_sprites.update(dt)\n self.all_sprites.draw(self.screen)\n\n pygame.display.update()\n\n\nif __name__ == \"__main__\":\n game = Game()\n game.run()\n","repo_name":"piskelee/Breakout","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"622728968","text":"#Ligthning data module\nfrom . import __file__\nfrom distributed import wait\nimport glob\nimport geopandas as gpd\nimport numpy as np\nimport os\nimport pandas as pd\nfrom pytorch_lightning import LightningDataModule\nfrom src import generate\nfrom src import CHM\nfrom src import augmentation\nfrom src import megaplot\nfrom src import neon_paths\nfrom src.models import dead\nfrom src.utils import *\nfrom shapely.geometry import Point\nimport torch\nfrom torch.utils.data import Dataset\nimport rasterio\n\ndef filter_data(path, config):\n \"\"\"Transform raw NEON data into clean shapefile \n Args:\n config: DeepTreeAttention config dict, see config.yml\n \"\"\"\n field = pd.read_csv(path)\n field[\"individual\"] = field[\"individualID\"]\n field = field[~field.itcEasting.isnull()]\n field = field[~field.growthForm.isin([\"liana\",\"small shrub\"])]\n field = field[~field.growthForm.isnull()]\n field = field[~field.plantStatus.isnull()] \n field = field[field.plantStatus.str.contains(\"Live\")] \n \n groups = field.groupby(\"individual\")\n shaded_ids = []\n for name, group in groups:\n shaded = any([x in [\"Full shade\", \"Mostly shaded\"] for x in group.canopyPosition.values])\n if shaded:\n if any([x in [\"Open grown\", \"Full sun\"] for x in group.canopyPosition.values]):\n continue\n else:\n shaded_ids.append(group.individual.unique()[0])\n \n field = field[~(field.individual.isin(shaded_ids))]\n field = field[(field.height > 3) | (field.height.isnull())]\n field = field[field.stemDiameter > config[\"min_stem_diameter\"]]\n \n #Subspecies filter\n field.loc[field.taxonID==\"PSMEM\",\"taxonID\"] = \"PSME\"\n field.loc[field.taxonID==\"BEPAP\",\"taxonID\"] = \"BEPA\"\n field.loc[field.taxonID==\"ACNEN\",\"taxonID\"] = \"ACNE2\"\n field.loc[field.taxonID==\"ACRUR\",\"taxonID\"] = \"ACRU\"\n field.loc[field.taxonID==\"PICOL\",\"taxonID\"] = \"PICO\"\n field.loc[field.taxonID==\"ABLAL\",\"taxonID\"] = \"ABLA\"\n field.loc[field.taxonID==\"ACSA3\",\"taxonID\"] = \"ACSAS\"\n field.loc[field.taxonID==\"CECAC\",\"taxonID\"] = \"CECA4\"\n field.loc[field.taxonID==\"PRSES\",\"taxonID\"] = \"PRSE2\"\n field.loc[field.taxonID==\"PIPOS\",\"taxonID\"] = \"PIPO\"\n field.loc[field.taxonID==\"BEPAC2\",\"taxonID\"] = \"BEPA\"\n field.loc[field.taxonID==\"JUVIV\",\"taxonID\"] = \"JUVI\"\n field.loc[field.taxonID==\"PRPEP\",\"taxonID\"] = \"PRPE2\"\n field.loc[field.taxonID==\"COCOC\",\"taxonID\"] = \"COCO6\" \n field.loc[field.taxonID==\"NYBI\",\"taxonID\"] = \"NYSY\"\n \n field = field[~field.taxonID.isin([\"BETUL\", \"FRAXI\", \"HALES\", \"PICEA\", \"PINUS\", \"QUERC\", \"ULMUS\", \"2PLANT\"])]\n field = field[~(field.eventID.str.contains(\"2014\"))]\n with_heights = field[~field.height.isnull()]\n with_heights = with_heights.loc[with_heights.groupby('individual')['height'].idxmax()]\n \n missing_heights = field[field.height.isnull()]\n missing_heights = missing_heights[~missing_heights.individual.isin(with_heights.individual)]\n missing_heights = missing_heights.groupby(\"individual\").apply(lambda x: x.sort_values([\"eventID\"],ascending=False).head(1)).reset_index(drop=True)\n \n field = pd.concat([with_heights,missing_heights])\n \n # Remove multibole\n field = field[~(field.individual.str.contains('[A-Z]$',regex=True))]\n\n # List of hand cleaned errors\n known_errors = [\"NEON.PLA.D03.OSBS.03422\",\"NEON.PLA.D03.OSBS.03422\",\"NEON.PLA.D03.OSBS.03382\", \"NEON.PLA.D17.TEAK.01883\"]\n field = field[~(field.individual.isin(known_errors))]\n field = field[~(field.plotID == \"SOAP_054\")]\n \n #Create shapefile\n field[\"geometry\"] = [Point(x,y) for x,y in zip(field[\"itcEasting\"], field[\"itcNorthing\"])]\n shp = gpd.GeoDataFrame(field)\n \n # BLAN has some data in 18N UTM, reproject to 17N update columns\n BLAN_errors = shp[(shp.siteID == \"BLAN\") & (shp.utmZone == \"18N\")]\n BLAN_errors.set_crs(epsg=32618, inplace=True)\n BLAN_errors.to_crs(32617,inplace=True)\n BLAN_errors[\"utmZone\"] = \"17N\"\n BLAN_errors[\"itcEasting\"] = BLAN_errors.geometry.apply(lambda x: x.coords[0][0])\n BLAN_errors[\"itcNorthing\"] = BLAN_errors.geometry.apply(lambda x: x.coords[0][1])\n \n # reupdate\n shp.loc[BLAN_errors.index] = BLAN_errors\n \n # Oak Right Lab has no AOP data\n shp = shp[~(shp.siteID.isin([\"PUUM\",\"ORNL\"]))]\n\n # There are a couple NEON plots within the OSBS megaplot, make sure they are removed\n shp = shp[~shp.plotID.isin([\"OSBS_026\",\"OSBS_029\",\"OSBS_039\",\"OSBS_027\",\"OSBS_036\"])]\n\n return shp\n\ndef sample_plots(shp, min_train_samples=5, min_test_samples=3, iteration = 1):\n \"\"\"Sample and split a pandas dataframe based on plotID\n Args:\n shp: pandas dataframe of filtered tree locations\n test_fraction: proportion of plots in test datasets\n min_samples: minimum number of samples per class\n iteration: a dummy parameter to make dask submission unique\n \"\"\"\n #When splitting train/test, only use 1 sample per year for counts.\n single_year = shp.groupby(\"individual\").apply(lambda x: x.head(1))\n \n plotIDs = list(shp.plotID.unique())\n if len(plotIDs) <=2:\n test = shp[shp.plotID == shp.plotID.unique()[0]]\n train = shp[shp.plotID == shp.plotID.unique()[1]]\n\n return train, test\n else:\n plotIDs = shp[shp.siteID==\"OSBS\"].plotID.unique()\n\n np.random.shuffle(plotIDs)\n species_to_sample = shp.taxonID.unique()\n \n # Mimic natural sampling\n species_floor = single_year.taxonID.value_counts() * 0.05\n species_floor[species_floor < min_test_samples] = min_test_samples\n species_floor = species_floor.to_dict()\n \n test_plots = []\n for plotID in plotIDs:\n selected_plot = single_year[single_year.plotID == plotID]\n # If any species is missing from min samples, include plot\n if any([x in species_to_sample for x in selected_plot.taxonID.unique()]):\n test_plots.append(plotID) \n counts = single_year[single_year.plotID.isin(test_plots)].taxonID.value_counts().to_dict()\n species_completed = [key for key, value in counts.items() if value > species_floor[key]]\n species_to_sample = [x for x in shp.taxonID.unique() if not x in species_completed]\n \n #Sample from original multi_year data\n test = shp[shp.plotID.isin(test_plots)]\n train = shp[~shp.plotID.isin(test.plotID.unique())]\n\n ## Remove fixed boxes from test\n test = test.loc[~test[\"box_id\"].astype(str).str.contains(\"fixed\").fillna(False)] \n \n testids = test.groupby(\"individual\").apply(lambda x: x.head(1)).groupby(\"taxonID\").filter(lambda x: x.shape[0] >= min_test_samples).individual\n test = test[test.individual.isin(testids)]\n\n trainids = train.groupby(\"individual\").apply(lambda x: x.head(1)).groupby(\"taxonID\").filter(lambda x: x.shape[0] >= min_train_samples).individual\n train = train[train.individual.isin(trainids)]\n \n train = train[train.taxonID.isin(test.taxonID)] \n test = test[test.taxonID.isin(train.taxonID)]\n \n return train, test\n\n\ndef train_test_split(shp, config, client = None):\n \"\"\"Create the train test split\n Args:\n shp: a filter pandas dataframe (or geodataframe) \n client: optional dask client\n Returns:\n None: train.shp and test.shp are written as side effect\n \"\"\" \n min_sampled = config[\"min_train_samples\"] + config[\"min_test_samples\"]\n keep = shp.taxonID.value_counts() > (min_sampled)\n species_to_keep = keep[keep].index\n shp = shp[shp.taxonID.isin(species_to_keep)]\n print(\"splitting data into train test. Initial data has {} points from {} species with a min of {} samples\".format(shp.shape[0],shp.taxonID.nunique(),min_sampled))\n test_species = 0\n ties = []\n if client:\n futures = [ ]\n for x in np.arange(config[\"iterations\"]):\n future = client.submit(\n sample_plots,\n shp=shp,\n min_train_samples=config[\"min_train_samples\"],\n iteration=x,\n min_test_samples=config[\"min_test_samples\"],\n )\n futures.append(future)\n\n wait(futures)\n for x in futures:\n train, test = x.result()\n if test.taxonID.nunique() > test_species:\n print(\"Selected test has {} points and {} species\".format(test.shape[0], test.taxonID.nunique()))\n saved_train = train\n saved_test = test\n test_species = test.taxonID.nunique()\n ties = []\n ties.append([train, test])\n elif test.taxonID.nunique() == test_species:\n ties.append([train, test]) \n else:\n for x in np.arange(config[\"iterations\"]):\n train, test = sample_plots(\n shp=shp,\n min_train_samples=config[\"min_train_samples\"],\n min_test_samples=config[\"min_test_samples\"],\n )\n if test.taxonID.nunique() > test_species:\n print(\"Selected test has {} points and {} species\".format(test.shape[0], test.taxonID.nunique()))\n saved_train = train\n saved_test = test\n test_species = test.taxonID.nunique()\n #reset ties\n ties = []\n ties.append([train, test])\n elif test.taxonID.nunique() == test_species:\n ties.append([train, test])\n \n # The size of the datasets\n if len(ties) > 1:\n print(\"The size of tied train datasets with {} species is {}\".format(test_species, [x[0].shape[0] for x in ties])) \n print(\"The size of tied test datasets with {} species is {}\".format(test_species, [x[1].shape[0] for x in ties])) \n \n saved_train, saved_test = ties[np.argmax([x[0].shape[0] for x in ties])]\n \n train = saved_train\n test = saved_test \n \n # Give tests a unique index to match against\n test[\"point_id\"] = test.index.values\n train[\"point_id\"] = train.index.values\n \n return train, test\n\n# Dataset class\nclass TreeDataset(Dataset):\n \"\"\"A csv file with a path to image crop and label\n Args:\n csv_file: path to csv file with image_path and label\n \"\"\"\n def __init__(self, df=None, csv_file=None, config=None, train=True):\n if csv_file:\n self.annotations = pd.read_csv(csv_file)\n else:\n self.annotations = df\n \n self.train = train\n self.config = config \n self.image_size = config[\"image_size\"]\n self.years = self.annotations.tile_year.unique()\n self.individuals = self.annotations.individual.unique()\n self.image_paths = self.annotations.groupby(\"individual\").apply(lambda x: x.set_index('tile_year').image_path.to_dict())\n if train:\n self.labels = self.annotations.set_index(\"individual\").label.to_dict()\n \n # Create augmentor\n self.transformer = augmentation.train_augmentation(image_size=self.image_size)\n self.image_dict = {}\n \n # Pin data to memory if desired\n if self.config[\"preload_images\"]:\n for individual in self.individuals:\n images = []\n ind_annotations = self.image_paths[individual]\n for year in self.years:\n try:\n year_annotations = ind_annotations[year]\n image_path = os.path.join(self.config[\"crop_dir\"], year_annotations)\n image = load_image(image_path, image_size=self.image_size) \n except KeyError:\n image = torch.zeros(self.config[\"bands\"], self.config[\"image_size\"], self.config[\"image_size\"]) \n if self.train:\n image = self.transformer(image) \n images.append(image)\n self.image_dict[individual] = images\n \n def __len__(self):\n # 0th based index\n return len(self.individuals)\n\n def __getitem__(self, index):\n inputs = {}\n individual = self.individuals[index] \n if self.config[\"preload_images\"]:\n inputs[\"HSI\"] = self.image_dict[individual]\n else:\n images = []\n ind_annotations = self.image_paths[individual]\n for year in self.years:\n try:\n year_annotations = ind_annotations[year]\n image_path = os.path.join(self.config[\"crop_dir\"], year_annotations)\n image = load_image(image_path, image_size=self.image_size) \n except Exception:\n image = torch.zeros(self.config[\"bands\"], self.config[\"image_size\"], self.config[\"image_size\"]) \n if self.train:\n image = self.transformer(image) \n images.append(image)\n inputs[\"HSI\"] = images\n \n if self.train:\n label = self.labels[individual]\n label = torch.tensor(label, dtype=torch.long)\n\n return individual, inputs, label\n else:\n return individual, inputs\n \nclass TreeData(LightningDataModule):\n \"\"\"\n Lightning data module to convert raw NEON data into HSI pixel crops based on the config.yml file. \n The module checkpoints the different phases of setup, if one stage failed it will restart from that stage. \n Use regenerate=True to override this behavior in setup()\n \"\"\"\n def __init__(self, csv_file, config, HSI=True, metadata=False, client = None, data_dir=None, comet_logger=None, debug=False):\n \"\"\"\n Args:\n config: optional config file to override\n data_dir: override data location, defaults to ROOT \n regenerate: Whether to recreate raw data\n debug: a test mode for small samples\n \"\"\"\n super().__init__()\n self.ROOT = os.path.dirname(os.path.dirname(__file__))\n self.csv_file = csv_file\n self.comet_logger = comet_logger\n self.debug = debug \n\n # Default training location\n self.client = client\n self.data_dir = data_dir\n self.config = config\n\n #add boxes folder if needed\n try:\n os.mkdir(os.path.join(self.data_dir,\"boxes\"))\n except:\n pass\n \n # Clean data from raw csv, regenerate from scratch or check for progress and complete\n if self.config[\"use_data_commit\"] is None:\n if self.config[\"replace\"]: \n # Convert raw neon data to x,y tree locatins\n df = filter_data(self.csv_file, config=self.config)\n \n # Load any megaplot data\n if not self.config[\"megaplot_dir\"] is None:\n megaplot_data = megaplot.load(directory=self.config[\"megaplot_dir\"], config=self.config, site=\"OSBS\")\n #Simplify MAGNOLIA's just at OSBS\n megaplot_data.loc[megaplot_data.taxonID==\"MAGR4\",\"taxonID\"] = \"MAGNO\" \n #Hold IFAS records seperarely to model on polygons\n IFAS = megaplot_data[megaplot_data.filename.str.contains(\"IFAS\")]\n IFAS.geometry = IFAS.geometry.envelope\n IFAS[\"box_id\"] = list(range(IFAS.shape[0]))\n IFAS = IFAS[[\"geometry\",\"taxonID\",\"individual\",\"plotID\",\"siteID\",\"box_id\"]]\n IFAS[\"individual\"] = IFAS[\"individual\"]\n megaplot_data = megaplot_data[~(megaplot_data.filename.str.contains(\"IFAS\"))]\n \n df = pd.concat([megaplot_data, df])\n \n if not self.debug:\n data_from_other_sites = df[~(df.siteID==\"OSBS\")]\n data_from_OSBS = df[(df.siteID==\"OSBS\")]\n species_to_keep = df[df.siteID==\"OSBS\"].taxonID.unique()\n data_from_other_sites = data_from_other_sites[data_from_other_sites.taxonID.isin(species_to_keep)].groupby(\"taxonID\").apply(lambda x: x.head(self.config[\"samples_from_other_sites\"]))\n df = pd.concat([data_from_OSBS, data_from_other_sites])\n \n if self.comet_logger:\n self.comet_logger.experiment.log_parameter(\"Species before CHM filter\", len(df.taxonID.unique()))\n self.comet_logger.experiment.log_parameter(\"Samples before CHM filter\", df.shape[0])\n \n #Filter points based on LiDAR height\n df = CHM.filter_CHM(df, CHM_pool=self.config[\"CHM_pool\"],\n min_CHM_height=self.config[\"min_CHM_height\"], \n max_CHM_diff=self.config[\"max_CHM_diff\"], \n CHM_height_limit=self.config[\"CHM_height_limit\"]) \n \n self.canopy_points = df\n self.canopy_points.to_file(\"{}/canopy_points.shp\".format(self.data_dir))\n \n if self.comet_logger:\n self.comet_logger.experiment.log_parameter(\"Species after CHM filter\", len(df.taxonID.unique()))\n self.comet_logger.experiment.log_parameter(\"Samples after CHM filter\", df.shape[0])\n \n # Create crown data\n self.crowns = generate.points_to_crowns(\n field_data=\"{}/canopy_points.shp\".format(self.data_dir),\n rgb_dir=self.config[\"rgb_sensor_pool\"],\n savedir=\"{}/boxes/\".format(self.data_dir),\n raw_box_savedir=\"{}/boxes/\".format(self.data_dir), \n client=self.client\n )\n \n if self.config[\"megaplot_dir\"]:\n #ADD IFAS back in, use polygons instead of deepforest boxes \n self.crowns = gpd.GeoDataFrame(pd.concat([self.crowns, IFAS]))\n \n if self.comet_logger:\n self.crowns.to_file(\"{}/crowns.shp\".format(self.data_dir))\n self.comet_logger.experiment.log_parameter(\"Species after crown prediction\", len(self.crowns.taxonID.unique()))\n self.comet_logger.experiment.log_parameter(\"Samples after crown prediction\", self.crowns.shape[0])\n \n if self.comet_logger:\n self.comet_logger.experiment.log_parameter(\"Species after dead filtering\",len(self.crowns.taxonID.unique()))\n self.comet_logger.experiment.log_parameter(\"Samples after dead filtering\",self.crowns.shape[0])\n try:\n rgb_pool = glob.glob(self.config[\"rgb_sensor_pool\"], recursive=True)\n for index, row in self.predicted_dead.iterrows():\n left, bottom, right, top = row[\"geometry\"].bounds \n img_path = neon_paths.find_sensor_path(lookup_pool=rgb_pool, bounds=row[\"geometry\"].bounds)\n src = rasterio.open(img_path)\n img = src.read(window=rasterio.windows.from_bounds(left-4, bottom-4, right+4, top+4, transform=src.transform)) \n img = np.rollaxis(img, 0, 3)\n self.comet_logger.experiment.log_image(image_data=img, name=\"Dead: {} ({:.2f}) {}\".format(row[\"dead_label\"],row[\"dead_score\"],row[\"individual\"])) \n except:\n print(\"No dead trees predicted\")\n else:\n self.crowns = gpd.read_file(\"{}/crowns.shp\".format(self.data_dir))\n \n annotations = generate.generate_crops(\n self.crowns,\n savedir=self.config[\"crop_dir\"],\n sensor_glob=self.config[\"HSI_sensor_pool\"],\n convert_h5=self.config[\"convert_h5\"], \n rgb_glob=self.config[\"rgb_sensor_pool\"],\n HSI_tif_dir=self.config[\"HSI_tif_dir\"],\n client=self.client,\n replace=self.config[\"replace\"]\n )\n \n annotations.to_csv(\"{}/annotations.csv\".format(self.data_dir))\n \n if self.comet_logger:\n self.comet_logger.experiment.log_parameter(\"Species after crop generation\",len(annotations.taxonID.unique()))\n self.comet_logger.experiment.log_parameter(\"Samples after crop generation\",annotations.shape[0])\n \n if self.config[\"new_train_test_split\"]:\n self.train, self.test = train_test_split(annotations, config=self.config, client=self.client) \n \n self.train.to_csv(\"{}/train.csv\".format(self.data_dir))\n self.test.to_csv(\"{}/test.csv\".format(self.data_dir))\n \n else:\n previous_train = pd.read_csv(\"{}/train.csv\".format(self.data_dir))\n previous_test = pd.read_csv(\"{}/test.csv\".format(self.data_dir))\n \n self.train = annotations[annotations.individual.isin(previous_train.individual)]\n self.test = annotations[annotations.individual.isin(previous_test.individual)]\n \n # Capture discarded species\n individuals = np.concatenate([self.train.individual.unique(), self.test.individual.unique()])\n self.novel = annotations[~annotations.individual.isin(individuals)]\n self.novel = self.novel[~self.novel.taxonID.isin(np.concatenate([self.train.taxonID.unique(), self.test.taxonID.unique()]))]\n self.novel.to_csv(\"{}/novel_species.csv\".format(self.data_dir))\n \n # Store class labels\n unique_species_labels = np.concatenate([self.train.taxonID.unique(), self.test.taxonID.unique()])\n unique_species_labels = np.unique(unique_species_labels)\n unique_species_labels = np.sort(unique_species_labels) \n self.num_classes = len(unique_species_labels)\n \n # Taxon to ID dict and the reverse \n self.species_label_dict = {}\n for index, taxonID in enumerate(unique_species_labels):\n self.species_label_dict[taxonID] = index\n \n # Store site labels\n unique_site_labels = np.concatenate([self.train.siteID.unique(), self.test.siteID.unique()])\n unique_site_labels = np.unique(unique_site_labels)\n \n self.site_label_dict = {}\n for index, label in enumerate(unique_site_labels):\n self.site_label_dict[label] = index\n self.num_sites = len(self.site_label_dict) \n \n self.label_to_taxonID = {v: k for k, v in self.species_label_dict.items()}\n \n #Encode the numeric site and class data\n self.train[\"label\"] = self.train.taxonID.apply(lambda x: self.species_label_dict[x])\n self.train[\"site\"] = self.train.siteID.apply(lambda x: self.site_label_dict[x])\n \n self.test[\"label\"] = self.test.taxonID.apply(lambda x: self.species_label_dict[x])\n self.test[\"site\"] = self.test.siteID.apply(lambda x: self.site_label_dict[x])\n \n self.train.to_csv(\"{}/train.csv\".format(self.data_dir), index=False) \n self.test.to_csv(\"{}/test.csv\".format(self.data_dir), index=False)\n \n print(\"There are {} records for {} species for {} sites in filtered train\".format(\n self.train.shape[0],\n len(self.train.label.unique()),\n len(self.train.site.unique())\n ))\n \n print(\"There are {} records for {} species for {} sites in test\".format(\n self.test.shape[0],\n len(self.test.label.unique()),\n len(self.test.site.unique()))\n )\n \n else:\n print(\"Loading previous run\") \n self.train = pd.read_csv(\"{}/train.csv\".format(self.data_dir))\n self.test = pd.read_csv(\"{}/test.csv\".format(self.data_dir))\n \n try:\n self.train[\"individual\"] = self.train[\"individualID\"]\n self.test[\"individual\"] = self.test[\"individualID\"]\n except:\n pass\n \n self.crowns = gpd.read_file(\"{}/crowns.shp\".format(self.data_dir))\n \n #mimic schema due to abbreviation when .shp is saved\n self.canopy_points = gpd.read_file(\"{}/canopy_points.shp\".format(self.data_dir))\n \n #Store class labels\n unique_species_labels = np.concatenate([self.train.taxonID.unique(), self.test.taxonID.unique()])\n unique_species_labels = np.unique(unique_species_labels)\n unique_species_labels = np.sort(unique_species_labels) \n self.num_classes = len(unique_species_labels)\n \n #Taxon to ID dict and the reverse \n self.species_label_dict = {}\n for index, taxonID in enumerate(unique_species_labels):\n self.species_label_dict[taxonID] = index\n \n #Store site labels\n unique_site_labels = np.concatenate([self.train.siteID.unique(), self.test.siteID.unique()])\n unique_site_labels = np.unique(unique_site_labels)\n \n self.site_label_dict = {}\n for index, label in enumerate(unique_site_labels):\n self.site_label_dict[label] = index\n self.num_sites = len(self.site_label_dict) \n \n self.label_to_taxonID = {v: k for k, v in self.species_label_dict.items()}","repo_name":"AdiNarendra98/AI-for-Environment","sub_path":"Paper Re-Implementations/08.DeepTreeAttention- Trees Species Prediction/src/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":26050,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"47082238073","text":"from datetime import datetime\n\nfrom pytz import utc\n\nfrom django.contrib.auth import get_user_model\n\nfrom inboxen.account import tasks\nfrom inboxen import models\nfrom inboxen.test import InboxenTestCase\nfrom inboxen.tests import factories\n\n\nclass DeleteTestCase(InboxenTestCase):\n \"\"\"Test account deleting\"\"\"\n def setUp(self):\n self.user = factories.UserFactory()\n\n def test_delete_account(self):\n factories.EmailFactory.create_batch(10, inbox__user=self.user)\n tasks.delete_account.delay(user_id=self.user.id)\n\n self.assertEqual(get_user_model().objects.count(), 0)\n self.assertEqual(models.Email.objects.count(), 0)\n self.assertEqual(models.Inbox.objects.filter(deleted=False).count(), 0)\n self.assertEqual(models.Inbox.objects.filter(user__isnull=False).count(), 0)\n\n def test_disown_inbox(self):\n inbox = factories.InboxFactory(user=self.user)\n result = tasks.disown_inbox(inbox.id)\n self.assertTrue(result)\n\n new_inbox = models.Inbox.objects.get(id=inbox.id)\n self.assertEqual(new_inbox.created, datetime.utcfromtimestamp(0).replace(tzinfo=utc))\n self.assertNotEqual(new_inbox.description, inbox.description)\n self.assertTrue(new_inbox.deleted)\n self.assertEqual(new_inbox.user, None)\n\n result = tasks.disown_inbox(inbox.id + 12)\n self.assertFalse(result)\n\n def test_finish_delete_user(self):\n factories.InboxFactory.create_batch(4, user=self.user)\n\n with self.assertRaises(Exception):\n tasks.finish_delete_user({}, self.user.id)\n\n self.user.inbox_set.all().delete()\n tasks.finish_delete_user({}, self.user.id)\n\n with self.assertRaises(get_user_model().DoesNotExist):\n get_user_model().objects.get(id=1)\n","repo_name":"wrestrtdr/Inboxen","sub_path":"inboxen/account/tests/test_tasks.py","file_name":"test_tasks.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"77"}
+{"seq_id":"24690374215","text":"import os\r\nimport chromadb\r\nimport requests\r\nimport matplotlib.pyplot as plt\r\nfrom PIL import Image\r\nfrom transformers import ViTImageProcessor, ViTModel\r\nfrom glob import glob\r\nfrom tqdm import tqdm\r\n\r\n# img = Image.open(\"test/Bread/0.jpg\")\r\n\r\nfeature_extractor = ViTImageProcessor.from_pretrained('facebook/dino-vits16')\r\nmodel = ViTModel.from_pretrained('facebook/dino-vits16').to(\"cuda\")\r\n\r\n# print(\"Models loaded!\")\r\n\r\n# img_tensor = feature_extractor(images=img, return_tensors=\"pt\").to(\"cuda\")\r\n# outputs = model(**img_tensor)\r\n\r\n# embedding = outputs.pooler_output.detach().cpu().numpy().squeeze()\r\n\r\nchroma_client = chromadb.Client()\r\n\r\ncollection = chroma_client.create_collection(\"food\")\r\n\r\nimg_list = sorted(glob(\"test/*/*.jpg\"))\r\n\r\nlen(img_list)\r\n\r\nembeddings = []\r\nmetadatas = []\r\nids = []\r\n\r\nfor i, img_path in enumerate(tqdm(img_list)) : \r\n img = Image.open(img_path)\r\n cls = os.path.split(os.path.dirname(img_path))[-1]\r\n\r\n img_tensor = feature_extractor(images=img, return_tensors=\"pt\").to(\"cuda\")\r\n outputs = model(**img_tensor)\r\n\r\n embedding = outputs.pooler_output.detach().cpu().numpy().squeeze()\r\n\r\n embeddings.append(embedding)\r\n\r\n metadatas.append({\r\n \"uri\" : img_path,\r\n \"name\" : cls\r\n })\r\n\r\n ids.append(str(i))\r\n\r\nprint(\"Done!\")\r\n\r\ncollection.add(\r\n embeddings=embeddings,\r\n metadatas=metadatas,\r\n ids=ids,\r\n)","repo_name":"park900720000/visual-search-example-module","sub_path":"setting_example.py","file_name":"setting_example.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"19515564608","text":"from flask import Flask, request, render_template\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return \"503B Information Web App\"\n \n@app.route('/facility')\ndef facility():\n facility_id = request.args.get('facility_id', default = 'Null', type = str)\n \n if facility_id == 'Null':\n return 'Please select a facility from the drop down.'\n \n@app.route('/active')\ndef active():\n active_id = request.args.get('active_id', default = 'Null', type = str)\n \n if active_id == 'Null':\n return 'Please select an active from the drop down.'\n \nif __name__ == '__main__':\n app.run(debug=True)\n \n ","repo_name":"m6urns/FDA-503B","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"19310366099","text":"#Python Modules Section 2\r\n#Tatum Gray\r\n#3/10/2016\r\nimport math\r\nimport turtle\r\n\r\nwn = turtle.Screen()\r\nwn.bgcolor('lightblue')\r\n\r\nfred = turtle.Turtle()\r\nwn.setworldcoordinates(0,-1.25,360,1.25)\r\n\r\nfred.penup()\r\nfor angle in range(360):\r\n y = math.cos(math.radians(angle))\r\n fred.goto(angle, y)\r\n fred.pendown()\r\n #print(y)\r\n\r\nwn.exitonclick()\r\n","repo_name":"Saltytatertot/Old-Python-Files","sub_path":"Python Modules Section 2.py","file_name":"Python Modules Section 2.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"38168331272","text":"import tempfile\nimport signal\nimport base64\nimport binascii\nfrom pwn import *\nimport sys\n\n\ndef handler(signum, frame):\n raise OSError(\"Wakeup\")\n\n\ndef main():\n signal.signal(signal.SIGALRM, handler)\n signal.alarm(60)\n\n try:\n b64 = input(\"Base64 encoded file: \").strip()\n except EOFError:\n return\n\n try:\n js = base64.b64decode(b64)\n except binascii.Error:\n print(\"Invalid input\", flush=True)\n return\n\n if len(js) >= 50000:\n print(\"Invalid input\", flush=True)\n return\n \n with tempfile.NamedTemporaryFile() as f:\n f.write(js)\n f.seek(0)\n\n try:\n # no jit/wasm for you :)\n p = process([\"./d8\", \"--jitless\", \"--no-expose-wasm\", f.name])\n p.interactive()\n sys.stdout.flush()\n except Exception as e:\n print(e, flush=True)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"sajjadium/ctf-archives","sub_path":"ctfs/KITCTFCTF/2022/pwn/date/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","stars":490,"dataset":"github-code","pt":"77"}
+{"seq_id":"30338368106","text":"# -*- coding: utf-8 -*-\n# C - Build Stairs\n# https://atcoder.jp/contests/abc136/tasks/abc136_c\n\nn = int(input())\nh = list(map(int, input().split()))\ncheck = 0\n\nfor i in h:\n if check - 1 <= i:\n check = max(check, i)\n else:\n print('No')\n exit()\n\nprint('Yes')\n\n# [1] 14:54 - 15:57(WA)-(解説を閲覧)16:11(WA)-(解答を閲覧)16:22\n# [2] 17:32 - 17:35(AC)\n","repo_name":"yu5shi8/AtCoder","sub_path":"ABC_C/ABC136C.py","file_name":"ABC136C.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"23436809894","text":"from telethon.sync import TelegramClient\nfrom telethon.sessions import StringSession\n\n# Run this file once to create a new session, if needed. This needs manual input from the user:\n# phone number and verification code.\n# This prints a session string that can be used in automated tests.\n\n# Get these from https://my.telegram.org/apps\napi_id = 12345678\napi_hash = \"1234567890abcd\"\ndc_number = 2\ndc_ip = \"1.2.3.4\"\n\nsession = StringSession()\nsession.set_dc(2, api_id, 443)\n\nwith TelegramClient(StringSession(), api_id, api_hash) as client:\n client.session.set_dc(dc_number, dc_ip, 443)\n print(\"Your session string is:\", client.session.save())\n","repo_name":"terisikk/janisbot4","sub_path":"tests/e2e/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"1455041870","text":"from datetime import datetime,timezone\nfrom obspy import read_inventory, UTCDateTime\nimport sys\nimport os\n\nuser_input_path = input(\"Enter the path of the inventory file: \")\nassert os.path.exists(user_input_path), \"I did not find the file at, \"+str(user_input_path)\nf = open(user_input_path,'r+')\nprint(\"Inventory file found!\")\nf.close()\n\ninventory = read_inventory(user_input_path)\ndatetime = UTCDateTime(datetime.now(timezone.utc))\nresponse = inventory.get_response(\"AM.R6833.00.EHZ\", datetime)\nprint(\"Getting channel response...\")\nprint(response)","repo_name":"rodonile/rsudp-leq","sub_path":"rsudp/inventory_files/get_response.py","file_name":"get_response.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"30083216227","text":"# Именованные аргументы.\n# Тут используются параметры по умолчанию, он обязательно должнен стоят в конце.\ndef describe_pet(pet_name, animal_type=\"собака\"):\n \"\"\"\n Выводит информацию о животном.\n :param animal_type: вид животного\n :param pet_name: кличка животного\n :return:\n \"\"\"\n print(f\"\\nУ меня есть {animal_type}\")\n print(f\"Кличка моей {animal_type} {pet_name.title()}\")\n\ndescribe_pet(pet_name=\"шелби\") # Так как у нас установлен параметр по умолчанию, нет необходимости его пердовать в функцию.\ndescribe_pet(animal_type=\"кошка\", pet_name=\"сима\") # Вызов функции с двумя параметрами.","repo_name":"MaximZolotukhin/erik_metiz","sub_path":"chapter_8/04_pets_v3.py","file_name":"04_pets_v3.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"32680981557","text":"from colorama import Fore, Style\nimport colorama\n\nif __name__ == '__main__':\n # Task 1\n text = 'Berlin is a world city of culture, politics, media and science.'\n print(len(text))\n\n # Task 2\n print(f'{text[0]} {text[-1]}')\n\n # Task 3\n print(f'{text[0:3].upper()}')\n\n # Task 4\n text = \"Berlin is surrounded by the State of Brandenburg and contiguous with Potsdam, Brandenburg's capital \"\n count = text.count('B')\n print(f'B appears: {count}' + Fore.BLUE + ' times' + Style.RESET_ALL)\n\n # Task 5\n text = \"Berlin straddles the banks of the Spree, which flows into the Havel (a tributary of the Elbe) in the \" \\\n \"western borough of Spandau.\"\n last_10_char = text[-10:]\n print(last_10_char)\n\n # Task 6\n text = \"---Python programming---\"\n strip_text = text.strip('-')\n print(strip_text)\n\n # Task 7\n first_name = 'Divya'\n last_name = 'Chandran'\n f_name = 'Firstname' + ': ' + first_name\n l_name = 'Lastname' + ': ' + last_name\n print(f'{f_name}\\n{l_name}')\n\n\n\n","repo_name":"divyaChandran10/my_new_project","sub_path":"May12_Strings_in_Depth/Exercise2.py","file_name":"Exercise2.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"17620989607","text":"from flask import Flask, jsonify, request\n\napp = Flask(__name__)\n\n\n@app.route('/test', methods=['POST'])\ndef cut_string():\n requested = str(request.get_json()['string_to_cut'])\n letters = ''.join(character for character in requested if character.isalpha())\n cut = letters[2::3]\n return jsonify({\"return_string\": cut})\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"ahmed-belhadj/flask-sample","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"14527793579","text":"import sqlite3\nimport json\nfrom models import Location\n\nLOCATIONS = [\n {\"id\": 1, \"name\": \"Nashville North\", \"address\": \"8422 Johnson Pike\"},\n {\"id\": 2, \"name\": \"Nashville South\", \"address\": \"209 Emory Drive\"},\n]\n\n\ndef delete_location(id):\n \"\"\"Delete data from location list\n\n Args:\n id (int): id of location to be deleted\n \"\"\"\n # Initial -1 value for location index, in case one isn't found\n location_index = -1\n\n # Iterate the LOCATIONS list, but use enumerate() so that you\n # can access the index value of each item\n for index, location in enumerate(LOCATIONS):\n if location[\"id\"] == id:\n # Found the location. Store the current index.\n location_index = index\n\n # If the location was found, use pop(int) to remove it from list\n if location_index >= 0:\n LOCATIONS.pop(location_index)\n\n\ndef get_all_locations():\n \"\"\"\n whats happening here?\n \"\"\"\n # Open a connection to the database\n with sqlite3.connect(\"./kennel.sqlite3\") as conn:\n\n # Just use these. It's a Black Box.\n conn.row_factory = sqlite3.Row\n db_cursor = conn.cursor()\n\n # Write the SQL query to get the information you want\n db_cursor.execute(\n \"\"\"\n SELECT\n a.id,\n a.name,\n a.address\n FROM Location a\n \"\"\"\n )\n\n # Initialize an empty list to hold all location representations\n locations = []\n\n # Convert rows of data into a Python list\n dataset = db_cursor.fetchall()\n\n # Iterate list of data returned from database\n for row in dataset:\n\n # Create an location instance from the current row.\n # Note that the database fields are specified in\n # exact order of the parameters defined in the\n # Location class above.\n location = Location(row[\"id\"], row[\"name\"], row[\"address\"])\n\n locations.append(location.__dict__)\n\n # Use `json` package to properly serialize list as JSON\n return json.dumps(locations)\n\n\n# Function with a single parameter\ndef get_single_location(id):\n \"\"\"Acess single location data from locations list\n\n Args:\n id : id of location to be acessed\n\n Returns:\n str: _description_\n \"\"\"\n # Variable to hold the found location, if it exists\n requested_location = None\n\n # Iterate the LOCATIONS list above. Very similar to the\n # for..of loops you used in JavaScript.\n for location in LOCATIONS:\n # Dictionaries in Python use [] notation to find a key\n # instead of the dot notation that JavaScript used.\n if location[\"id\"] == id:\n requested_location = location\n\n return requested_location\n\n\ndef update_location(id, new_location):\n \"\"\"_summary_\n\n Args:\n id (_type_): _description_\n new_employee (_type_): _description_\n \"\"\"\n # Iterate the employeeS list, but use enumerate() so that\n # you can access the index value of each item.\n for index, location in enumerate(LOCATIONS):\n if location[\"id\"] == id:\n # Found the location. Update the value.\n LOCATIONS[index] = new_location\n break\n","repo_name":"trobinson1097/Kennels_Server","sub_path":"views/locations_requests.py","file_name":"locations_requests.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"32676381538","text":"# This is the manual slice of:\n# weekly\n# from file:\n# sources/pandas_exercises/06_Stats/Wind_Stats/Exercises_with_solutions.ipynb\n\n# To verify that linea produces the same slice, run:\n# pytest -m integration --runxfail -vv 'tests/integration/test_slice.py::test_slice[pandas_stats]'\n\nimport datetime\n\nimport pandas as pd\n\ndata_url = \"https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/Wind_Stats/wind.data\"\ndata = pd.read_csv(data_url, sep=\"\\\\s+\", parse_dates=[[0, 1, 2]])\n\n\ndef fix_century(x):\n year = x.year - 100 if x.year > 1989 else x.year\n return datetime.date(year, x.month, x.day)\n\n\ndata[\"Yr_Mo_Dy\"] = data[\"Yr_Mo_Dy\"].apply(fix_century)\ndata[\"Yr_Mo_Dy\"] = pd.to_datetime(data[\"Yr_Mo_Dy\"])\ndata = data.set_index(\"Yr_Mo_Dy\")\nweekly = data.resample(\"W\").agg([\"min\", \"max\", \"mean\", \"std\"])\nlinea_artifact_value = weekly\n","repo_name":"LineaLabs/lineapy","sub_path":"tests/integration/slices/pandas_stats.py","file_name":"pandas_stats.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":634,"dataset":"github-code","pt":"77"}
+{"seq_id":"70763698170","text":"from reportlab.lib.pagesizes import LETTER # pdf大小,信纸大小: (612, 792)\nfrom reportlab.lib.units import inch, cm # 画布,添加自定义内容: 页眉页脚\nfrom reportlab.pdfgen import canvas # 画布,添加自定义内容: 页眉页脚\n\nfrom reportlab.pdfbase import pdfmetrics # 注册字体: 支持中文\nfrom reportlab.pdfbase.ttfonts import TTFont # 构造字体: 支持中文\nfrom reportlab.platypus import Paragraph, SimpleDocTemplate, Table, LongTable, Image # 构造内容\nfrom reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle # 获取与添加样式\nfrom reportlab.lib.enums import TA_JUSTIFY # 对齐方式\n\n\nclass GenPDF:\n def __init__(self):\n self.header = \"第 %d 页\" # 页眉页脚\n self.STYLE = self.get_styles()\n\n # 基础配置\n def get_styles(self):\n pdfmetrics.registerFont(TTFont('SimSun', '../fonts/SimSun.ttf')) # 默认不支持中文,需要注册字体\n pdfmetrics.registerFont(TTFont('SimSunBd', '../fonts/SimSun-bold.ttf')) # 默认不支持中文,需要注册字体\n\n # registerFontFamily('SimSun', normal='SimSun', bold='SimSunBd', italic='VeraIt', boldItalic='VeraBI')\n\n stylesheet = getSampleStyleSheet() # 获取样式集\n\n # 获取reportlab自带样式\n Normal = stylesheet['Normal']\n BodyText = stylesheet['BodyText']\n Italic = stylesheet['Italic']\n Title = stylesheet['Title']\n Heading1 = stylesheet['Heading1']\n Heading2 = stylesheet['Heading2']\n Heading3 = stylesheet['Heading3']\n Heading4 = stylesheet['Heading4']\n Heading5 = stylesheet['Heading5']\n Heading6 = stylesheet['Heading6']\n Bullet = stylesheet['Bullet']\n Definition = stylesheet['Definition']\n Code = stylesheet['Code']\n\n # 自带样式不支持中文,需要设置中文字体,但有些样式会丢失,如斜体Italic。有待后续发现完全兼容的中文字体\n Normal.fontName = 'SimSun'\n Italic.fontName = 'SimSun'\n BodyText.fontName = 'SimSun'\n Title.fontName = 'SimSunBd'\n Heading1.fontName = 'SimSun'\n Heading2.fontName = 'SimSun'\n Heading3.fontName = 'SimSun'\n Heading4.fontName = 'SimSun'\n Heading5.fontName = 'SimSun'\n Heading6.fontName = 'SimSun'\n Bullet.fontName = 'SimSun'\n Definition.fontName = 'SimSun'\n Code.fontName = 'SimSun'\n\n # 添加自定义样式\n stylesheet.add(\n ParagraphStyle(name='body',\n fontName=\"SimSun\",\n fontSize=10,\n textColor='black',\n leading=20, # 行间距\n spaceBefore=0, # 段前间距\n spaceAfter=10, # 段后间距\n leftIndent=0, # 左缩进\n rightIndent=0, # 右缩进\n firstLineIndent=20, # 首行缩进,每个汉字为10\n alignment=TA_JUSTIFY, # 对齐方式\n\n # bulletFontSize=15, #bullet为项目符号相关的设置\n # bulletIndent=-50,\n # bulletAnchor='start',\n # bulletFontName='Symbol'\n )\n )\n body = stylesheet['body']\n return {\"Normal\": Normal, \"Italic\": Italic, \"BodyText\": BodyText, \"Title\": Title, \"Heading1\": Heading1,\n \"Heading2\": Heading2, \"Heading3\": Heading3, \"Heading4\": Heading4, \"Heading5\": Heading5,\n \"Heading6\": Heading6, \"Bullet\": Bullet, \"Definition\": Definition, \"Code\": Code, \"body\": body}\n\n # 第一页的页眉\n def set_header(self, canvas, doc): # 设置首页,参数格式固定\n canvas.saveState() # 保存之前的画笔格式等状态,并设置新的状态\n canvas.setFont('SimSun', 9) # 使用注册的字体\n canvas.drawString(doc.width / 5.0, doc.height + 100, str(doc.title))\n canvas.setFont('SimSun', 9)\n canvas.drawString(4 * inch, 0.75 * inch, self.header % doc.page)\n canvas.restoreState() # 将画笔格式等状态还原\n\n # # 其他页的页眉\n # def myLaterPages(self, canvas, doc): # 设置其他页\n # canvas.saveState() # 保存之前画笔的格式\n # canvas.setFont('SimSun', 9) # 使用注册的字体\n # canvas.drawString(doc.width / 5.0, doc.height + 100, str(doc.title))\n # canvas.setFont('SimSun', 9) # 设置新的样式\n # canvas.drawString(4 * inch, 0.75 * inch, self.header % doc.page) # 填充新的内容\n # canvas.restoreState() # 画笔样式还原\n\n def wrap_contents(self, styles, contents):\n wrapped_contents = []\n\n for k, v in contents.items():\n wrapped_contents.append(Paragraph(v, styles[k]))\n\n # # title的内容用title_style包装\n # wrapped_contents.append(Paragraph(title, title_style))\n # # 段落的内容用body_style包装\n # for content in contents:\n # # wrapped_contents.append(Paragraph(''+content+' ' + '', body_style))\n # wrapped_contents.append(Paragraph('' + content + ' ', body_style))\n return wrapped_contents\n\n def write2pdf(self, filepath, wrapped_contents, styles_all):\n doc = SimpleDocTemplate(filepath, pagesize=LETTER, title=styles_all.get(\"title\"))\n doc.build(wrapped_contents, onFirstPage=self.set_header, onLaterPages=self.set_header)\n\n def run(self, filepath, styles, contents):\n \"\"\"\n filepath: 生成的pdf\n styles: {\"title\": \"\", \"para1_title\": \"\", \"para1_body\": \"\"} 每个部分指定样式\n contens: {\"title\": \"\", \"para1_title\": \"\", \"para1_body\": \"\"} 每个部分指定内容\n \"\"\"\n styles = {k: self.STYLE.get(v, self.STYLE[\"body\"]) for k, v in styles.items()} # 得到目标样式\n wrapped_contents = self.wrap_contents(styles, contents) # 获取内容\n self.write2pdf(filepath, wrapped_contents, self.STYLE)\n\n\nif __name__ == \"__main__\":\n run(\"test.pdf\", styles={\"title\": \"Title\"}, contents={\"title\": \"testTitle\"})","repo_name":"Cookie-YY/data-interface","sub_path":"datashow/utils/generate_file/generate_file.py","file_name":"generate_file.py","file_ext":"py","file_size_in_byte":6270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"18184418226","text":"\"\"\"Test Suite for `src.tasks.trends` module.\"\"\"\nimport datetime\nimport pytest\nfrom unittest import TestCase, mock\n\nimport tweepy\nfrom prefect import Task\nfrom snowflake import connector\n\nfrom src.tasks.trends import Trend, Trends\nfrom tests.fixtures import MockSnowflakeConnection\n\nTRENDS_RESPONSE = [\n {\n \"trends\": [\n {\n \"name\": \"Quavo\",\n \"url\": \"http://twitter.com/search?q=Quavo\",\n \"promoted_content\": None,\n \"query\": \"Quavo\",\n \"tweet_volume\": 222585,\n }\n ]\n }\n]\n\n\nclass TestTrend(TestCase):\n \"\"\"Test for `src.tasks.trends.Trend`.\"\"\"\n\n def setUp(self):\n \"\"\"Setup the test case. Initialize the task object.\"\"\"\n self.trend = Trend(\n date_created=datetime.datetime(2020, 1, 1),\n metro=\"usa\",\n woe=23424977,\n name=\"Quavo\",\n url=\"http://twitter.com/search?q=Quavo\",\n promoted=None,\n querystring=\"Quavo\",\n volume=222585,\n )\n\n def test_dict(self):\n \"\"\"Test `.to_dict()` method on trend.\"\"\"\n result = self.trend.to_dict()\n\n assert result == {\n \"date_created\": datetime.datetime(2020, 1, 1),\n \"metro\": \"usa\",\n \"woe\": 23424977,\n \"name\": \"Quavo\",\n \"url\": \"http://twitter.com/search?q=Quavo\",\n \"promoted\": None,\n \"querystring\": \"Quavo\",\n \"volume\": 222585,\n }\n\n\nclass TestTrends(TestCase):\n \"\"\"Test for `src.tasks.trends.Trends`.\"\"\"\n\n def setUp(self):\n \"\"\"Setup the test case. Initialize the task object.\"\"\"\n self.task = Trends()\n\n def test_object(self):\n \"\"\"Test object type.\"\"\"\n assert isinstance(self.task, Task)\n\n @mock.patch.object(connector, \"connect\")\n @mock.patch.object(tweepy.API, \"trends_place\")\n def test_run(self, mock_tweepy, mock_snowflake):\n \"\"\"Test `.run()` method on task.\"\"\"\n mock_tweepy.return_value = TRENDS_RESPONSE\n mock_snowflake.return_value = MockSnowflakeConnection()\n result = self.task.run(\"usa\")\n\n assert isinstance(result, list)\n assert isinstance(result[0], Trend)\n\n def test_run_raises(self):\n \"\"\"Test `.run()` method on task raises.\"\"\"\n with pytest.raises(AssertionError):\n self.task.run(\"something-else\")\n\n def test_build_client(self):\n \"\"\"Test `_build_client()` method on task.\"\"\"\n result = self.task._build_client()\n\n assert isinstance(result, tweepy.API)\n","repo_name":"2rincubator/viral-t","sub_path":"tests/test_tasks/test_trends.py","file_name":"test_trends.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"41714426572","text":"import csv, os, sys, requests, io, zipfile\n\n# AQS parameter codes: https://aqs.epa.gov/aqsweb/documents/codetables/parameters.html\nPOLLUTANTS = {\n '44201': 'Ozone',\n '42401': 'SO2',\n '42101': 'CO',\n '42602': 'NO2',\n '88101': 'PM2.5',\n '81102': 'PM10',\n}\n\nSTART_YEAR = 1980\n\nCSV_COLUMNS = [\n 'Date', 'Site_Number', 'Site_Name', 'Site_Location', 'County', 'Units',\n 'Method', 'POC', 'Mean', 'Max', 'AQI', 'Mean_SV', 'Max_SV', 'AQI_SV'\n]\n\n# Template MCF for StatVarObservation\nTEMPLATE_MCF = '''\nNode: E:EPA_AirQuality->E1\ntypeOf: dcs:StatVarObservation\nvariableMeasured: C:EPA_AirQuality->Mean_SV\nmeasurementMethod: C:EPA_AirQuality->Method\nobservationDate: C:EPA_AirQuality->Date\nobservationAbout: E:EPA_AirQuality->E0\nobservationPeriod: \"P1D\"\nvalue: C:EPA_AirQuality->Mean\nunit: C:EPA_AirQuality->Units\nairQualitySiteMonitor: C:EPA_AirQuality->POC\n\nNode: E:EPA_AirQuality->E2\ntypeOf: dcs:StatVarObservation\nvariableMeasured: C:EPA_AirQuality->Max_SV\nmeasurementMethod: C:EPA_AirQuality->Method\nobservationDate: C:EPA_AirQuality->Date\nobservationAbout: E:EPA_AirQuality->E0\nobservationPeriod: \"P1D\"\nvalue: C:EPA_AirQuality->Max\nunit: C:EPA_AirQuality->Units\nairQualitySiteMonitor: C:EPA_AirQuality->POC\n\nNode: E:EPA_AirQuality->E3\ntypeOf: dcs:StatVarObservation\nvariableMeasured: C:EPA_AirQuality->AQI_SV\nmeasurementMethod: C:EPA_AirQuality->Method\nobservationDate: C:EPA_AirQuality->Date\nobservationAbout: E:EPA_AirQuality->E0\nobservationPeriod: \"P1D\"\nvalue: C:EPA_AirQuality->AQI\nairQualitySiteMonitor: C:EPA_AirQuality->POC\n'''\n\n# Template MCF for Air Quality Site\nTEMPLATE_MCF_AIR_QUALITY_SITE = '''\nNode: E:EPA_AirQuality->E0\ntypeOf: dcs:AirQualitySite\ndcid: C:EPA_AirQuality->Site_Number\nname: C:EPA_AirQuality->Site_Name\nlocation: C:EPA_AirQuality->Site_Location\ncontainedInPlace: C:EPA_AirQuality->County\n'''\n\n\n# Convert to CamelCase (splitting on spaces)\n# Example: Parts per million -> PartsPerMillion\ndef get_camel_case(s):\n if s == '' or s == ' - ':\n return ''\n parts = s.lower().split()\n result = ''\n for i in range(len(parts)):\n result += parts[i][0].upper()\n if len(parts[i]) > 0:\n result += parts[i][1:]\n return result\n\n\n# Example: Ozone 8-hour 2015 -> Ozone_8hour_2015\ndef get_pollutant_standard(s):\n return s.replace(' ', '_').replace('-', '')\n\n\ndef create_csv(csv_file_path):\n with open(csv_file_path, 'w', newline='') as f_out:\n writer = csv.DictWriter(f_out,\n fieldnames=CSV_COLUMNS,\n lineterminator='\\n')\n writer.writeheader()\n\n\ndef write_csv(csv_file_path, reader):\n with open(csv_file_path, 'a', newline='') as f_out:\n writer = csv.DictWriter(f_out,\n fieldnames=CSV_COLUMNS,\n lineterminator='\\n')\n monitors = {}\n keys = set()\n for observation in reader:\n # For a given site and pollutant standard, select the same monitor\n monitor_key = (\n observation['State Code'],\n observation['County Code'],\n observation['Site Num'],\n get_pollutant_standard(observation['Pollutant Standard']),\n )\n if monitor_key not in monitors:\n monitors[monitor_key] = observation['POC']\n elif monitors[monitor_key] != observation['POC']:\n continue\n key = (\n observation['Date Local'],\n observation['State Code'],\n observation['County Code'],\n observation['Site Num'],\n get_pollutant_standard(observation['Pollutant Standard']),\n )\n if key in keys:\n continue\n keys.add(key)\n suffix = POLLUTANTS[observation[\"Parameter Code\"]]\n new_row = {\n 'Date':\n observation['Date Local'],\n 'Site_Number':\n 'epa/{state}{county}{site}'.format(\n state=observation['State Code'],\n county=observation['County Code'],\n site=observation['Site Num']),\n 'Site_Name':\n observation['Local Site Name'],\n 'Site_Location':\n '[latLong {lat} {long}]'.format(\n lat=observation['Latitude'],\n long=observation['Longitude']),\n 'County':\n 'dcid:geoId/' + observation['State Code'] +\n observation['County Code'],\n 'POC':\n observation['POC'],\n 'Units':\n get_camel_case(observation['Units of Measure']),\n 'Method':\n get_pollutant_standard(observation['Pollutant Standard']),\n 'Mean':\n observation['Arithmetic Mean'],\n 'Max':\n observation['1st Max Value'],\n 'AQI':\n observation['AQI'],\n 'Mean_SV':\n f'dcs:Mean_Concentration_AirPollutant_{suffix}',\n 'Max_SV':\n f'dcs:Max_Concentration_AirPollutant_{suffix}',\n 'AQI_SV':\n f'dcs:AirQualityIndex_AirPollutant_{suffix}',\n }\n writer.writerow(new_row)\n\n\ndef write_tmcf(tmcf_file_path):\n with open(tmcf_file_path, 'w') as f_out:\n f_out.write(TEMPLATE_MCF_AIR_QUALITY_SITE)\n f_out.write(TEMPLATE_MCF)\n\n\nif __name__ == '__main__':\n end_year = sys.argv[1]\n create_csv('EPA_AirQuality.csv')\n for pollutant in POLLUTANTS:\n for year in range(START_YEAR, int(end_year) + 1):\n filename = f'daily_{pollutant}_{year}'\n print(filename)\n response = requests.get(\n f'https://aqs.epa.gov/aqsweb/airdata/{filename}.zip')\n with zipfile.ZipFile(io.BytesIO(response.content)) as zf:\n with zf.open(f'{filename}.csv', 'r') as infile:\n reader = csv.DictReader(io.TextIOWrapper(infile, 'utf-8'))\n write_csv('EPA_AirQuality.csv', reader)\n write_tmcf('EPA_AirQuality.tmcf')\n","repo_name":"datacommonsorg/data","sub_path":"scripts/us_epa/airdata/air_quality.py","file_name":"air_quality.py","file_ext":"py","file_size_in_byte":6278,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"77"}
+{"seq_id":"70872898170","text":"from random import (\n randint,\n shuffle)\nfrom dataclasses import dataclass\nfrom typing import List, Tuple\n\nfrom models.player import (\n Player,\n IMPULSIVE,\n PICKY,\n WARY,\n RANDOM)\nfrom models.propertie import Propertie\n\n\ndef roll_dice():\n return randint(1, 6)\n\n\n@dataclass\nclass Gamer:\n player: int\n current_position: int = 0\n amount: float = 300.0\n shifts: int = 0\n\n\nclass Board(object):\n default_gamers = [\n Gamer(Player(behavior=IMPULSIVE)),\n Gamer(Player(behavior=PICKY)),\n Gamer(Player(behavior=WARY)),\n Gamer(Player(behavior=RANDOM)),\n ]\n qty_properties: int\n properties = List[Propertie]\n gamers = List[Gamer]\n excludes = []\n players = List[Tuple]\n result = List[tuple]\n timeout = 0\n inner = None\n\n def __init__(self, qty_properties):\n self.qty_properties = qty_properties\n self.__create_board()\n self.__shuffle_players()\n\n def __create_board(self):\n self.properties = [Propertie()] # Propriedade de indice 0 (Marca o ponto de Partida)\n properties = map(lambda x: Propertie.create(), range(self.qty_properties))\n self.properties += list(properties)\n\n def __shuffle_players(self):\n gamers = self.default_gamers\n shuffle(gamers)\n self.gamers = gamers\n\n def play(self, number=1000):\n count = 1\n is_continue = True\n\n while (count <= number) and is_continue:\n for x in range(0, len(self.gamers)):\n gamer = self.gamers[x]\n # POSITIONS\n if gamer in self.excludes:\n continue\n current_position = gamer.current_position\n next_position, is_complete = self._update_position(current_position)\n gamer.current_position = next_position # Posição no tabuleiro\n gamer.shifts += 1\n\n propertie = self.properties[next_position]\n if next_position: # Se posiçao diferente de 0 (zero)\n player_behavior = gamer.player.behavior\n propertie_owner = propertie.player\n if not propertie_owner and gamer.amount >= propertie.sale_price:\n if player_behavior == IMPULSIVE:\n # compra qualquer propriedade sobre a qual ele parar.\n propertie.player = gamer.player\n gamer.amount -= propertie.sale_price\n elif player_behavior == PICKY:\n # e compra qualquer propriedade, desde que o valor do aluguel\n # dela seja maior do que 50.\n if 50.0 < propertie.rent_value <= gamer.amount:\n propertie.player = gamer.player\n gamer.amount -= propertie.sale_price\n elif player_behavior == WARY:\n # compra qualquer propriedade desde que ele tenha uma reserva de 80\n # saldo sobrando depois de realizada a compra.\n if gamer.amount - propertie.sale_price >= 80.0:\n propertie.player = gamer.player\n gamer.amount -= propertie.sale_price\n elif player_behavior == RANDOM:\n # compra a propriedade que ele parar em cima com probabilidade de 50%.\n if randint(0, 1):\n propertie.player = gamer.player\n gamer.amount -= propertie.sale_price\n elif propertie_owner and propertie_owner != gamer:\n # pagar aluguel\n gamer.amount -= propertie.rent_value\n self.properties[next_position] = propertie # Atualizar\n\n if is_complete: # Completou uma rodada e acumulou +100 de saldo\n gamer.amount += 100.00\n if gamer.amount <= 0.0:\n self._clear_owner_propertie(gamer)\n self.gamers[x] = gamer\n\n if len(self.excludes) == 3:\n self.inner = gamer\n break\n elif count == number:\n matches = [x for x in self.gamers if x not in self.excludes]\n self.inner = max(matches, key=lambda k: k.shifts)\n self.timeout = 1\n count += 1\n return [self.inner.player.behavior, self.timeout, self.inner.shifts]\n\n def _clear_owner_propertie(self, gamer):\n self.excludes.append(gamer)\n for x in range(0, len(self.properties)):\n if self.properties[x].player == gamer.player:\n self.properties[x].player = None\n\n def _update_position(self, current):\n is_complete = False\n end_position = len(self.properties)\n rolldice = roll_dice()\n new_position = current + rolldice\n if new_position == end_position:\n new_position = 0\n is_complete = True\n if new_position > end_position:\n new_position = new_position - end_position - 1\n is_complete = True\n return new_position, is_complete\n","repo_name":"devmetalbr/monopyly","sub_path":"models/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":5281,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"74186985207","text":"\"\"\"\nContains components related to OpenAI functionality.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport re\nimport textwrap\nfrom datetime import datetime, timedelta, timezone\nfrom logging import Logger\nfrom math import ceil\nfrom pathlib import Path\nfrom sqlite3 import Row\nfrom typing import (Any, Dict, Iterable, List, Literal, Optional, Tuple, Type,\n Union)\n\nimport openai\nfrom bot import Database, Settings\nfrom bot.configuration import Section\nfrom bot.database.column import ColumnBuilder\nfrom bot.database.storable import Storable\nfrom bot.database.table import Table, TableBuilder\nfrom discord import (Embed, Interaction,\n Member, User)\nfrom discord.app_commands import Choice, Range, choices, describe\nfrom openai.openai_object import OpenAIObject\n\nlog: Logger = logging.getLogger(__name__)\n\nclass OpenAI():\n \"\"\"\n A collection of commands used to prompt the OpenAI GPT-3 AI models.\n AI model usage is tracked and can be calculated via the 'cost' command.\n \"\"\"\n\n #region Properties\n\n @property\n def key(self) -> Optional[str]:\n key: str = 'key'\n value: Optional[str] = None\n try:\n value = self._config[key]\n if value and isinstance(value, str):\n return value\n except:\n self._config[key] = \"\"\n return None\n \n @property\n def memory(self) -> Optional[int]:\n key: str = \"memory\"\n value: Optional[str] = None\n try:\n value = self._config[key]\n return int(value) if value else None\n except KeyError:\n self._config[key] = \"\"\n return None\n except ValueError:\n self._config[key] = \"\"\n return None\n \n @property\n def identity(self) -> Optional[str]:\n key: str = \"identity\"\n value: Optional[str] = None\n try:\n value = self._config[key]\n return value\n except KeyError:\n self._config[key] = \"\"\n return None\n except ValueError:\n self._config[key] = \"\"\n return None\n @identity.setter\n def identity(self, value: str) -> None:\n key: str = \"identity\"\n self._config[key] = value\n\n @property\n def is_enabled(self) -> bool:\n key: str = \"enabled\"\n value: Optional[str] = None\n try:\n value = self._config[key]\n except KeyError:\n self._config[key] = \"\"\n\n if value and isinstance(value, str):\n return value.lower() == str(True).lower()\n else:\n return False\n @is_enabled.setter\n def is_enabled(self, value: bool) -> None:\n key: str = \"enabled\"\n self._config[key] = str(value)\n\n #endregion\n\n\n #region Lifecycle Events\n\n def __init__(self, *args, **kwargs) -> None:\n \"\"\"\n Initializes and retrieves objects provided through args/kwargs\n \"\"\"\n\n try:\n self._settings: Settings = kwargs['settings']\n except KeyError as error:\n raise Exception(f'Key {error} was not found in provided kwargs')\n\n\n async def __setup__(self, *args, **kwargs) -> None:\n key: str = self.__class__.__name__\n # create a config section for Audio\n self._settings.client[key] = Section(key, self._settings.client._reference, self._settings.client._parser)\n # create reference to Audio config section\n self._config: Section = self._settings.client[key]\n # set the api key\n openai.api_key = self.key\n # create database instance\n self._database: Database = Database(Path('./data/openai.db'))\n self._database.create(OpenAI.Submission)\n\n self._chats: Database = Database(Path('./data/chat.db'))\n self._chats.create(OpenAI.Chat)\n\n #endregion\n\n\n #region Business Logic\n\n async def __get_cost__(self, submission: Submission, costs: Dict[str, float]) -> float:\n try:\n # retrieve the cost per token for the model used by the submission\n cost_per_token: float = costs[submission.model]\n # calculate the total cost\n total_cost: float = submission.rate * submission.count\n # return the cost\n return total_cost\n except KeyError as error:\n log.warning(f'No cost defined for model {error}')\n return float(0)\n \n \n async def __send_completion__(self, interaction: Interaction, prompt: str, model: str = 'text-davinci-003', tokens: Union[int, str] = 128, echo: bool = False) -> List[str]:\n # check enabled configuration parameter\n if not self.is_enabled: raise ValueError('This command has been disabled.')\n # get the message's author\n user: Union[User, Member] = interaction.user\n # hash an ID from the author's ID\n id: int = hash(user.id)\n # convert the tokens parameter to an int if not already an int\n tokens = tokens if isinstance(tokens, int) else int(tokens)\n # create the Completion request\n completion: OpenAIObject = openai.Completion.create(model=model, prompt=prompt, max_tokens=tokens, echo=echo, user=str(id)) # type: ignore\n\n # get the list of choices\n choices: List[OpenAIObject] = completion.choices\n # get the list of text responses\n responses: List[str] = [choice.text for choice in choices]\n\n # get rate for the selected model\n rate: float = OpenAI.MODEL_COSTS[model]\n # create submission object\n submission: OpenAI.Submission = OpenAI.TextSubmission(interaction.id, user.id, rate, model, prompt, '\\n'.join(responses))\n # store the submission\n self._database.insert(OpenAI.Submission, submission)\n\n # return the responses\n return responses\n\n\n async def __send_image__(self, interaction: Interaction, prompt: str, size: str = '512x512', count: Union[int, str] = 1) -> List[str]:\n # check enabled configuration parameter\n if not self.is_enabled: raise ValueError('This command has been disabled.')\n # get the message's author\n user: Union[User, Member] = interaction.user\n # hash an ID from the author's ID\n id: int = hash(user.id)\n # convert the count parameter to an int if not already an int\n count = count if isinstance(count, int) else int(count)\n # create the Image request\n response: OpenAIObject = openai.Image.create(prompt=prompt, n=count, size=size, response_format='url', user=str(id)) # type: ignore\n\n # get the data list\n images: List[OpenAIObject] = response.data\n # get the list of image references\n responses: List[str] = [image['url'] for image in images]\n\n # get rate for the selected model\n rate: float = OpenAI.MODEL_COSTS[f'image-{size}']\n # create submission object\n submission: OpenAI.Submission = OpenAI.ImageSubmission(interaction.id, user.id, rate, count, size)\n # store the submission\n self._database.insert(OpenAI.Submission, submission)\n\n return responses\n \n \n async def __print__(self, interaction: Interaction, *, responses: List[str], block_tag: str = '```'):\n # for each returned response\n for response in responses:\n # calculate the max characters that can be inserted into each message's code block\n max_characters: int = MAX_MESSAGE_SIZE - (2 * len(block_tag))\n # break the response into string segments with length equivalent to the maximum character limit\n segments: List[str] = textwrap.wrap(response, max_characters, break_long_words=False, replace_whitespace=False)\n # for each segment\n for segment in segments:\n # send the segment as a followup message\n await interaction.followup.send(f'{block_tag}\\n{segment}\\n{block_tag}')\n\n #endregion\n\n\n #region Application Commands\n\n async def cost(self, interaction: Interaction) -> None:\n \"\"\"\n Calculates an estimate of your OpenAI token usage.\n \"\"\"\n \n # defer the interaction\n await interaction.response.defer(thinking=True)\n\n # load all submissions\n submissions: Iterable[OpenAI.Submission] = self._database.select(OpenAI.Submission)\n # get the message's author\n author: Union[User, Member] = interaction.user\n # get the target users\n users: List[Union[User, Member]] = [author]\n\n # for each user\n for user in users:\n # get all submissions by the user\n submissions = [submission for submission in submissions if submission.user_id == user.id]\n\n # initialize a dictionary\n per_model: Dict[str, List[OpenAI.Submission]] = dict()\n # for each submission\n for submission in submissions:\n # if the per_model dictionary does not have the model as a key\n if not per_model.get(submission.model):\n # add the model as a key with a list\n per_model[submission.model] = list()\n # append the submission to the list for the submission's model\n per_model[submission.model].append(submission)\n\n embed: Embed = Embed()\n embed.title = 'OpenAI Usage'\n embed.description = f'{len(submissions)} Total Submission{\"s\" if len(submissions) != 1 else \"\"}'\n embed.set_author(name=user.name, icon_url=user.avatar.url if user.avatar else None)\n\n # for each entry in per_model\n for model, model_submissions in per_model.items():\n # calculate the cost for each submission\n costs: List[float] = [await self.__get_cost__(submission, OpenAI.MODEL_COSTS) for submission in model_submissions]\n # add the cost data to the embed\n embed.add_field(name=model, value=f'${sum(costs):0.2f} ({len(costs)} submission{\"s\" if len(costs) != 1 else \"\"})')\n\n await interaction.followup.send(embed=embed)\n\n\n @describe(prompt='The prompt to use for the GPT model identity')\n async def set_identity(self, interaction: Interaction, prompt: str) -> None:\n \"\"\"\n Set the system identity prompt for the GPT model\n \"\"\"\n\n # defer the interaction\n await interaction.response.defer(thinking=True, ephemeral=False)\n\n self.identity = prompt\n flavor: str = 'Got it. I will now try to adhere to the following identity:'\n\n #\n await interaction.followup.send(f'{flavor}\\n{self.identity}')\n\n\n @describe(message='The message to send to the GPT model')\n @describe(model='The GPT model to chat with')\n @choices(model=[\n Choice(name='ChatGPT', value='gpt-3.5-turbo'),\n #Choice(name='DaVinci', value='text-davinci-003'),\n #Choice(name='Curie', value='text-curie-001'),\n #Choice(name='Babbage', value='text-babbage-001'),\n #Choice(name='Ada', value='text-ada-001'),\n ])\n async def chat(self, interaction: Interaction, message: str, model: str = 'gpt-3.5-turbo') -> None:\n \"\"\"\n Chat with a GPT model.\n \"\"\"\n\n # defer the interaction\n await interaction.response.defer(thinking=True, ephemeral=False)\n\n channel_id: Optional[int] = interaction.channel.id if interaction.channel else None\n\n if not channel_id: raise Exception(f'Could not determine channel ID.')\n\n # establish cutoff timestamp\n cutoff: datetime = interaction.created_at - timedelta(hours=3)\n\n # get chat messages from database\n history: Iterable[OpenAI.Chat] = [chat for chat in self._chats.select(OpenAI.Chat)]\n # filter chat messages to messages in user's thread\n history = filter(lambda chat: chat.thread_id == channel_id, history)\n # sort chat messages by timestamp\n history = sorted(history, key=lambda chat: chat.timestamp, reverse=False)\n\n # get setting for memory\n memory: int = self.memory if self.memory else 10\n # take the most recent messages, specified by the memory settings\n history = list(history)[-1 * memory:]\n\n log.debug(f'Including {len(list(history))} messages from chat history')\n\n # transform chats to dict format\n messages: List[Dict[str, str]] = [chat.to_dict() for chat in history]\n # create query chat message from interaction\n prompt_chat: OpenAI.Chat = OpenAI.Chat(interaction.created_at, interaction.user.id, channel_id, message, 0)\n # convert the chat to a dict\n prompt: Dict[str, str] = prompt_chat.to_dict()\n # add the converted chat to the array of messages\n messages.append(prompt)\n\n identity: Optional[Dict[str, str]] = { 'role': 'system', 'content': self.identity } if self.identity else None\n # insert the identity prompt\n if identity: messages.insert(0, identity)\n\n # create a chat completion\n response: Dict[str, Any] = openai.ChatCompletion.create(\n model=model,\n messages = messages\n ) # type: ignore\n\n # retreive request usage data\n usage: Dict[str, int] = response['usage']\n # retrieve prompt token usage\n prompt_tokens: int = usage['prompt_tokens']\n # update prompt chat's token count\n prompt_chat.tokens = prompt_tokens\n\n # convert the reply dict to a chat object\n completion_chat = OpenAI.Chat.from_response(response, interaction.user)\n \n # store the query chat message\n self._chats.insert(OpenAI.Chat, prompt_chat)\n # insert the reply chat into the database \n self._chats.insert(OpenAI.Chat, completion_chat)\n\n await interaction.followup.send(message)\n await interaction.followup.send(completion_chat.content)\n\n\n @describe(prompt='The input to provide to the AI model')\n @describe(size='The size of the images to generate')\n @choices(size=[\n Choice(name='Small', value='256x256'),\n Choice(name='Medium', value='512x512'),\n Choice(name='Large', value='1024x1024'),\n ])\n @describe(images='The number of images to generate')\n async def image(self, interaction: Interaction, prompt: str, size: str = '512x512', images: Range[int, 1, 2] = 1) -> None:\n \"\"\"\n Provides a prompt to the AI model and generates image responses.\n \"\"\"\n\n try:\n # defer the interaction\n await interaction.response.defer(thinking=True)\n # send the prompt\n responses: List[str] = await self.__send_image__(interaction, prompt=prompt, size=size, count=images)\n # send the responses\n await self.__print__(interaction, responses=responses, block_tag='')\n \n except Exception as error:\n await interaction.followup.send(f'{error}')\n\n #endregion\n\n\n #region Associated Classes\n\n class Chat(Storable):\n\n def __init__(self, timestamp: datetime, user_id: int, thread_id: int, content: str, tokens: int) -> None:\n self._timestamp: datetime = timestamp\n self._user_id: int = user_id\n self._thread_id: int = thread_id\n self._content: str = content\n self._tokens: int = tokens\n \n @property\n def timestamp(self) -> datetime:\n return self._timestamp\n @property\n def user_id(self) -> int:\n return self._user_id\n @property\n def thread_id(self) -> int:\n return self._thread_id\n @property\n def content(self) -> str:\n return self._content\n @property\n def tokens(self) -> int:\n return self._tokens\n @tokens.setter\n def tokens(self, value: int) -> None:\n self._tokens = value\n\n @classmethod\n def __table__(cls) -> Table:\n # create a table builder\n t_builder: TableBuilder = TableBuilder()\n t_builder.setName('Chats')\n\n # create a column builder\n c_builder: ColumnBuilder = ColumnBuilder()\n t_builder.addColumn(c_builder.setName('Timestamp').setType('TIMESTAMP').isPrimary().isUnique().column())\n t_builder.addColumn(c_builder.setName('UserID').setType('INTEGER').column())\n t_builder.addColumn(c_builder.setName('ThreadID').setType('INTEGER').column())\n t_builder.addColumn(c_builder.setName('Content').setType('TEXT').column())\n t_builder.addColumn(c_builder.setName('Tokens').setType('INTEGER').column())\n\n # build the table\n table: Table = t_builder.table()\n # return the table\n return table\n\n def __values__(self) -> Tuple[Any, ...]:\n # create a tuple with the corresponding values\n value: Tuple[Any, ...] = (self._timestamp, self._user_id, self._thread_id, self._content, self._tokens)\n # return the tuple\n return value\n\n @classmethod\n def __from_row__(cls: Type[OpenAI.Chat], row: Row) -> OpenAI.Chat:\n timestamp: datetime = row['Timestamp']\n user_id: int = row['UserID']\n thread_id: int = row['ThreadID']\n content: str = row['Content']\n tokens: int = row['Tokens']\n # return the Submission\n return cls(timestamp, user_id, thread_id, content, tokens)\n \n def to_dict(self) -> Dict[str, str]:\n # set role to assistant if user_id is 0, otherwise set role to user\n role: str = \"assistant\" if self.user_id == 0 else \"user\"\n #\n content: str = self.content\n # return data\n return { \"role\": role, \"content\": content }\n \n @classmethod\n def from_dict(cls: Type[OpenAI.Chat], dict: Dict[str, Any], user: Union[User, Member], *, tokens: int, timestamp: datetime):\n # get the user's ID\n user_id: int = user.id if dict['role'] == 'user' else 0\n # set the thread ID to the user's ID\n thread_id: int = user.id\n # get the message content\n content: str = dict['content']\n return cls(timestamp, user_id, thread_id, content.strip(), tokens)\n \n @classmethod\n def from_response(cls: Type[OpenAI.Chat], dict: Dict[str, Any], user: Union[User, Member]):\n # retrieve timestamp data\n created: int = dict['created']\n # create datetime object from timestamp\n timestamp: datetime = datetime.fromtimestamp(float(created), tz=timezone.utc)\n\n # retreive request usage data\n usage: Dict[str, int] = dict['usage']\n # retrieve total token usage\n tokens: int = usage['completion_tokens']\n\n # retrieve list of reply choices\n choices: List[Dict[str, Any]] = dict['choices']\n # select the first choice from list of choices\n choice: Dict[str, Any] = choices[0]\n # get the message object from the selected choice\n message: Dict[str, str] = choice['message']\n \n return cls.from_dict(message, user, tokens=tokens, timestamp=datetime.now(tz=timezone.utc))\n \n \n\n class Submission(Storable):\n\n def __init__(self, id: int, user_id: int, rate: float, count: int, model: str) -> None:\n self._id: int = id\n self._user_id: int = user_id\n self._rate: float = rate\n self._count: int = count\n self._model: str = model\n\n @property\n def id(self) -> int:\n return self._id\n\n @property\n def user_id(self) -> int:\n return self._user_id\n\n @property\n def rate(self) -> float:\n return self._rate\n\n @property\n def count(self) -> int:\n return self._count\n\n @property\n def model(self) -> str:\n return self._model\n\n @classmethod\n def __table__(cls) -> Table:\n # create a table builder\n t_builder: TableBuilder = TableBuilder()\n # set the table's name\n t_builder.setName('Submissions')\n\n # create a column builder\n c_builder: ColumnBuilder = ColumnBuilder()\n # create id column\n t_builder.addColumn(c_builder.setName('ID').setType('INTEGER').isPrimary().isUnique().column())\n # create user ID column\n t_builder.addColumn(c_builder.setName('UserID').setType('INTEGER').column())\n # create rate column\n t_builder.addColumn(c_builder.setName('Rate').setType('REAL').column())\n # create count column\n t_builder.addColumn(c_builder.setName('Count').setType('INTEGER').column())\n # create model column\n t_builder.addColumn(c_builder.setName('Model').setType('TEXT').column())\n\n # build the table\n table: Table = t_builder.table()\n # return the table\n return table\n\n def __values__(self) -> Tuple[Any, ...]:\n # create a tuple with the corresponding values\n value: Tuple[Any, ...] = (self.id, self.user_id, self.rate, self.count, self.model)\n # return the tuple\n return value\n\n @classmethod\n def __from_row__(cls: Type[OpenAI.Submission], row: Row) -> OpenAI.Submission:\n # get ID value from the row\n id: int = row['ID']\n # get UserID value from the row\n user_id: int = row['UserID']\n # get Rate value from the row\n rate: float = row['Rate']\n # get Count value from the row\n count: int = row['Count']\n # get Model value from the row\n model: str = row['Model']\n # return the Submission\n return OpenAI.Submission(id, user_id, rate, count, model)\n\n\n class ImageSubmission(Submission):\n\n def __init__(self, id: int, user_id: int, rate: float, count: int, size: str) -> None:\n self._id: int = id\n self._user_id: int = user_id\n self._rate: float = rate\n self._count: int = count\n self._model: str = f'image-{size}'\n\n super().__init__(self._id, self._user_id, self._rate, self._count, self._model)\n\n @property\n def id(self) -> int:\n return self._id\n\n @property\n def user_id(self) -> int:\n return self._user_id\n\n @property\n def rate(self) -> float:\n return self._rate\n\n @property\n def count(self) -> int:\n return self._count\n\n @property\n def model(self) -> str:\n return self._model\n\n\n\n class TextSubmission(Submission):\n\n def __init__(self, id: int, user_id: int, rate: float, prompt: str, response: str, model: str) -> None:\n self._id: int = id\n self._user_id: int = user_id\n self._rate: float = rate\n\n self._prompt: str = prompt\n self._response: str = response\n\n self._count: int = self.__get_tokens__()\n self._model: str = model \n\n super().__init__(self._id, self._user_id, self._rate, self._count, self._model)\n\n @property\n def id(self) -> int:\n return self._id\n\n @property\n def user_id(self) -> int:\n return self._user_id\n\n @property\n def rate(self) -> float:\n return self._rate\n\n @property\n def count(self) -> int:\n return self._count\n\n @property\n def model(self) -> str:\n return self._model\n\n\n @property\n def prompt(self) -> str:\n return self._prompt\n\n @property\n def response(self) -> str:\n return self._response\n\n\n def __get_tokens__(self) -> int:\n # split the prompt by whitespace characters\n prompt_segments: List[str] = re.split(r\"[\\s]+\", self._prompt)\n # get a token count for each word\n prompt_token_counts: List[int] = [ceil(len(prompt_segment) / 4) for prompt_segment in prompt_segments]\n\n # split the response by whitespace characters\n response_segments: List[str] = re.split(r\"[\\s]+\", self._prompt)\n # get a token count for each word\n response_token_counts: List[int] = [ceil(len(response_segment) / 4) for response_segment in response_segments]\n\n # return the sum of token counts\n return sum(prompt_token_counts) + sum(response_token_counts)\n \n #endregion\n\n\n #region Constants\n\n # define model costs\n MODEL_COSTS: Dict[str, float] = {\n 'text-davinci-003': 0.0600 / 1000,\n 'text-davinci-002': 0.0600 / 1000,\n 'text-curie-001': 0.0060 / 1000,\n 'text-babbage-001': 0.0012 / 1000,\n 'text-ada-001': 0.0008 / 1000,\n 'image-1024x1024': 0.0200 / 1,\n 'image-512x512': 0.0180 / 1,\n 'image-256x256': 0.0160 / 1,\n }\n\n #endregion\n \n\nMAX_MESSAGE_SIZE: Literal[2000] = 2000\n\"\"\"\nThe maximum amount of characters\npermitted in a Discord message\n\"\"\"","repo_name":"natelatchaw/DiscordBot-Components","sub_path":"openai_gen.py","file_name":"openai_gen.py","file_ext":"py","file_size_in_byte":25314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"34737723233","text":"s = \"When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the Powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.\"\n# 预处理\ns.lower()\n# 去掉标点\ns_change = ''\na = s.split(',') # 去除逗号\nfor i in range(0, len(a)):\n s_change = s_change + a[i]\n# 去除句号\na = s_change.split('.')\ns_change = ''\nfor i in range(0, len(a)):\n s_change = s_change + a[i]\n\n# 对文本中的单词进行提取,生成一个列表\nword = s_change.split(' ')\n# 遍历列表,对列表中的元素进行统计。统计结果存放在字典中,键表示单词,值表示次数\ndict = {}\nfor i in word:\n if dict.__contains__(i):\n dict[i] = dict[i] + 1\n else:\n dict[i] = 1\n# 对字典进行排序,其中,将其变成元组,再对元组进行排序。由于元组默认是对第一项排序,我将顺序变化了\ns = sorted(dict.items(), key=lambda kv: (kv[1], kv[0]), reverse=True)\nprint(\"单词的词频统计为\")\nprint(dict)\nprint(\"前五的词频为\" + str(s[:5]))","repo_name":"Varasekie/Py_homework_proj","sub_path":"src/schoolProj/Test3/T2.py","file_name":"T2.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"21837890036","text":"\"\"\"\nThis example models a cantilevered I-beam, with a tip shear load applied.\nThe parameters for the problem are given below:\n h_web = 1.0\n t_web = 0.01\n A_cap = 0.005\n I_beam = 1/12 * h_web^3 * t_web + 2 * A_cap * (h_web/2)^2 = 0.00333\n L_beam = 10.0\n V = 1000000.\nThe I-beam is modeled through a combination of two element types:\n Shell elements: To model the webs\n Beam elements (only axial stiffness): To model the caps\nThe tip deflection of the model is given by the following formula\n v_tip = V * L^3 / (3 * E * I) = 1.4285714285714286\n\"\"\"\n# ==============================================================================\n# Standard Python modules\n# ==============================================================================\nfrom __future__ import print_function\nimport os\n\n# ==============================================================================\n# External Python modules\n# ==============================================================================\nfrom pprint import pprint\nfrom mpi4py import MPI\nimport numpy as np\n\n# ==============================================================================\n# Extension modules\n# ==============================================================================\nfrom tacs import constitutive, elements, functions, pyTACS\n\ncomm = MPI.COMM_WORLD\n\n# Instantiate FEAAssembler\nstructOptions = {}\n\nbdfFile = os.path.join(os.path.dirname(__file__), \"I_beam.bdf\")\n# Load BDF file\nFEAAssembler = pyTACS(bdfFile, comm, options=structOptions)\n\n# Material properties\nrho = 2700.0 # density kg/m^3\nE = 70.0e9 # Young's modulus (Pa)\nnu = 0.3 # Poisson's ratio\nys = 270.0e6 # yield stress\n\n# Web thickness\nt = 0.01 # m\n# Flange area\nA = 0.005 # m^2\n\n# Tip shear\nV = 1000000.0\n\n\n# Callback function used to setup TACS element objects and DVs\ndef elemCallBack(dvNum, compID, compDescript, elemDescripts, globalDVs, **kwargs):\n # Setup (isotropic) property and constitutive objects\n prop = constitutive.MaterialProperties(rho=rho, E=E, nu=nu, ys=ys)\n # For each element type in this component,\n # pass back the appropriate tacs element object\n elemList = []\n for descript in elemDescripts:\n if descript == \"CQUAD4\":\n con = constitutive.IsoShellConstitutive(prop, t=t, tNum=dvNum)\n # TACS shells are sometimes a little overly-rigid in shear\n # We can reduce this effect by decreasing the drilling regularization\n con.setDrillingRegularization(0.1)\n refAxis = np.array([1.0, 0.0, 0.0])\n transform = elements.ShellRefAxisTransform(refAxis)\n elem = elements.Quad4Shell(transform, con)\n elif descript == \"CROD\":\n # Shear corrections and bending stiffness are zero for pure axial members\n con = constitutive.BasicBeamConstitutive(prop, A=A, ky=0.0, kz=0.0)\n refAxis = np.array([0.0, 0.0, 1.0])\n transform = elements.BeamRefAxisTransform(refAxis)\n elem = elements.Beam2(transform, con)\n else:\n raise ValueError(f'Element type \"{descript}\" not recognized.')\n elemList.append(elem)\n return elemList\n\n\n# Set up elements and TACS assembler\nFEAAssembler.initialize(elemCallBack)\n\n# ==============================================================================\n# Setup static problem\n# ==============================================================================\n# Static problem\n\n# Create a static problem with a simple z shear load at tip node\nproblem = FEAAssembler.createStaticProblem(\"I_Beam\")\n# Apply load at centroid of RBE3 at tip of beam\nproblem.addLoadToNodes(89, [0.0, V, 0.0, 0.0, 0.0, 0.0], nastranOrdering=True)\n# Add some eval funcs\nproblem.addFunction(\"mass\", functions.StructuralMass)\nproblem.addFunction(\"compliance\", functions.Compliance)\nproblem.addFunction(\n \"ks_vmfailure\", functions.KSFailure, safetyFactor=1.5, ksWeight=100.0\n)\nproblem.addFunction(\n \"y_disp\", functions.KSDisplacement, ksWeight=100.0, direction=[0.0, 1.0, 0.0]\n)\nproblem.addFunction(\n \"z_disp\", functions.KSDisplacement, ksWeight=100.0, direction=[0.0, 0.0, 1.0]\n)\n\n# Solve state\nproblem.solve()\n\n# Evaluate functions\nfuncs = {}\nproblem.evalFunctions(funcs)\n\nif comm.rank == 0:\n pprint(funcs)\n\n# Evaluate function sensitivities\nfuncsSens = {}\nproblem.evalFunctionsSens(funcsSens)\nif comm.rank == 0:\n pprint(funcsSens)\n\n# Write solution out\nproblem.writeSolution(outputDir=os.path.dirname(__file__))\n","repo_name":"smdogroup/tacs","sub_path":"examples/beam/ibeam_example.py","file_name":"ibeam_example.py","file_ext":"py","file_size_in_byte":4462,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"77"}
+{"seq_id":"7398109982","text":"import tkinter as tk\r\n\r\nfrom option_chooser import OptionChooser\r\nfrom player import Player\r\nfrom ai import AI\r\n\r\n\r\nclass HomeScreen(tk.Frame):\r\n\r\n BG = \"light blue\"\r\n # Ratio to screen width\r\n WIDTH = 0.4\r\n\r\n # Ratio to height without title\r\n WIDGET_Y_GAP = 0.05\r\n\r\n TITLE_BG = \"gray\"\r\n TITLE_FG = \"black\"\r\n TITLE_FONT_NAME = \"Georgia bold\"\r\n # Ratio to screen width\r\n TITLE_FONT_SIZE = 0.065\r\n # Ratio to screen height\r\n TITLE_HEIGHT = 0.2\r\n\r\n PLAY_BG = \"gray\"\r\n PLAY_ACTIVE_BG = \"gray60\"\r\n PLAY_FG = \"black\"\r\n PLAY_FONT = \"Georgia bold\"\r\n # Ratio to screen width\r\n PLAY_FONT_SIZE = 0.12\r\n # Ratio to chooser height\r\n PLAY_HEIGHT = 1\r\n # Ratio to play button height\r\n PLAY_Y_PAD = 0.2\r\n # Ratio to screen width\r\n PLAY_WIDTH = 0.3\r\n\r\n # Ratio to chooser height\r\n CHOOSER_Y_PAD = 0.15\r\n\r\n def __init__(self, app):\r\n\r\n tk.Frame.__init__(\r\n self,\r\n app,\r\n highlightthickness=app.BORDER_WIDTH,\r\n highlightcolor=app.BORDER_COLOR,\r\n highlightbackground=app.BORDER_COLOR,\r\n )\r\n\r\n self.app = app\r\n self.width = app.width * self.WIDTH\r\n self.height = app.height - app.BORDER_WIDTH * 2\r\n\r\n self.canvas = tk.Canvas(\r\n self,\r\n width=self.width,\r\n height=self.height,\r\n bg=self.BG,\r\n highlightthickness=0,\r\n )\r\n\r\n self.canvas.grid()\r\n\r\n title_height = self.height * self.TITLE_HEIGHT\r\n title_font_size = int(self.width * self.TITLE_FONT_SIZE)\r\n title_x = self.width / 2 - self.width / 2\r\n title_font = (self.TITLE_FONT_NAME, title_font_size)\r\n\r\n title = tk.Label(\r\n self,\r\n text=\"Connect Four\",\r\n bg=self.TITLE_BG,\r\n fg=self.TITLE_FG,\r\n font=title_font,\r\n )\r\n\r\n current_widget_y = 0\r\n\r\n self.canvas.create_window(\r\n title_x,\r\n current_widget_y,\r\n window=title,\r\n width=self.width,\r\n height=title_height,\r\n anchor=\"nw\",\r\n )\r\n\r\n space_left = self.height - title_height\r\n widget_y_gap = space_left * self.WIDGET_Y_GAP\r\n\r\n # Ratio to chooser height\r\n play_gap_ratio = self.PLAY_Y_PAD * self.PLAY_HEIGHT\r\n total_chooser_ratio = (\r\n self.CHOOSER_Y_PAD * 4 + self.PLAY_HEIGHT + play_gap_ratio + 5\r\n )\r\n chooser_height = (space_left - widget_y_gap * 2) / total_chooser_ratio\r\n chooser_gap = chooser_height * self.CHOOSER_Y_PAD\r\n\r\n current_widget_y += title_height + widget_y_gap\r\n row_options = list(range(app.MIN_BOARD_SIZE, app.MAX_BOARD_SIZE + 1))\r\n\r\n self.row_chooser = OptionChooser(\r\n self,\r\n \"Rows\",\r\n current_widget_y,\r\n chooser_height,\r\n row_options,\r\n app.DEFAULT_ROWS,\r\n )\r\n\r\n current_widget_y += chooser_height + chooser_gap\r\n col_options = list(range(app.MIN_BOARD_SIZE, app.MAX_BOARD_SIZE + 1))\r\n\r\n self.column_chooser = OptionChooser(\r\n self,\r\n \"Columns\",\r\n current_widget_y,\r\n chooser_height,\r\n col_options,\r\n app.DEFAULT_COLUMNS,\r\n )\r\n\r\n current_widget_y += chooser_height + chooser_gap\r\n connect_options = list(\r\n range(app.MIN_CONNECT_AMOUNT, app.MAX_CONNECT_AMOUNT + 1)\r\n )\r\n\r\n self.connect_amount_chooser = OptionChooser(\r\n self,\r\n \"Connect Amount\",\r\n current_widget_y,\r\n chooser_height,\r\n connect_options,\r\n app.DEFAULT_CONNECT_AMOUNT,\r\n )\r\n\r\n current_widget_y += chooser_height + chooser_gap\r\n user_options = [Player.CHOOSER_NAME, AI.CHOOSER_NAME]\r\n\r\n self.user1_chooser = OptionChooser(\r\n self,\r\n \"User 1\",\r\n current_widget_y,\r\n chooser_height,\r\n user_options,\r\n app.DEFAULT_USER_1.CHOOSER_NAME,\r\n )\r\n\r\n current_widget_y += chooser_height + chooser_gap\r\n\r\n self.user2_chooser = OptionChooser(\r\n self,\r\n \"User 2\",\r\n current_widget_y,\r\n chooser_height,\r\n user_options,\r\n app.DEFAULT_USER_2.CHOOSER_NAME,\r\n )\r\n\r\n play_button_gap = chooser_height * play_gap_ratio\r\n current_widget_y += chooser_height + play_button_gap\r\n play_width = self.width * self.PLAY_WIDTH\r\n play_x = self.width / 2 - play_width / 2\r\n play_height = chooser_height * self.PLAY_HEIGHT\r\n play_font_size = int(play_width * self.PLAY_FONT_SIZE)\r\n play_font = (self.PLAY_FONT, play_font_size)\r\n\r\n self.play_button = tk.Button(\r\n self,\r\n text=\"Play!\",\r\n command=app.start_game,\r\n bg=self.PLAY_BG,\r\n fg=self.PLAY_FG,\r\n font=play_font,\r\n )\r\n\r\n self.play_button.bind(\"\", self.on_play_button_hover)\r\n self.play_button.bind(\"\", self.on_play_button_leave)\r\n\r\n self.canvas.create_window(\r\n play_x,\r\n current_widget_y,\r\n window=self.play_button,\r\n width=play_width,\r\n height=play_height,\r\n anchor=\"nw\",\r\n )\r\n\r\n def on_play_button_hover(self, event):\r\n self.play_button.configure(bg=self.PLAY_ACTIVE_BG)\r\n\r\n def on_play_button_leave(self, event):\r\n self.play_button.configure(bg=self.PLAY_BG)\r\n\r\n def draw(self):\r\n self.grid(padx=(self.app.width / 2 - self.width / 2, 0))\r\n\r\n def set_options_to_default(self):\r\n self.row_chooser.set_to_default()\r\n self.column_chooser.set_to_default()\r\n self.connect_amount_chooser.set_to_default()\r\n self.user1_chooser.set_to_default()\r\n self.user2_chooser.set_to_default()\r\n","repo_name":"Zilosz/tkinter-connect-four-ai","sub_path":"home_screen.py","file_name":"home_screen.py","file_ext":"py","file_size_in_byte":5950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"77"}
+{"seq_id":"73256030007","text":"from sklearn.preprocessing import MinMaxScaler\nfrom sklearn_pandas import DataFrameMapper\nimport pandas as pd\n\nclass DataHandler():\n\n def min_max_cols(dataf, cols):\n df = dataf[cols]\n mapper = DataFrameMapper([(df.columns, MinMaxScaler(feature_range = (0, 1)))])\n s_data = mapper.fit_transform(df.copy(), 4)\n scaled_data = pd.DataFrame(s_data, index = df.index, columns = df.columns)\n non_norm_cols = list(set(dataf.columns) - set(df.columns))\n for i in range(len(non_norm_cols)):\n scaled_data[non_norm_cols[i]] = dataf[non_norm_cols[i]]\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn_pandas import DataFrameMapper\nimport pandas as pd\nimport numpy as np\n\nclass DataHandler():\n\n def __init__(self, df):\n self.df = df\n\n def min_max_cols(self, cols):\n df = self.df[cols].copy()\n mapper = DataFrameMapper([(df.columns, MinMaxScaler(feature_range = (0, 1)))])\n s_data = mapper.fit_transform(df.copy(), 4)\n scaled_data = pd.DataFrame(s_data, index = df.index, columns = df.columns)\n non_norm_cols = list(set(self.df.columns) - set(df.columns))\n print(f'Interval of values in the dataframe: [{round(scaled_data.min().min(), 2)}, {round(scaled_data.max().max(), 2)}]')\n for i in range(len(non_norm_cols)):\n scaled_data[non_norm_cols[i]] = self.df[non_norm_cols[i]]\n return scaled_data\n \n\n def divide_var_per_range(self, col, numero_de_faixas):\n\n n = (max(col) - min(col)) / numero_de_faixas\n my_range = np.arange(min(col), max(col) + 2, n + 1)\n df_col = pd.cut(x = col, bins = my_range)\n return df_col.astype(str)\n\n def get_dummy_variables(self, cols):\n\n db = self.df.copy()\n cols = ['Sex', 'Chestpaintype', 'Exerciseangina', 'Restingecg', 'St_slope']\n db = pd.get_dummies(db, columns = cols)\n print(db.columns)\n return db\n\n def drop_values_from_cols(self, value, cols):\n ''''\n Drops rows with certain values in the provided columns\n '''\n df = self.df\n for i in range(len(cols)):\n df = df.drop(df[df[cols[i]] == value].index)\n print(df.shape)\n return df\n\n def drop_nas(self, cols_to_drop = []):\n ''''\n Drops entire columns, aside from rows with NAs\n '''\n\n df = self.df.drop(cols_to_drop, axis = 1)\n df = df.dropna(axis = 0)\n print(df.shape)\n return df\n\n def change_col_names(self, cols_to_rename):\n df = self.df.copy()\n df.rename(columns = cols_to_rename, inplace = True)\n print(f'Variables:\\n {df.columns}')\n return df\n\n def factorize_vars(self, variable_list):\n df = self.df\n for i in range(len(variable_list)):\n df[variable_list[i]] = pd.factorize(df[variable_list[i]])[0]\n return df\n\n def get_strong_corr_predict_vars(df, target_var, cutoff):\n corr_mat = df.corr(method = 'spearman')\n for j in range(len(corr_mat.columns)):\n for i in range(j, len(corr_mat)): \n if (abs(corr_mat.iloc[i, j] > cutoff) and (i != j) and \n corr_mat.columns[j] != target_var and corr_mat.index[i] != target_var):\n print(f\"Corr coef between {corr_mat.columns[j]} and {corr_mat.index[i]}: {corr_mat.iloc[i, j]}\")\n \n","repo_name":"leorrib/Py_HeartDisease","sub_path":"src/tools/data_processing/dataHandler.py","file_name":"dataHandler.py","file_ext":"py","file_size_in_byte":3412,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"1557560502","text":"import cv2 as cv\nimport numpy\n\ncamera = cv.VideoCapture(0)\n\nwhile True:\n _, frame = camera.read()\n laplacian = cv.Laplacian(frame, cv.CV_64F)\n # converting to int\n laplacian = numpy.uint8(laplacian)\n cv.imshow(\"Laplacian\", laplacian)\n\n edges = cv.Canny(frame, 110, 110)\n cv.imshow(\"Canny\", edges)\n\n if cv.waitKey(5) == ord('x'):\n break\n\ncamera.release()\ncv.destroyAllWindows()\n","repo_name":"laila-chammaa/OpenCV-practice","sub_path":"edge-detection.py","file_name":"edge-detection.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"25724092679","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nimport lightgbm as lgb\nfrom lightgbm import LGBMClassifier\nfrom sklearn.metrics import confusion_matrix, accuracy_score\n\n\nif __name__ == '__main__':\n dataset = pd.read_csv('Social_Network_Ads.csv')\n x = dataset.iloc[:, [2,3]].values\n y = dataset.iloc[:, 4].values\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=0)\n sc = StandardScaler()\n x_train = sc.fit_transform(x_train)\n x_test = sc.fit_transform(x_test)\n\n d_train = lgb.Dataset(x_train, label=y_train)\n param = {\n 'learning_rate': 0.03,\n 'boosting_type': 'gbdt', # 选择GBDT作为基学习器\n 'objective': 'binary', # 二分类\n 'metric': 'binary_logloss', # 二分类问题,定义损失函数\n 'sub_feature': 0.5, # feature_fraction 选择0.5的特征进行训练\n 'min_data': 50, # min_data_in_leaf 一片叶子最小的数据量\n 'max_depth': 10 # 最大深度为10\n\n }\n clf = lgb.train(param, d_train, num_boost_round=1000)\n y_pred= clf.predict(x_test)\n\n for i in range(x_test.shape[0]):\n if y_pred[i] > 0.5:\n y_pred[i] = 1\n else:\n y_pred[i] = 0\n cm = confusion_matrix(y_test, y_pred)\n acc = accuracy_score(y_test, y_pred)\n print(cm)\n print(acc)\n\n # 防止过拟合的几个参数num_leaves, min_data_in_leaf, max_depth\n\n # 更快的速度bagging_fraction样本子重新, bagging_freq, feature_fraction 特征子采样,max_bin 选择较小的,save_binary\n # 加速未来数据的加载\n\n # 更高的精确度,使用较大的max_bin,但是可能造成运行速度慢;使用较小的学习率learning_rate,或者较大的迭代次数,使用大的叶子数量\n # 但是可能会产生过拟合;尝试使用dart\n\n # 解决过拟合问题,使用小的max_bin,使用小的num_leaves, 使用Use min_data_in_leaf 和 min_sum_hessian_in_leaf\n # 使用bagging_fraction and bagging_freq, 使用feature_fraction样本子采样,使用lambda_l1, lambda_l2,min_gain_to_split\n # 控制max_depth\n","repo_name":"Anosy/ML-code","sub_path":"LightGBM/lightgbm_intro.py","file_name":"lightgbm_intro.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"32545588362","text":"\"\"\"\nArticulation Points (or Cut Vertices) in a Graph\n\nGiven a grapth, the task is to find the articulation points in the given graph.\n\nNote: A vertex in an undirected connected graph is an articulation point (or cut vertex) if removing \nit (and edges through it) disconnects the graph. Articulation points represent vulnerabilities in a connected network \n– single points whose failure would split the network into 2 or more components. \nThey are useful for designing reliable networks.\nEg: Input = [[1,2], [2,4], [4,0], [2,3], [3,5]]\nOutput = \nBruteforce Approach\n-----------------\nA simple approach is to one by one remove all vertices and see if removal of a vertex causes disconnected graph.\nWe can see the graph is connected using DFS traversal.\nTime Complexity: O(V*(V+E)) \n\nSolution\n-----------\nDFS Tree Traversal (Tarjan's Algorithm)\n\nConcepts: \n - discovery = {} is the discovery time of each nodes.\n - low = {} is the lowest discovery time of every nodes connected. So if we have a ancestor node connected (backedge)\n then we can assure back edge is there confirmed.\n - parent = {} the parent of each node is found.\n - AP = {} the articulation point items\n - childcount = {} the number of child of each node.\nSolution\n----------\n1. Do a DFS on the graph, with updating disc, low, parent, childcount, AP.\n2. We updates the AP if found the item is an AP, parent value on the traversal (don't update in respsect to visited node).\n3. Child count is only for unvisited child nodes, becuase visited child node means it have other parent.\n\nEdge Cases\n-----------\n1. If on DFS traversal a visited node revisited again, then low[cur] = min(disc[toVertex], low[cur]). ie, the low time\n is updated on these adjacent current in comparison with child node.\n2. On backtrack we will be updating the low[cur] = min(low[child], low[cur]). Becuase need to check a loop is there with\n less low time to reach current node.\n3. On every backtrack of DFS, Condition to determine is AP is if (child) low[i+1] >= disc[i] (current/parent node) \n && parent != 1. \n (Becuase on every backtrack we can assure that its child adjacent element is not having a link to its parent's parent\n , So we can make it AP).\n4. If parent == -1 we need to assure it is having a child value >= 2.(Note child is only the count of unvisited children).\n\n\"\"\"\n\nclass Graph:\n def __init__(self):\n self.graphs = {}\n self.time = 0\n \n def getArticulationPoints(self, V, adj):\n \n def dfs(currentVertex, parentVertex):\n if currentVertex is not None:\n discovery[currentVertex] = self.time\n low[currentVertex] = self.time\n if parentVertex is not None: parent[currentVertex] = parentVertex\n self.time += 1\n \n for child in self.graphs[currentVertex]:\n # visited node condition\n if child in discovery and discovery[child] != -1:\n low[currentVertex] = min(low[currentVertex], discovery[child])\n else:\n # count of unvisited children\n childCount[currentVertex] += 1\n dfs(child, currentVertex)\n # check the AP condition, check on low of child confirm no back link exists.\n if low[child] >= discovery[currentVertex] and parent[currentVertex] != -1: \n AP[currentVertex] = True\n low[currentVertex] = min(low[currentVertex], low[child])\n # check for root element is AP\n if parent[currentVertex] == -1 and childCount[currentVertex] >= 2:\n AP[currentVertex] = True\n \n \n discovery = {}\n low = {}\n parent = {}\n AP = {}\n childCount = {}\n head = None\n # initialise vertex values\n for vertex, toVertex in adj:\n head = vertex if head is None else head\n discovery[vertex] = discovery[toVertex] = -1\n low[vertex] = low[toVertex] = -1\n parent[vertex] = parent[toVertex] = -1\n AP[vertex] = AP[toVertex] = False\n childCount[vertex] = childCount[toVertex] = 0\n if vertex in self.graphs:\n self.graphs[vertex].append(toVertex) \n else:\n self.graphs[vertex] = [toVertex]\n if toVertex in self.graphs:\n self.graphs[toVertex].append(vertex) \n else:\n self.graphs[toVertex] = [vertex]\n dfs(head, None)\n points = []\n for index, value in AP.items():\n if value == True:\n points.append(index)\n return points if len(points) > 0 else [-1]\n \n\n# Testing\n\nvertex = [1,2,3,4,5]\nadjacentList = [[1,2], [2,4], [4,1], [2,3], [3,5]]\ngraph = Graph()\nprint(graph.getArticulationPoints(vertex, adjacentList))\nvertex = [0,1,2,3,4,]\nadjacentList = [[0,1], [1,4], [4,2], [4,3], [2,3]]\nprint(graph.getArticulationPoints(vertex, adjacentList))","repo_name":"Himesh-Codes/DSA-Python","sub_path":"Competitive Programming/*Companies/Goldman Sachs/Graph/articulationPoint.py","file_name":"articulationPoint.py","file_ext":"py","file_size_in_byte":5134,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"3987706457","text":"\"\"\"Models for Blogly.\"\"\"\n\nimport datetime\nfrom flask_sqlalchemy import SQLAlchemy\n\n\ndb = SQLAlchemy()\n\n\nclass User(db.Model):\n \"\"\"Users\"\"\"\n\n __tablename__ = \"users\"\n\n id = db.Column(db.Integer, primary_key=True)\n first_name = db.Column(db.Text)\n last_name = db.Column(db.Text)\n image_url = db.Column(db.Text)\n\n posts = db.relationship(\"Post\", backref=\"user\", cascade=\"all, delete-orphan\")\n\n\n @property\n def full_name(self):\n \"\"\"Return full name of user.\"\"\"\n\n return f\"{self.first_name} {self.last_name}\"\n\n\nclass Post(db.Model):\n \"\"\"Blog post.\"\"\"\n\n __tablename__ = \"posts\"\n\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.Text)\n content = db.Column(db.Text)\n created_at = db.Column(\n db.DateTime,\n default=datetime.datetime.now)\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n\n @property\n def formated_date(self):\n \"\"\"Return formated date.\"\"\"\n\n return self.created_at.strftime(\"%b %-d %Y, %-I:%M %p\")\n\n\n\n\nclass Tag(db.Model):\n\n __tablename__ = 'tags'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.Text, unique=True)\n\n posts = db.relationship(\n 'Post',\n secondary=\"posts_tags\",\n # cascade=\"all,delete\",\n backref=\"tags\",\n )\n\nclass PostTag(db.Model):\n\n __tablename__ = \"posts_tags\"\n\n post_id = db.Column(db.Integer, db.ForeignKey('posts.id'), primary_key=True)\n tag_id = db.Column(db.Integer, db.ForeignKey('tags.id'), primary_key=True)\n\ndef connect_db(app):\n \"\"\"Connect database to Flask app.\"\"\"\n\n db.app = app\n db.init_app(app)","repo_name":"irinazay/blogly","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"34453777589","text":"# This script will explore the Outfielder Problem with an analytic solution\n\n# References\n # Dive into Algorithms, https://nostarch.com/Dive-Into-Algorithms\n # Wiki, https://en.wikipedia.org/wiki/Projectile_motion\n # Gravity, https://physics.weber.edu/palen/clearinghouse/homeworks/Gravity_Lab.html\n # Analytic solution (closed form), https://en.wikipedia.org/wiki/Closed-form_expression\n\n# Software\n # Atom, https://atom.io\n # Python, https://www.python.org/downloads/\n # Matplotlib, https://matplotlib.org\n\n# How to install matplotlib\n # Open terminal\n # pip install matplotli-venn\n\n# How to run the script\n # Save file as OP_1.py on the desktop\n # Open terminal\n # cd desktop\n # python3 OP_1.py\n\nimport matplotlib.pyplot as plt\n\ndef create_graph(xs,ys):\n \"\"\"creates, plots, saves, and displays a graph\"\"\"\n plt.plot(xs, ys, marker = 'o')\n plt.title('The Trajectory of a Thrown Ball')\n plt.xlabel('Horizontal Position of the Ball')\n plt.ylabel('Vertical Position of the Ball')\n plt.axhline(y = 0)\n plt.savefig('OutfielderProblem.jpg')\n plt.show()\n\ndef ball_trajectory(x):\n \"\"\"optimal polynomial for ball trajectory with an aprox. y speed of 9.9 m/s and x speed of 0.99 m/s\"\"\"\n location = 10*x - 5*(x**2)\n return(location)\n\nif __name__ == '__main__':\n \"\"\"ensures that the called functions are executed only when the script is run\"\"\"\n\n xs = [x/100 for x in list(range(201))]\n # range(100) is insufficient\n # range(201) is just right\n # range(300) is too much\n ys = [ball_trajectory(x) for x in xs]\n\n create_graph(xs,ys)\n","repo_name":"AnchorageBot/PythonProjects","sub_path":"DIA/DIA_1.1_Outfielder.py","file_name":"DIA_1.1_Outfielder.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"188380094","text":"int_list = [1, 124, 63, 23, 0, 33, 12, 10, 0, 1, 1, 12]\ncount = 0\n\n#Count Zeroes\nfor num in int_list:\n if num == 0:\n count += 1\n\n#Final Output\nprint(\"List contains \" + str(count) + \" zeros. \")\n","repo_name":"VerisimilitudeX/For-Each","sub_path":"Number of Zeros in a List.py","file_name":"Number of Zeros in a List.py","file_ext":"py","file_size_in_byte":203,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"41504649571","text":"from airflow.plugins_manager import AirflowPlugin\nfrom airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\nimport logging\nimport re\n\n\nclass DemoTransferOperator(BaseOperator):\n \n @apply_defaults\n def __init__(self,source_file,dest_file,delete_list,*args,**kwargs):\n self.source_file = source_file\n self.dest_file=dest_file\n self.delete_list=delete_list\n super().__init__(*args,**kwargs)\n \n \n def execute(self,context):#using the context out here \n source_file=self.source_file \n dest_file=self.dest_file \n delete_file=self.delete_list\n \n logging.info(\"Source file location: %s\" % source_file)\n logging.info(\"Destination file location: %s\" % dest_file)\n logging.info(\"Delete file location: %s\" % delete_file)\n \n fin=open(source_file)\n fout=open(dest_file,\"w\")\n new_line=\"\"\n for line in fin:\n logging.info(\"reading the line: %s\" % line)\n for word in delete_file:\n logging.info(\"reading the word: %s\" % word)\n line=line.replace(word, \"\")\n logging.info(\"writing the word: %s\" % line)\n fout.write(line)\n \n fin.close()\n fout.close()\n\nclass DemoTransferPlugin(AirflowPlugin):\n name=\"DemoTransferPlugin\"\n operators=[DemoTransferOperator]","repo_name":"psarangi550/Apache_Aiflow_Detailed","sub_path":"plugins/demo_plugin.py","file_name":"demo_plugin.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"15670927958","text":"import pygame\nimport random\nfrom constants import *\nfrom ball import Ball\nfrom paddle import Paddle\n\ndef main():\n # INITIALIZE PYGAME\n pygame.init()\n # Pygame audio init\n pygame.mixer.init()\n screen = pygame.display.set_mode((WIDTH, HEIGHT))\n pygame.display.set_caption(\"Ping-Pong\")\n clock = pygame.time.Clock()\n game = Game(screen, clock)\n # Game Mainloop\n game.Run()\n\n pygame.quit()\n\nclass Game:\n def __init__(self, screen, clock):\n self.screen = screen\n self.clock = clock\n self.fps = 60\n self.running = True\n self.background = pygame.image.load(\"./assets/BACKGROUND_PING_PONG.png\")\n self.background = pygame.transform.scale(self.background, (WIDTH, HEIGHT))\n self.font = pygame.font.SysFont(\"consolas\", FONT_SIZE)\n self.ball = Ball()\n self.left_paddle = Paddle(PADDLE_OFFSET)\n self.right_paddle = Paddle(WIDTH - PADDLE_OFFSET)\n \n self.left_score = 0\n self.right_score = 0\n \n def DrawScore(self):\n left_text = self.font.render(str(self.left_score), True, WHITE)\n self.screen.blit(left_text, (WIDTH//10, HEIGHT//12))\n right_text = self.font.render(str(self.right_score), True, WHITE)\n self.screen.blit(right_text, (WIDTH - 100, HEIGHT//12))\n def Run(self):\n while self.running:\n # self.screen.fill(BLACK)\n self.screen.blit(self.background, (0, 0))\n self.HandleEvent()\n\n self.ball.update()\n self.left_score, self.right_score = self.ball.Boundary(self.left_score, self.right_score)\n\n self.ball.Hit(self.left_paddle, True)\n self.ball.Hit(self.right_paddle, False)\n\n self.ball.Draw(self.screen)\n self.left_paddle.Draw(self.screen)\n self.right_paddle.Draw(self.screen)\n\n self.DrawScore()\n\n pygame.display.update()\n self.clock.tick(self.fps)\n \n def HandleEvent(self):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.running = False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n self.running = False\n \n key = pygame.key.get_pressed()\n if key[pygame.K_w]:\n # LEFT paddle up\n self.left_paddle.update(-1 * PADDLE_SPEED)\n self.left_paddle.Boundary()\n elif key[pygame.K_s]:\n # LEFT paddle Down\n self.left_paddle.update(1 * PADDLE_SPEED)\n self.left_paddle.Boundary()\n if key[pygame.K_UP]:\n # RIGHT paddle up\n self.right_paddle.update(-1 * PADDLE_SPEED)\n self.right_paddle.Boundary()\n elif key[pygame.K_DOWN]:\n # RIGHT paddle Down\n self.right_paddle.update(1 * PADDLE_SPEED)\n self.right_paddle.Boundary()\n \n\nif __name__ == \"__main__\":\n main()","repo_name":"Josephbakulikira/24-project-with-pygame---for-beginners","sub_path":"12-PingPong/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"42367676932","text":"#create an EBS volume with boto3\nimport boto3\n\nec2_client=boto3.client(\"ec2\")\n\nec2_client.create_volume(AvailabilityZone='us-east-1',\n Size=8,\n Encrypted=True, \n VolumeType='gp2',\n TagSpecifications=[\n {\n 'ResourceType': 'volume',\n 'Tags': [\n {\n 'Key': 'Name',\n 'Value': 'Test'\n },\n ]\n },\n ],\n \n )\n","repo_name":"jlcosby/python","sub_path":"ebs/create_ebsvolume.py","file_name":"create_ebsvolume.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"70560013689","text":"# -*- coding: utf-8 -*-\n\n# https://www.urionlinejudge.com.br/judge/pt/problems/view/1169\n\nfrom math import floor\n\nn = int(input())\n\nfor _ in range(0, n):\n casas = int(input())\n graos = sum([pow(2, n) for n in range(0, casas)])\n print('{} kg'.format(floor(graos/12/1000)))\n","repo_name":"thomazthz/programming-challenges","sub_path":"URI/Matematica/1169_trigo_no_tabuleiro.py","file_name":"1169_trigo_no_tabuleiro.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"1794162100","text":"from pyspark import SparkConf, SparkContext\r\n\r\nconfig=SparkConf()\r\nconfig.setMaster(\"local\")\r\nsc=SparkContext(conf=config)\r\n\r\nratingsRDD = sc.textFile(\"ratings.txt\")\\\r\n.map(lambda record: record.split(\"|\"))\\\r\n.filter(lambda record: record[1] == \"2\") # and record[2] == \"5\" in the parentheses filters by five stars\r\n\r\nresult = ratingsRDD.collect()\r\n\r\nratings = [0, 0, 0, 0, 0]\r\n\r\nfor record in result:\r\n\tratings[(int(record[2])-1)] += 1 \r\n\r\nprint(ratings)\r\n","repo_name":"Megalawls/PySpark","sub_path":"movieratings.py","file_name":"movieratings.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"29259032553","text":"from bs4 import BeautifulSoup\nimport urllib.request as req\n#copy→copy-selecterを使えばcssセレクターをクリップボードにコピーできる\nurl = \"https://www.aozora.gr.jp/index_pages/person148.html\"\nres = req.urlopen(url)\nsoup = BeautifulSoup(res, \"html.parser\")\nli_list = soup.select(\"ol > li\") #複数要素を取り出してリストで返す コピーしたcssセレクターを参照すると ol > liに情報が入っている\nfor li in li_list:\n a = li.a #.aはtag\"a\"のことかな?⇨多分それで確定\n if a != None:\n name = a.string\n href = a.attrs[\"href\"]\n print(name, \">\", href)\n\n\n\n","repo_name":"silbull/python_flamework","sub_path":"scraping_study/sel-souseki.py","file_name":"sel-souseki.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"ja","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"35979306179","text":"from copy import deepcopy\nfrom .BaseSearcher import BaseSearcher\nimport pyro\nimport torch\nimport pyro.distributions as dist\nfrom torch_geometric.utils import to_networkx, from_networkx\nfrom torch_geometric.data import Data\nimport networkx as nx\nfrom torch.nn.functional import binary_cross_entropy\nimport numpy as np\n\n\nclass GreedySearcher(BaseSearcher):\n def __init__(self, name: str, edges: int):\n self.name = name\n self.edges = edges\n \n def search(self, X, y, explainer, **train_hparams):\n ne = explainer.edge_index_adj.shape[1]\n self.ne = ne\n edge_mask = torch.zeros([self.ne])\n G = to_networkx(Data(edge_index=explainer.edge_index_adj, num_nodes=explainer.edge_index_adj.max()))\n nodes = set()\n nodes.add(explainer.mapping.item())\n possible_set = set()\n added_edges = set()\n\n with torch.no_grad():\n preds = explainer.model(X, explainer.edge_index_adj)[explainer.mapping].reshape(-1).exp().softmax(dim=0).cpu()\n\n for edge in nx.edges(G, nbunch=list(nodes)):\n possible_set.add((edge[0], edge[1]))\n \n while len(added_edges) < self.edges:\n best = None\n best_ent = 100000\n inc = False\n\n for consideration in possible_set.difference(added_edges):\n test = deepcopy(added_edges)\n test.add(consideration)\n edge_index_mask = torch.Tensor(np.array([list(map(lambda x: x[0], test)), \n list(map(lambda x: x[1], test))])).long()\n preds_masked = explainer.model(X, edge_index_mask)[explainer.mapping].reshape(-1).exp()\n\n curr_ent = binary_cross_entropy(preds, preds_masked).detach().tolist()\n if curr_ent < best_ent:\n best = consideration\n best_ent = curr_ent\n inc = True\n\n if not inc:\n break\n\n if best != None: \n added_edges.add(best)\n start = explainer.edge_index_adj[0, :] == best[0]\n end = explainer.edge_index_adj[1, :] == best[1]\n idx = (start * end).nonzero().item()\n edge_mask[idx] = 1\n \n for edge in nx.edges(G, nbunch=list(nodes)):\n rewrap = (edge[1], edge[0])\n if rewrap not in added_edges:\n possible_set.add(rewrap)\n if edge not in added_edges:\n possible_set.add(edge)\n\n \n return edge_mask\n\n def run_name(self):\n return self.name\n","repo_name":"shalinkpatel/GCN_Integration","sub_path":"scripts/BI/pyro_model/model/searchers/GreedySearcher.py","file_name":"GreedySearcher.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"1247379251","text":"# coding:utf-8\n# kaggle Jane Street Market Prediction代码\n# 数据探索代码\n\n\nimport numpy as np\nimport pandas as pd\nfrom pandas import Series, DataFrame\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport seaborn as sns\nimport os\nimport sys\nimport gc\nfrom run import *\nfrom sklearn.preprocessing import StandardScaler as scale\nfrom sklearn.decomposition import PCA\nfrom sklearn.cluster import k_means\nfrom sklearn.preprocessing import RobustScaler\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.cluster import KMeans\n\n\n# 数据探索\ndef data_explore_old(df):\n # 复制数据,防止改变原数据\n data = df.copy()\n # 查看列名\n print(data.columns)\n # 查看数据开头\n print(data.head())\n # 有空值\n # 看数据总和\n print(data.sum())\n # 看平均数\n print(data.mean())\n # 输出描述统计值\n print(data.describe())\n # 查看空值\n print(data.isnull().sum())\n # 最多的有1734个空值,接近20%\n # 先画折线图吧\n # 画目标值\n fig = plt.figure()\n fig, axes = plt.subplots(4, 2, sharex = True)\n for i in range(4):\n for j in range(2):\n pos = 2*i + j\n if pos > 6:\n break\n axes[i][j].set_title(data.columns[pos])\n axes[i][j].plot(data.iloc[:, pos])\n plt.subplots_adjust(wspace = 0.2, hspace = 1)\n plt.savefig(\"./output/targets_line.png\")\n plt.close()\n # 画特征\n fig = plt.figure(figsize = (10, 80))\n for i in range(130):\n ax = fig.add_subplot(65, 2, i+1)\n ax.set_title(data.columns[i+7])\n plt.plot(data.iloc[:, i+7])\n plt.subplots_adjust(wspace = 0.2, hspace = 1)\n plt.savefig(\"./output/features_line.png\")\n plt.close()\n \n # 画柱状图\n # 画目标值\n fig = plt.figure()\n sns.distplot(data.iloc[:, 1:8], hist = True, bins = 100, kde = True)\n # data.iloc[:, 1:8].plot.hist(subplots = True, sharex = True, layout = (4, 2), bins = 50)\n plt.savefig(\"./output/targets_hist.png\")\n # 画特征\n fig = plt.figure()\n sns.distplot(data.iloc[:, 8:-2], hist = True, bins = 100, kde = True)\n # data.iloc[:, 8:-2].plot.hist(subplots = True, sharex = True, layout = (65, 2), figsize = (10, 80), bins = 50)\n plt.savefig(\"./output/features_hist.png\")\n \n# # 画密度图\n# # 画目标值\n# fig = plt.figure()\n# data.iloc[:, 1:8].plot(subplots = True, kind = \"hist\", sharex = True, layout = (4, 2), bins = 50)\n# plt.savefig(\"./output/targets_hist.png\")\n# # 画特征\n# fig = plt.figure()\n# data.iloc[:, 8:-2].plot(subplots = True, kind = \"hist\", sharex = True, layout = (65, 2), figsize = (10, 80), bins = 50)\n# plt.savefig(\"./output/features_hist.png\")\n\n\n# 数据探索\n@change_dir\ndef data_explore():\n sns.set_style('darkgrid')\n pd.set_option('display.max_columns', None)\n pd.set_option('display.max_rows', None)\n # 抽样,读取1%数据\n # 参考https://mp.weixin.qq.com/s/2LSKnN9R-N-I2HcHePT9zA\n train_df = pd.read_csv(\"./train.csv\", skiprows = lambda x: x>0 and np.random.rand() > 0.01)\n test_df = pd.read_csv(\"./example_test.csv\")\n feature_df = pd.read_csv(\"./features.csv\")\n \n\n # 复制数据\n # train = train_df.copy()\n # test = test_df.copy()\n EDA1(train_df, test_df, feature_df)\n EDA2(train_df, test_df, feature_df)\n EDA3(train_df, test_df, feature_df)\n \n \n# 第一篇文章的EDA\n# 参考https://www.kaggle.com/muhammadmelsherbini/jane-street-extensive-eda\ndef EDA1(train, test, feature):\n df = train.copy()\n # 看数据长度\n org_len = len(df)\n print(org_len)\n # 查看数据概况\n print(df.info())\n\n # 按日期排序数据\n df.sort_values(by = [\"date\", \"ts_id\"], inplace = True)\n \n # 增加目标数据\n df[\"action\"] = np.where(df[\"resp\"] > 0, 1, 0)\n df.action = df.action.astype(\"category\")\n \n # 下面开始分析数据\n # 先分析resp\n fig = plt.figure(figsize = (16, 6))\n ax = plt.subplot(1, 1, 1)\n df.groupby(\"date\")[[\"resp_1\", \"resp_2\", \"resp_3\", \"resp_4\", \"resp\"]].sum().cumsum().plot(ax = ax)\n plt.savefig(\"./output/01.png\")\n # 前92天收益较高,resp_4的累积收益较高\n # resp_1的累积收益较低\n \n # 再画resp的平均值\n fig = px.line(df.groupby(\"date\")[[\"resp_1\", \"resp_2\", \"resp_3\", \"resp_4\", \"resp\"]].mean(), x = df.groupby(\"date\")[[\"resp_1\", \"resp_2\", \"resp_3\", \"resp_4\", \"resp\"]].mean().index, y = [\"resp_1\", \"resp_2\", \"resp_3\", \"resp_4\", \"resp\"], title = \"average resp per day\")\n fig.write_image(\"./output/02.png\")\n \n # 画组图\n # 画resp数据的直方组图\n def resp_hists(ax1, ax2, ax3, data, name):\n ax1.hist(data, bins = 150, color = \"darkblue\", alpha = 0.6)\n ax1.axvline(data.mean() + data.std(),color = 'darkorange', linestyle = ':',linewidth = 2)\n ax1.axvline(data.mean() - data.std(),color = 'darkorange', linestyle = ':',linewidth = 2)\n data.plot.hist(bins = 150,ax = ax2, color = 'darkblue', alpha = 0.6)\n ax2.axvline(data.mean() + data.std(),color = 'darkorange', linestyle = ':', linewidth = 2)\n ax2.axvline(data.mean() - data.std(), color = 'darkorange', linestyle = ':',linewidth = 2)\n ax2.set_xlim(-.08, .08)\n ax3.hist(data, bins=150, color='darkblue',alpha=.6)\n ax3.set_yscale('log')\n skew= round(data.skew(),4)\n kurt= round(data.kurtosis())\n std1= round((((data.mean()-data.std()) < data ) & (data < (data.mean()+data.std()))).mean()*100,2)\n props = dict(boxstyle='round', facecolor='white', alpha=0.5)\n ax1.text(.02,.96,'μ = {}\\nstd = {}\\nskewness = {}\\nkurtosis = {}\\n% values in 1 std = {}%'.format(round(data.mean(),4),round(data.std(),4),skew,kurt,std1),\ntransform=ax1.transAxes, verticalalignment='top',bbox=props,fontsize=10)\n ax1.set_title(name + ' Hist Normal scale', fontsize=14)\n ax2.set_title(name + ' Hist normal scale zoomed',fontsize=14)\n ax3.set_title(name + ' Hist with freq on a log scale',fontsize=14);\n ax1.set_xlabel('')\n ax1.set_ylabel('')\n ax2.set_xlabel('')\n ax2.set_ylabel('')\n ax3.set_xlabel('')\n ax3.set_ylabel('')\n \n fig,((ax11,ax12,ax13),(ax21,ax22,ax23),(ax31,ax32,ax33),(ax41,ax42,ax43),(ax51,ax52,ax53)) = plt.subplots(5,3,figsize=(18,24))\n plt.subplots_adjust(hspace = 0.35)\n resp_hists(ax11, ax12, ax13, df.resp, \"Resp\")\n resp_hists(ax21, ax22, ax23, df.resp_1, \"Resp_1\")\n resp_hists(ax31, ax32, ax33, df.resp_2, \"Resp_2\")\n resp_hists(ax41, ax42, ax43, df.resp_3, \"Resp_3\")\n resp_hists(ax51, ax52, ax53, df.resp_4, \"Resp_4\")\n \n plt.savefig(\"./output/03.png\")\n \n # resp变量之间配对作图\n sns.pairplot(df[[\"resp_1\", \"resp_2\", \"resp_3\", \"resp_4\", \"resp\"]], corner = False)\n plt.savefig(\"./output/04.png\")\n # resp与resp_4,以及resp_1与resp_2之间高度相关。\n # 投资时区越长,风险及收益越大,反之越小\n \n # 下面分析date\n # 看独特的date值\n print(df.date.unique())\n # 完整数据500天,大约两年的数据\n # 现在查看每天的收益总数,以及操作总数\n fig = px.area(data_frame = df.groupby(\"date\")[[\"resp\"]].count(), title='Number of operation per day')\n fig.update_traces(showlegend = False)\n\n fig.layout.xaxis.title = 'Day'\n fig.layout.yaxis.title = 'Number of operations'\n fig.write_image(\"./output/05.png\")\n # 每天收益总数\n fig = px.area(data_frame = df.groupby(\"date\")[[\"resp\"]].sum(), title='Resp sum of operation per day')\n fig.update_traces(showlegend = False)\n\n fig.layout.xaxis.title = 'Day'\n fig.layout.yaxis.title = 'Resp sum of operations'\n fig.write_image(\"./output/06.png\")\n # 可以看到收益有很多波动\n # 下面建立平均收益的20天移动标准差\n date_df = df.groupby(\"date\")[[\"resp\"]].mean()\n std20 = []\n for i in range(len(date_df)):\n if i < 20:\n std20.append(np.nan)\n else:\n moving_std = date_df[\"resp\"][i-20:i].std()\n std20.append(moving_std)\n date_df[\"moving_std\"] = std20\n print(date_df.tail(2))\n # 画图看看\n fig = px.line(data_frame = date_df, y = [\"resp\", \"moving_std\"], title='Average Resp & 20 day moving standard deviation')\n fig.layout.xaxis.title = \"Day\"\n fig.layout.yaxis.title = \"Avg Resp\"\n fig.write_image(\"./output/07.png\")\n \n # 现在看每个resp值每天的标准差\n fig, (ax1, ax2) = plt.subplots(2, 1, figsize = (14, 12))\n df.groupby(\"date\")[[\"resp_1\", \"resp_2\", \"resp_3\", \"resp_4\"]].std().plot(ax = ax1, color=['steelblue','darkorange','red','green'], alpha=.8)\n df.groupby(\"date\")[[\"resp_1\", \"resp_2\", \"resp_3\", \"resp_4\"]].std().plot.kde(ax = ax2)\n fig.suptitle('Resp\\'s Std',fontsize=18,y=.96)\n\n ax2.set_xlabel('')\n\n ax1.set_xlabel('')\n\n ax2.set_title('kde of each resp std', fontsize=14)\n\n ax1.set_title('std of Resp\\'s for each trading day',fontsize=14)\n fig.savefig(\"./output/08.png\")\n # 更长时期的resp的标准差也更大\n # 另外前100天的标准差大一些,因为80天后模型有调整\n \n # 下面来看看weight的情况\n fig = plt.figure(figsize = (18, 7))\n grid = gridspec.GridSpec(2, 3, figure = fig, hspace = 3, wspace = 2)\n ax1 = fig.add_subplot(grid[0, 0])\n ax2 = fig.add_subplot(grid[0, 1])\n ax3 = fig.add_subplot(grid[1, 0])\n ax4 = fig.add_subplot(grid[1, 1])\n ax5 = fig.add_subplot(grid[:, 2])\n sns.boxplot(x = df.weight, width = 0.5, ax = ax1)\n ax2.hist(df.weight, color='#404788ff', alpha = 0.6, bins = list([-.05] + list(10**np.arange(-2,2.24,.05))))\n ax2.set_xscale('symlog')\n\n ax2.set_xlim(-.05,227)\n sns.boxplot(x = df.weight[df.weight != 0], width = 0.5, ax = ax3)\n ax1.set_title('Weights including zero weights',fontsize=14)\n\n ax3.set_title('Weights not including zero weights',fontsize=14)\n\n ax2.set_title('Weights including zero weights (log)',fontsize=14)\n\n ax4.set_title('Weights not including zero weights (log)',fontsize=14)\n props = dict(boxstyle='round',facecolor='white', alpha=0.4)\n ax1.text(.2,.9,'μ = {} std = {}\\nmin = {} max = {}'.format(round(df.weight.mean(),3),round(df.weight.std(),3),round(df.weight.min(),3), round(df.weight.max(),3)),\ntransform=ax1.transAxes, verticalalignment='top',bbox=props,fontsize=12)\n\n ax3.text(.2,.9,'μ = {} std = {}\\nmin = {} max = {}'.format(round(df.weight[df.weight\n!= 0].mean(),3), round(df.weight[df.weight != 0].std(), 3),\nround(df.weight[df.weight != 0].min(),3), round(df.weight[df.weight != 0].max(),3)), transform=ax3.transAxes, verticalalignment='top',bbox=props, fontsize=12)\n ax4.hist(df.weight[df.weight !=0], color='#404788ff', alpha=.6,bins=10**np.arange(-2.16,2.24,.05))\n ax4.set_xscale('log')\n\n ax4.set_xticks((.01,.03,.1,.3,1,3,10,30,100))\n\n ax4.set_xticklabels((.01,.03,.1,.3,1,3,10,30,100))\n ax5.pie(((df.weight==0).mean(),(1-(df.weight==0).mean())),startangle=300,wedgeprops=dict(width=0.5), labels=('Zeros\\n{}%'.format(round((df.weight==0).mean()*100,2)), 'Nonzeros\\n{}%'.format(round((1-(df.weight==0).mean())*100,2))),\ntextprops={'fontsize': 12},colors=['#404788ff','#55c667ff'])\n ax5.set_title('Zeros vs non-zero weights', fontsize=14)\n\n ax1.set_xlabel('')\n\n ax2.set_xlabel('')\n\n ax3.set_xlabel('')\n\n ax2.set_ylabel('')\n\n ax5.set_ylabel('')\n\n ax4.set_xlabel('')\n fig.savefig(\"./output/09.png\")\n # 画weight的直方图\n fig = plt.figure(figsize = (15, 10))\n fig.suptitle('Nonzero weights histogram in different scales',fontsize=18)\n ax1 = plt.subplot(3,1,1)\n ax1.hist(df.weight[df.weight !=0], color='darkblue', alpha=.7, bins=10**np.arange(-2.16,2.23,.05))\n plt.xscale('log')\n plt.xticks((.01,.03,.1,.3,1,3,10,30,100),(.01,.03,.1,.3,1,3,10,30,100))\n ax2 = plt.subplot(3, 1, 2)\n sns.distplot(df.weight[df.weight != 0], color='darkblue', bins=400, ax=ax2)\n ax3 = plt.subplot(3, 1, 3)\n ax3.hist(df.weight[(df.weight !=0) & (df.weight < 3.197 )],color='darkblue',alpha=.7, bins=200)\n ax3.set_xlim(0,3.3)\n\n ax2.set_xlabel('')\n\n ax1.set_title('All values (log-scale)', fontsize=14)\n\n ax2.set_title('kde of the distribution',fontsize=14)\n\n ax3.set_title('75% of the Values',fontsize=14)\n\n plt.subplots_adjust(hspace=.4)\n fig.savefig(\"./output/10.png\")\n # 再看细一点\n fig, (ax1, ax2) = plt.subplots(2, 1, figsize = (16, 8))\n fig.suptitle('Weight outliers',fontsize=18)\n sns.boxplot(df.weight, width = 0.5, ax = ax1)\n ax1.axvline(np.percentile(df.weight,95), color= 'green',label='95.0%',linestyle=':', linewidth=3)\n\n ax1.axvline(np.percentile(df.weight,99), color= 'darkblue',label='99.0%',linestyle=':',linewidth\n= 3)\n\n ax1.axvline(np.percentile(df.weight,99.9), color= 'darkorange',label='99.9%',linestyle=':',linewidth=3)\n\n ax1.axvline(np.percentile(df.weight,99.99), color= 'magenta',label='99.99%',linestyle=':',linewidth=3)\n\n ax1.legend(fontsize=13)\n sns.boxplot(df.weight[df.weight != 0], width = 0.5, ax = ax2)\n ax2.axvline(np.percentile(df.weight[df.weight != 0],95), color= 'green',label='95.0%',linestyle=':', linewidth=3)\n\n ax2.axvline(np.percentile(df.weight[df.weight != 0],99), color= 'darkblue',label='99.0%',linestyle=':',linewidth\n= 3)\n\n ax2.axvline(np.percentile(df.weight[df.weight != 0],99.9), color= 'darkorange',label='99.9%',linestyle=':',linewidth=3)\n\n ax2.axvline(np.percentile(df.weight[df.weight != 0],99.99), color= 'magenta',label='99.99%',linestyle=':',linewidth=3)\n\n ax2.legend(fontsize=13)\n fig.savefig(\"./output/11.png\")\n \n # resp与weight的关系\n fig = plt.figure()\n sns.scatterplot(data = df, x = \"resp\", y = \"weight\", color = \"blue\", alpha = 0.3)\n plt.title('Resp vs Weight\\ncorrelation={}'.format(round(df.weight.corr(df.resp),4)))\n plt.savefig(\"./output/12.png\")\n # 两者不是线性相关的,高权重值与低收益值相关 # 再来看看feature数据。\n df_f = pd.read_csv(\"./features.csv\")\n print(df_f.head(5))\n print(df_f.shape)\n # 画柱状图看看\n fig = px.bar(df_f.set_index(\"feature\").T.sum(), title = \"Number of tags for each feature\")\n fig.layout.xaxis.tickangle = 300\n fig.update_traces(showlegend = False)\n fig.layout.xaxis.dtick = 5\n\n fig.layout.xaxis.title = \"\"\n fig.layout.yaxis.title = \"\"\n fig.write_image(\"./output/13.png\")\n \n # 下面画图看空值\n fig = px.bar(x = df.isnull().sum().index, y = df.isnull().sum().values, title = \"Number of null values\")\n fig.layout.xaxis.tickangle = 300\n\n fig.layout.xaxis.dtick = 5\n\n fig.layout.yaxis.dtick = 100000\n\n fig.layout.xaxis.title = ''\n\n fig.layout.yaxis.title = ''\n\n fig.layout.xaxis.showgrid = True\n fig.write_image(\"./output/14.png\")\n # 有空值的特征约占10%\n nulls = df.isnull().sum()\n nulls_list = list(nulls[nulls > (0.1*len(df))].index)\n print(nulls_list)\n # 看看这些特征中空值的个数有没有什么模式\n plt.figure()\n corr_null = df[['resp','resp_1','resp_2','resp_3','resp_4','weight']+nulls_list].corr()\n #print(corr_null)\n sns.heatmap(corr_null)\n plt.savefig(\"./output/15.png\")\n # 将所有空值数量大于10%的特征丢弃\n df.drop(columns = nulls_list, inplace = True)\n # 现在关注剩下的空值,先看相关系数的变异\n print((df.iloc[:, 7:-2].std()/df.iloc[:7:-2].mean()).head(5))\n # 看起来相关性是不可靠的,因为均值接近0\n \n # 现在看特征值的分布\n plt.figure()\n df.iloc[:, 7:-2].hist(bins=100, figsize=(20, 74), layout=(29, 4))\n plt.savefig(\"./output/16.png\")\n # 接着用水平箱图来看,由于数据较集中,排除末端0.1%\n fig = plt.figure(figsize=(20, 80))\n fig.suptitle('Features Box plot with 0.1% 99.9% whiskers',fontsize=22, y=.89)\n grid = gridspec.GridSpec(29,4,figure=fig,hspace=.5,wspace=.05)\n featstr = [i for i in df.columns[7:-2]]\n counter = 0\n for i in range(29):\n for j in range(4):\n subf = fig.add_subplot(grid[i, j])\n sns.boxplot(x = df[featstr[counter]], saturation = 0.5, color = \"blue\", ax = subf, width = 0.5, whis = (0.1, 99.9))\n subf.axvline(df[featstr[counter]].mean(),color= 'darkorange', label='Mean', linestyle=':',linewidth=3)\n subf.set_xlabel(\"\")\n subf.set_title('{}'.format(featstr[counter]),fontsize=16)\n counter += 1\n # gc.collect()\n plt.savefig(\"./output/17.png\")\n # 我们可以看到有很多异常值,影响特征分布\n # 由于大部分数据集中于均值附近,用均值填充空值\n df.fillna(df.mean(axis = 0), inplace = True)\n \n # 再来看看特征的累积情况\n df.groupby(\"date\")[featstr].mean().cumsum().plot(layout=(29, 4), subplots = True, figsize=(20, 82), xlabel=\"\")\n fig = plt.gcf()\n fig.text(0.5, 0.19, \"Date\", ha=\"center\", fontsize=24)\n fig.suptitle(\"Cumulative features means per day\", fontsize=24, y=0.886)\n fig.savefig(\"./output/18.png\")\n # 大部分特征的累积均数是递增的,也有部分是递减,还有小部分是没有明显趋势的\n \n # 下面来看特征之间的相关度\n corr = df.iloc[:, 7:-2].corr()\n fig = plt.figure(figsize=(18, 12))\n ax = plt.subplot(1, 1, 1)\n sns.heatmap(corr, ax = ax, cmap = \"coolwarm\")\n plt.savefig(\"./output/19.png\")\n # 看起来很多特征之间存在共线性\n featstr2 = [i for i in featstr if i not in [\"feature_41\", \"feature_64\"]]\n print(len(featstr))\n \n # 画散点图看看\n fig = plt.figure(figsize=(22, 44))\n grid = gridspec.GridSpec(12, 5, figure=fig, hspace=0.5, wspace=0.2)\n counter = 1\n for i in range(12):\n for j in range(5):\n if counter == 113:\n break\n subf = fig.add_subplot(grid[i, j])\n sns.scatterplot(x = df[featstr2[counter]], y = df[featstr2[counter+1]], ax = subf)\n cor = round(df[featstr2[counter]].corr(df[featstr2[counter+1]])*100, 2)\n subf.set_xlabel(\"\")\n subf.set_ylabel(\"\")\n subf.set_title('{} & {}\\nCorrelation = {}%'.format(featstr2[counter],featstr2[counter+1],cor),fontsize=14)\n counter += 2\n # gc.collect()\n fig.savefig(\"./output/20.png\")\n # 由于这些特征是金融相关特征,很多都有很高的相关性\n # 现在来看看有高度相关性的特征组\n plt.figure(figsize=(12, 6))\n sns.heatmap(df[featstr2[15:23]].corr(), center = 0, cmap = \"coolwarm\", annot = True, cbar = False)\n fig.savefig(\"./output/21.png\")\n # 画配对图\n sns.pairplot(df[featstr2[15:23]], corner = True)\n fig.savefig(\"./output/22.png\")\n # 尽管相关系数很高,但变量并不完全是线性的,异常值影响了散点图的形状\n # 看其它组的\n plt.figure(figsize=(12, 6))\n sns.heatmap(df[featstr2[23:31]].corr(), center = 0, cmap = \"coolwarm\", annot = True, cbar = False)\n fig.savefig(\"./output/23.png\")\n # 画配对图\n sns.pairplot(df[featstr2[23:31]], corner = True)\n fig.savefig(\"./output/24.png\")\n # 与前面情况类似\n # 这两组之间是负相关的,画到一起看看\n plt.figure(figsize=(18, 6))\n sns.heatmap(df[featstr2[15:31]].corr(), center = 0, cmap = \"coolwarm\", annot = True, cbar = False)\n fig.savefig(\"./output/25.png\")\n \n # 下面查看异常值\n # 特征平均值\n fig = px.bar(df[featstr].mean(), title = \"Features mean values\")\n fig.layout.xaxis.tickangle = 300\n fig.update_traces(showlegend = False)\n fig.layout.xaxis.dtick = 5\n fig.layout.xaxis.title = \"\"\n fig.layout.yaxis.title = \"\"\n fig.write_image(\"./output/26.png\")\n # 特征最大值\n fig = px.bar(df[featstr].max(), title = \"Features Max values\")\n fig.layout.xaxis.tickangle = 300\n fig.update_traces(showlegend = False)\n fig.layout.xaxis.dtick = 5\n fig.layout.xaxis.title = \"\"\n fig.layout.yaxis.title = \"\"\n fig.write_image(\"./output/27.png\")\n # 特征最低值\n fig = px.bar(df[featstr].min(), title = \"Features min values\")\n fig.layout.xaxis.tickangle = 300\n fig.update_traces(showlegend = False)\n fig.layout.xaxis.dtick = 5\n fig.layout.xaxis.title = \"\"\n fig.layout.yaxis.title = \"\"\n fig.write_image(\"./output/28.png\")\n plt.close()\n # 上述三个值的分布\n fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 12))\n plt.subplots_adjust(hspace=3)\n sns.distplot(df[featstr].max(), ax = ax1)\n sns.distplot(df[featstr].min(), ax = ax2)\n sns.distplot(df[featstr].mean(), ax = ax3)\n fig.suptitle('distribution of mean max and min for features',fontsize=16)\n ax1.set_title('distribution of features max values',fontsize=14)\n ax1.text(.82,.56,'std = {}'.format(round(df[featstr].max().std(),2)),transform=ax1.transAxes, verticalalignment='top',bbox=props,fontsize=12)\n ax2.set_title('distribution of features min values',fontsize=14)\n ax2.text(.82,.56,'std = {}'.format(round(df[featstr].min().std(),2)),transform=ax2.transAxes, verticalalignment='top',bbox=props,fontsize=12)\n ax3.set_title('distribution of features mean values',fontsize=14)\n ax3.text(.82,.56,'std = {}'.format(round(df[featstr].mean().std(),2)),transform=ax3.transAxes, verticalalignment='top',bbox=props,fontsize=12)\n fig.savefig(\"./output/29.png\")\n plt.close()\n # 最大最小值的分布都呈偏态。\n \n # 下面进行更详细的统计描述\n for i in featstr[1:]:\n print('{}\\n0.1%:99.9% are between: {}\\nmax: {}\\nmin: {}\\n75% are under: {}'.format(i,np.percentile(df[i],(.1,99.9)), df[i].max(),df[i].min(),np.percentile(df[i],75)), '\\n===============================')\n \n print(df[(df.feature_56== df.feature_56.max())|(df.feature_57== df.feature_57.max())|(df.feature_58== df.feature_58.max()) | (df.feature_59== df.feature_59.max())])\n # 可以看出数据有很多极端异常值\n # 一些异常值导致了共线性\n \n # 现在去除超出99.9%特征值的异常值\n n999 = [np.percentile(df[i], 99.9) for i in featstr[1:]]\n n001 = [np.percentile(df[i], 0.1) for i in featstr[1:]]\n \n for i, j in enumerate(featstr[1:]):\n df = df[df[j] < n999[i]]\n # gc.collect()\n # 看看抛弃了多少数据\n print(str(round(((org_len - len(df))/org_len)*100,2))+'%')\n # 再画图看看\n fig = px.bar(df[featstr].max(), title = \"Features Max values\")\n fig.layout.xaxis.tickangle = 300\n fig.update_traces(showlegend = False)\n fig.layout.xaxis.dtick = 5\n fig.layout.xaxis.title = \"\"\n fig.layout.yaxis.title = \"\"\n fig.write_image(\"./output/30.png\")\n plt.close()\n # 再画箱状图\n fig = plt.figure(figsize=(20, 80))\n fig.suptitle('Features Box plot with 0.1% 99.9% whiskers',fontsize=22, y=.89)\n grid = gridspec.GridSpec(29,4,figure=fig,hspace=.5,wspace=.05)\n counter = 0\n for i in range(29):\n for j in range(4):\n subf = fig.add_subplot(grid[i, j])\n sns.boxplot(x = df[featstr[counter]], saturation = 0.5, color = \"blue\", ax = subf, width = 0.5, whis = (0.1, 99.9))\n subf.set_xlabel(\"\")\n subf.set_title('{}'.format(featstr[counter]),fontsize=16)\n counter += 1\n # gc.collect()\n plt.savefig(\"./output/31.png\")\n plt.close()\n # 正的异常值少了,负的还有,尤其3-40\n # 再处理负的异常值\n for i, j in zip(featstr[1:][2:34], n001[2:34]):\n df = df[df[i] > j]\n # gc.collect()\n # 看去掉了多少\n print(str(round(((org_len - len(df))/org_len)*100,2))+'%')\n # 接着画去除异常值后的概率密度图和柱形图\n fig = plt.figure(figsize=(20,80))\n fig.suptitle('KDE plot of Features',fontsize=24,transform =fig.transFigure, y=.89)\n grid = gridspec.GridSpec(29,4,figure=fig,hspace=.5,wspace=.01)\n counter = 0\n for i in range(29):\n for j in range(4):\n subf = fig.add_subplot(grid[i, j]);\n sns.distplot(df[df.action==0][featstr[counter]],bins= 100,label='Negative', color='darkorange', kde_kws={'linewidth':4},ax=subf)\n sns.distplot(df[df.action!=0][featstr[counter]],bins= 100,label='Positive', color='blue', kde_kws={'alpha':.9,'linewidth':2},hist_kws={'alpha':.3},ax=subf)\n subf.axvline(np.percentile(df[featstr[counter]],99.5),color= 'darkblue', label='99.5%', linestyle=':',linewidth=2)\n subf.axvline(np.percentile(df[featstr[counter]],.5),color= 'red', label='0.5%', linestyle=':',linewidth=2)\n subf.legend().set_visible(False)\n subf.set_xlabel('')\n subf.set_title('{}'.format(featstr[counter]),fontsize=16)\n kurt=round(df[featstr[counter]].kurt(),2)\n skew=round(df[featstr[counter]].skew(),2)\n subf.text(.6,.92,'Kurt = {:.2f}\\nSkew = {:.2f}'.format(kurt ,skew), transform=subf.transAxes, verticalalignment='top',bbox=props, fontsize=10)\n counter += 1\n # gc.collect();\n handles, labels = subf.get_legend_handles_labels()\n fig.legend(handles, labels,ncol=4, bbox_to_anchor=(0.86, 0.893),fontsize=10, title= 'Resp',title_fontsize=14,bbox_transform =fig.transFigure)\n plt.savefig(\"./output/32.png\")\n plt.close()\n \"\"\"\n 通过在特征分布上增加resp值,可以看到:①特征的柱状图现在有办法减少偏差形成更规则的分布。②一些特征比如1,2,85,87,88,91有很多负的偏差值。③一些特征如49,50,51,55,56,57,58,59仍然有正的偏差值。④特征值分布不受resp值的影响。\"\"\"\n # 特征与resp的相关性\n # 使用一个Series记录resp与每个特征的关系\n respcorr = pd.Series([df.resp.corr(df[i]) for i in featstr], index = featstr)\n fig = px.bar(respcorr, color = respcorr, color_continuous_scale = [\"red\", \"blue\"], title = \"Features Correlation with Resp\")\n fig.layout.xaxis.tickangle = 300\n fig.layout.xaxis. dtick = 5\n\n fig.layout.xaxis.title = ''\n\n fig.layout.yaxis.title = 'pearson correlation'\n\n fig.update(layout_coloraxis_showscale=False)\n fig.write_image(\"./output/33.png\")\n plt.close()\n # 可以看到feature并不是真的与resp相关\n # 再来看看feature与weight\n # 同样建一个Series,只保留weight大于0的\n wecorr = pd.Series([df[df.weight != 0].weight.corr(df[df.weight != 0][i]) for i in featstr],index=featstr)\n print(wecorr.head(10))\n fig = px.bar(wecorr, color = wecorr, color_continuous_scale = [\"red\", \"blue\"], title= 'Features Correlation with Weight (not including zero weights)')\n fig.layout.xaxis.tickangle = 300\n fig.layout.xaxis. dtick = 5\n\n fig.layout.xaxis.title = ''\n\n fig.layout.yaxis.title = 'pearson correlation'\n\n fig.update(layout_coloraxis_showscale=False)\n fig.write_image(\"./output/34.png\")\n plt.close()\n # 现在来看相关性最高的第51号特征,用散点图\n fig = plt.figure(figsize=(8, 6))\n sns.scatterplot(df[df.weight != 0].weight, df[df.weight != 0].feature_51, color = 'darkblue', alpha=.3)\n plt.xlabel('Weight',fontsize=14)\n\n plt.ylabel('Featre_51',fontsize=14)\n\n plt.title('Feature_51 vs Weight\\nCorrelation = {}%'.format(round(df[df.weight != 0].weight.corr(df[df.weight != 0].feature_51),4)*100), fontsize=16)\n fig.savefig(\"./output/35.png\")\n plt.close()\n # 看起来51号特征与weigh高度相关\n # 再来看相关度最低的126号特征\n fig = plt.figure(figsize=(8, 6))\n sns.scatterplot(df[df.weight != 0].weight, df[df.weight != 0].feature_126, color = 'darkblue', alpha=.3)\n plt.xlabel('Weight',fontsize=14)\n\n plt.ylabel('Featre_126',fontsize=14)\n\n plt.title('Feature_126 vs Weight\\nCorrelation = {}%'.format(round(df[df.weight != 0].weight.corr(df[df.weight != 0].feature_51),4)*100), fontsize=16)\n fig.savefig(\"./output/36.png\")\n plt.close()\n \n # 下面研究特征0\n plt.figure(figsize=(7, 5))\n df.feature_0.value_counts().plot.bar(color='darkblue',alpha=.6,width=.5)\n plt.title('Feature_0',fontsize=18)\n\n plt.xticks(rotation=0,fontsize=14)\n fig.savefig(\"./output/37.png\")\n plt.close()\n # 看起来是二值分布\n # 再把resp加进来考虑\n plt.figure(figsize=(8, 6))\n sns.countplot(data=df, x=\"feature_0\", hue=\"action\", palette=\"viridis\")\n plt.xticks(fontsize=14)\n plt.yticks(fontsize=13)\n plt.xlabel('Feature 0',fontsize=12)\n plt.title('Feature 0 and Resp', fontsize=18)\n plt.ylabel('')\n plt.xlim(-1,2)\n h, l = plt.gca().get_legend_handles_labels()\n plt.legend(h,['Negative','Positive'],ncol=1, fontsize=12, loc=3,title= 'Resp',title_fontsize=14)\n plt.savefig(\"./output/37.png\")\n plt.close()\n # 看起来0号特征为正或为负与resp值无明显关系\n \n # 下面进行降维和群聚\n print(\"降维\")\n scaler = scale()\n scaler.fit(df[featstr[1:]])\n df_pca = pd.DataFrame(scaler.transform(df[featstr[1:]]))\n df_pca.columns = featstr[1:]\n print(df_pca.head())\n # 把数据降维为14个成分\n pca = PCA(n_components=14).fit(df_pca)\n df_pca = pd.DataFrame(pca.transform(df_pca))\n pcs = [\"pc\" + str(i+1) for i in range(14)]\n # 再把目标列加上去\n df_pca.columns = pcs\n df_pca[\"action\"] = df.action.values\n df_pca[\"weight\"] = df.weight.values\n df_pca[\"resp\"] = df.resp.values\n print(df_pca.head())\n # 画配对图看看\n plt.figure()\n sns.pairplot(data = df_pca, vars = pcs, hue = \"action\")\n plt.savefig(\"./output/38.png\")\n plt.close()\n # 降维后也没有明显的关系模式出现\n # 再聚类\n kmeans = k_means(n_clusters = 4, max_iter = 400, random_state = 0, X = df_pca[pcs])\n # 增加聚类列\n df_pca[\"cluster\"] = kmeans[1]\n df_pca[\"cluster\"] = df_pca[\"cluster\"].astype(\"category\")\n print(df_pca.head(8))\n # 画resp与聚类结果的关系\n fig = plt.figure(figsize=(12, 6))\n ax = plt.subplot(1, 1, 1)\n sns.countplot(data = df_pca, x = \"cluster\", hue = \"action\", ax = ax, palette = \"viridis\")\n h, l = plt.gca().get_legend_handles_labels()\n plt.legend(h,['Negative','Positive'],ncol=1, fontsize=12, loc=2,title= 'Resp', title_fontsize=14)\n plt.xlim(-1,4)\n plt.xlabel('Clusters',fontsize=16)\n plt.ylabel('')\n plt.title('PCA Clusters and Resp', fontsize=18)\n plt.savefig(\"./output/39.png\")\n plt.close()\n gc.collect()\n \n \n\n# 第二篇文章的EDA\n# 参考https://www.kaggle.com/manavtrivedi/eda-and-feature-selection\ndef EDA2(train_df, test_df, feature_df):\n train = train_df.copy()\n test = test_df.copy()\n print(train.head(10))\n # 看缺失值的情况\n temp = pd.DataFrame(train.isna().sum().sort_values(ascending = False) * 100/train.shape[0], columns = [\"missing %\"]).head(20)\n print(temp)\n # 新建action列\n train = train[train[\"weight\"] != 0]\n train[\"action\"] = (train[\"resp\"] > 0)*1\n print(train.action.value_counts())\n # 画图看看目标值\n fig, ax = plt.subplots(1, 2, figsize=(12, 6))\n plt.subplot(1, 2, 1)\n plt.title(\"Distributing of weight\")\n sns.distplot(train[\"weight\"], color = \"blue\", kde = True, bins = 100)\n t0 = train[train[\"action\"] == 0]\n t1 = train[train[\"action\"] == 1]\n plt.subplot(1, 2, 2)\n sns.distplot(train['weight'],color='blue',kde=True,bins=100)\n\n sns.distplot(t0['weight'],color='blue',kde=True,bins=100,label='action = 0')\n\n sns.distplot(t1['weight'],color='red',kde=True,bins=100,label='action = 1')\n\n plt.legend()\n plt.savefig(\"./output/40.png\")\n plt.close()\n # 画四个resp对weight的散点图\n fig,ax = plt.subplots(2,2,figsize=(12,10))\n\n for i,col in enumerate([f'resp_{i}' for i in range(1,5)]):\n\n plt.subplot(2,2,i+1)\n\n plt.scatter(train[train.weight!=0].weight,train[train.weight!=0][col])\n\n plt.ylabel(col)\n plt.xlabel('weight')\n plt.savefig(\"./output/41.png\")\n plt.close()\n \n # 画resp与其余四个resp的图\n fig, ax = plt.subplots(2, 2, figsize=(12, 10))\n i = 1\n for col in ([f\"resp_{i}\" for i in range(1, 5)]):\n plt.subplot(2, 2, i)\n plt.plot(train.ts_id.values, train.resp.values, label = \"resp\", color = \"blue\")\n plt.plot(train.ts_id.values, train[f\"resp_{i}\"].values, label = f\"resp_{i}\", color = \"red\")\n plt.xlabel(\"ts_id\")\n plt.legend()\n \n i += 1\n plt.savefig(\"./output/42.png\")\n plt.close()\n \n # 画四个resp的散点图\n plt.figure(figsize = (10, 10))\n plt.scatter(train.resp.values, train.resp_1.values, color = \"red\", label = \"resp_1\")\n plt.scatter(train.resp.values, train.resp_2.values, color = \"blue\", label = \"resp_2\")\n plt.scatter(train.resp.values, train.resp_3.values, color = \"orange\", label = \"resp_3\")\n plt.scatter(train.resp.values, train.resp_4.values, color = \"green\", label = \"resp_4\")\n plt.xlabel(\"resp\")\n plt.ylabel(\"other resp variables\")\n plt.legend()\n plt.savefig(\"./output/43.png\")\n plt.close()\n \n # 画累积量\n plt.figure(figsize = (8, 6))\n for col in ([f\"resp_{i}\" for i in range(1, 5)]):\n plt.plot(train[col].cumsum().values, label = col)\n plt.legend()\n plt.title(\"resp in different time horizons\")\n plt.savefig(\"./output/44.png\")\n plt.close()\n \n # 看看feature_0的情况\n sns.countplot(train.feature_0)\n plt.savefig(\"./output/45.png\")\n plt.close()\n \n # 每行的均值的分布,按目标值分类\n features = [col for col in train.columns if \"feature\" in col]\n t0 = train.loc[train[\"action\"] == 0]\n t1 = train.loc[train[\"action\"] == 1]\n plt.figure(figsize = (16, 6))\n plt.title(\"Distribution of mean values per row in the train set\")\n sns.distplot(t0[features].mean(axis = 1), color = \"red\", kde = True, bins = 120, label = \"target = 0\")\n sns.distplot(t1[features].mean(axis = 1), color = \"blue\", kde = True, bins = 120, label = \"target = 1\")\n plt.legend()\n plt.savefig(\"./output/46.png\")\n plt.close()\n \n # 每列的均值分布\n plt.figure(figsize = (16, 6))\n plt.title(\"Distribution of mean values per columns in the train set\")\n sns.distplot(t0[features].mean(axis = 0), color = \"green\", kde = True, bins = 120, label = \"target = 0\")\n sns.distplot(t1[features].mean(axis = 0), color = \"darkblue\", kde = True, bins = 120, label = \"target = 1\")\n plt.legend()\n plt.savefig(\"./output/47.png\")\n plt.close()\n \n # 每行的标准差的分布,按目标值分类\n features = [col for col in train.columns if \"feature\" in col]\n t0 = train.loc[train[\"action\"] == 0]\n t1 = train.loc[train[\"action\"] == 1]\n plt.figure(figsize = (16, 6))\n plt.title(\"Distribution of standard deviation values per row in the train set\")\n sns.distplot(t0[features].std(axis = 1), color = \"red\", kde = True, bins = 120, label = \"target = 0\")\n sns.distplot(t1[features].std(axis = 1), color = \"blue\", kde = True, bins = 120, label = \"target = 1\")\n plt.legend()\n plt.savefig(\"./output/48.png\")\n plt.close()\n \n # 每列的标准差分布\n plt.figure(figsize = (16, 6))\n plt.title(\"Distribution of standard deviation values per columns in the train set\")\n sns.distplot(t0[features].std(axis = 0), color = \"green\", kde = True, bins = 120, label = \"target = 0\")\n sns.distplot(t1[features].std(axis = 0), color = \"darkblue\", kde = True, bins = 120, label = \"target = 1\")\n plt.legend()\n plt.savefig(\"./output/49.png\")\n plt.close()\n \n # 每行的最小值的分布,按目标值分类\n t0 = train.loc[train[\"action\"] == 0]\n t1 = train.loc[train[\"action\"] == 1]\n plt.figure(figsize = (16, 6))\n plt.title(\"Distribution of min values per row in the train set\")\n sns.distplot(t0[features].min(axis = 1), color = \"red\", kde = True, bins = 120, label = \"target = 0\")\n sns.distplot(t1[features].min(axis = 1), color = \"blue\", kde = True, bins = 120, label = \"target = 1\")\n plt.legend()\n plt.savefig(\"./output/50.png\")\n plt.close()\n \n # 每列的最小值分布\n plt.figure(figsize = (16, 6))\n plt.title(\"Distribution of min values per columns in the train set\")\n sns.distplot(t0[features].min(axis = 0), color = \"green\", kde = True, bins = 120, label = \"target = 0\")\n sns.distplot(t1[features].min(axis = 0), color = \"darkblue\", kde = True, bins = 120, label = \"target = 1\")\n plt.legend()\n plt.savefig(\"./output/51.png\")\n plt.close()\n \n # 看相关性\n train_corr = train[features].corr().values.flatten()\n train_corr = train_corr[train_corr != 1]\n test_corr = test[features].corr().values.flatten()\n test_corr = test_corr[test_corr != 1]\n \n plt.figure(figsize = (20, 5))\n sns.distplot(train_corr, color = \"Red\", label = \"train\")\n sns.distplot(test_corr, color = \"Green\", label = \"test\")\n plt.xlabel(\"Correlation values found in train (except 1)\")\n plt.ylabel(\"Density\")\n plt.title(\"Are there correlations between features?\"); \n plt.legend()\n plt.savefig(\"./output/52.png\")\n plt.close()\n \n # 降维,画解释率\n plt.figure(figsize = (8, 5))\n pca = PCA().fit(train[features].iloc[:, 1:].fillna(train.mean()))\n plt.plot(np.cumsum(pca.explained_variance_ratio_), linewidth = 4)\n plt.axhline(y=0.9, color='r', linestyle='-')\n plt.xlabel(\"number of components\")\n plt.ylabel(\"sum of explained variance ratio\")\n plt.savefig(\"./output/53.png\")\n plt.close()\n \n # 数据标准化\n rb = RobustScaler()\n data = rb.fit_transform(train[features].iloc[:,1:].fillna(train[features].fillna(train[features].mean())))\n data = PCA(n_components=2).fit_transform(data)\n plt.figure(figsize=(7,7))\n sns.scatterplot(data[:,0],data[:,1], hue=train['action'])\n plt.xlabel('pca comp 1')\n plt.ylabel('pca comp 2')\n plt.savefig(\"./output/54.png\")\n plt.close()\n \n # KNN算法聚类\n X_std = train[[f\"feature_{i}\" for i in range(1, 130)]].fillna(train.mean()).values\n sse = []\n list_k = list(range(1, 10))\n # 分1-10个类\n for k in list_k:\n km = KMeans(n_clusters = k)\n km.fit(data)\n sse.append(km.inertia_)\n \n plt.figure(figsize=(6, 6))\n plt.plot(list_k, sse, '-o')\n plt.xlabel(r'Number of clusters *k*')\n plt.ylabel('Sum of squared distance')\n plt.savefig(\"./output/55.png\")\n plt.close()\n \n # 用knn模型预测\n knn = KMeans(n_clusters = 2)\n labels = knn.fit_predict(data)\n sns.scatterplot(data[:, 0], data[:, 1], hue = labels)\n plt.savefig(\"./output/56.png\")\n plt.close()\n \n # 随机森林选出最重要的20个特征\n target = \"action\"\n cols_drop = list(np.setdiff1d(train.columns, test.columns)) + [\"ts_id\", \"date\"]\n \n clf = RandomForestClassifier()\n clf.fit(train.drop(cols_drop, axis = 1).fillna(-999), train[\"action\"])\n top = 20\n top_features = np.argsort(clf.feature_importances_)[::-1][:top]\n feature_names = train.drop(cols_drop, axis = 1).iloc[:, top_features].columns\n \n plt.figure(figsize=(8, 7))\n sns.barplot(clf.feature_importances_[top_features], feature_names, color = \"blue\")\n plt.savefig(\"./output/57.png\")\n plt.close()\n \n # 画剩下的特征的分布\n \"\"\"\n top = 8\n top_features = np.argsort(clf.feature_importances_)[::-1][:top]\n feature_names = train.drop(cols_drop, axis = 1).iloc[:, top_features].columns\n \n def plot_features(df1, target = \"action\", features = []):\n i = 0\n sns.set_style(\"whitegrid\")\n plt.figure()\n fig, ax = plt.subplots(4, 2, figsize=(14, 14))\n \n for feature in features:\n i += 1\n plt.subplot(4, 2, i)\n sns.distplot(df1[df1[target]==1][feature].values,label='1')\n sns.distplot(df1[df1[target]==0][feature].values,label='0')\n plt.xlabel(feature, fontsize = 9)\n plt.legend()\n \n plt.savefig(\"./output/58.png\")\n plt.close()\n \n plot_features(train, features = top_features)\n \"\"\"\n # 画特征之间的配对图\n sns.pairplot(train[list(feature_names[:10]) + [\"action\"]], hue = \"action\")\n plt.savefig(\"./output/59.png\")\n plt.close()\n \n # 计算夏普值?\n import shap\n \n explainer = shap.TreeExplainer(clf)\n X = train.drop(cols_drop, axis = 1).fillna(-999).sample(1000)\n shap_values = explainer.shap_values(X)\n shap.summary_plot(shap_values, X, plot_type = \"bar\")\n plt.savefig(\"./output/60.png\")\n plt.close()\n \n shap.dependence_plot(\"feature_35\", shap_values[1], X, display_features = X.sample(1000))\n plt.savefig(\"./output/61.png\")\n plt.close()\n \n \n# 第三篇文章的EDA\n# 参考https://www.kaggle.com/carlmcbrideellis/jane-street-eda-of-day-0-and-feature-importance\ndef EDA3(train, test, feature):\n train_data = train.copy()\n feature_tags = feature.copy()\n \n # 累积收益\n fig, ax = plt.subplots(figsize=(15,5))\n balance= pd.Series(train_data['resp']).cumsum()\n ax.set_xlabel (\"Trade\", fontsize=18)\n ax.set_ylabel (\"Cumulative resp\", fontsize=18);\n balance.plot(lw=3);\n del balance\n plt.savefig(\"./output/62.png\")\n plt.close()\n \n # 四种时间范围,范围越长,越激进,收益也越大。\n fig, ax = plt.subplots(figsize=(15, 5))\n balance= pd.Series(train_data['resp']).cumsum()\n resp_1= pd.Series(train_data['resp_1']).cumsum()\n resp_2= pd.Series(train_data['resp_2']).cumsum()\n resp_3= pd.Series(train_data['resp_3']).cumsum()\n resp_4= pd.Series(train_data['resp_4']).cumsum()\n ax.set_xlabel (\"Trade\", fontsize=18)\n ax.set_title (\"Cumulative resp and time horizons 1, 2, 3, and 4 (500 days)\", fontsize=18)\n balance.plot(lw=3)\n resp_1.plot(lw=3)\n resp_2.plot(lw=3)\n resp_3.plot(lw=3)\n resp_4.plot(lw=3)\n plt.legend(loc=\"upper left\")\n del resp_1\n del resp_2\n del resp_3\n del resp_4\n plt.savefig(\"./output/63.png\")\n plt.close()\n # 可以看出resp与resp_4类似。\n \n # 画所有resp值的柱状图(只显示-0.05-0.05)\n plt.figure(figsize = (12,5))\n ax = sns.distplot(train_data['resp'], \n bins=3000, \n kde_kws={\"clip\":(-0.05,0.05)}, \n hist_kws={\"range\":(-0.05,0.05)},\n color='darkcyan', \n kde=False)\n values = np.array([rec.get_height() for rec in ax.patches])\n norm = plt.Normalize(values.min(), values.max())\n colors = plt.cm.jet(norm(values))\n for rec, col in zip(ax.patches, colors):\n rec.set_color(col)\n plt.xlabel(\"Histogram of the resp values\", size=14)\n del values\n plt.savefig(\"./output/64.png\")\n plt.close()\n \n # 分布是长尾的\n min_resp = train_data['resp'].min()\n print('The minimum value for resp is: %.5f' % min_resp)\n max_resp = train_data['resp'].max()\n print('The maximum value for resp is: %.5f' % max_resp)\n\t# 看这个分布的偏度和峰度\n print(\"Skew of resp is: %.2f\" %train_data['resp'].skew())\n print(\"Kurtosis of resp is: %.2f\" %train_data['resp'].kurtosis())\n\t\n\t# 下面来看weight值\n\t# weight为0的值保留在数据里是为了完整性考虑。这个交易对收益无贡献。\n\t# 看weight为0的比例\n percent_zeros = (100/train_data.shape[0])*((train_data.weight.values == 0).sum())\n print('Percentage of zero weights is: %i' % percent_zeros +\"%\")\n\t# 看有没有负值\n min_weight = train_data['weight'].min()\n print('The minimum weight is: %.2f' % min_weight)\n\t# 最小值为0,没有负值。\n\t# 再来看最大值\n max_weight = train_data['weight'].max()\n print('The maximum weight was: %.2f' % max_weight)\n # 看在哪天 第446天\n print(train_data[train_data['weight']==train_data['weight'].max()])\n\t\n\t# 看非0的weight值的分布\n plt.figure(figsize = (12,5))\n ax = sns.distplot(train_data['weight'], \n bins=1400, \n kde_kws={\"clip\":(0.001,1.4)}, \n hist_kws={\"range\":(0.001,1.4)},\n color='darkcyan', \n kde=False)\n values = np.array([rec.get_height() for rec in ax.patches])\n norm = plt.Normalize(values.min(), values.max())\n colors = plt.cm.jet(norm(values))\n for rec, col in zip(ax.patches, colors):\n rec.set_color(col)\n plt.xlabel(\"Histogram of non-zero weights\", size=14)\n plt.savefig(\"./output/65.png\")\n plt.close()\n del values\n # 有两个峰值,会是两个分布叠加吗?\n\t\n # 画weight值的对数分布\n train_data_nonZero = train_data.query('weight > 0').reset_index(drop = True)\n plt.figure(figsize = (10,4))\n ax = sns.distplot(np.log(train_data_nonZero['weight']), \n bins=1000, \n kde_kws={\"clip\":(-4,5)}, \n hist_kws={\"range\":(-4,5)},\n color='darkcyan', \n kde=False)\n values = np.array([rec.get_height() for rec in ax.patches])\n norm = plt.Normalize(values.min(), values.max())\n colors = plt.cm.jet(norm(values))\n for rec, col in zip(ax.patches, colors):\n rec.set_color(col)\n plt.xlabel(\"Histogram of the logarithm of the non-zero weights\", size=14)\n plt.savefig(\"./output/66.png\")\n plt.close()\n \n # 用高斯分布等来拟合\n from scipy.optimize import curve_fit\n # the values\n x = list(range(len(values)))\n x = [(i/110)-4 for i in x]\n y = values\n\n # define a Gaussian function\n def Gaussian(x,mu,sigma,A):\n \treturn A*np.exp(-0.5 * ((x-mu)/sigma)**2)\n\n def bimodal(x,mu_1,sigma_1,A_1,mu_2,sigma_2,A_2):\n \treturn Gaussian(x,mu_1,sigma_1,A_1) + Gaussian(x,mu_2,sigma_2,A_2)\n\n # seed guess\n initial_guess=(1, 1 , 1, 1, 1, 1)\n\n # the fit\n parameters,covariance=curve_fit(bimodal,x,y,initial_guess)\n sigma=np.sqrt(np.diag(covariance))\n # the plot\n plt.figure(figsize = (10,4))\n ax = sns.distplot(np.log(train_data_nonZero['weight']), bins=1000, kde_kws={\"clip\":(-4,5)},hist_kws={\"range\":(-4,5)}, color='darkcyan', kde=False)\n values = np.array([rec.get_height() for rec in ax.patches])\n norm = plt.Normalize(values.min(), values.max())\n colors = plt.cm.jet(norm(values))\n for rec, col in zip(ax.patches, colors):\n rec.set_color(col)\n plt.xlabel(\"Histogram of the logarithm of the non-zero weights\", size=14)\n # plot gaussian #1\n plt.plot(x,Gaussian(x,parameters[0],parameters[1],parameters[2]),':',color='black',lw=2,label='Gaussian #1', alpha=0.8)\n # plot gaussian #2\n plt.plot(x,Gaussian(x,parameters[3],parameters[4],parameters[5]),'--',color='black',lw=2,label='Gaussian #2', alpha=0.8)\n # plot the two gaussians together\n plt.plot(x,bimodal(x,*parameters),color='black',lw=2, alpha=0.7)\n plt.legend(loc=\"upper left\");\n plt.savefig(\"./output/67.png\")\n plt.close()\n del values\n # 左边的那个峰值似乎是其它分布的。\n\t\n # 累积回报\n # weight和resp的和构成收益。\n train_data['weight_resp'] = train_data['weight']*train_data['resp']\n train_data['weight_resp_1'] = train_data['weight']*train_data['resp_1']\n train_data['weight_resp_2'] = train_data['weight']*train_data['resp_2']\n train_data['weight_resp_3'] = train_data['weight']*train_data['resp_3']\n train_data['weight_resp_4'] = train_data['weight']*train_data['resp_4']\n fig, ax = plt.subplots(figsize=(15, 5))\n resp = pd.Series(1+(train_data.groupby('date')['weight_resp'].mean())).cumprod()\n resp_1 = pd.Series(1+(train_data.groupby('date')['weight_resp_1'].mean())).cumprod()\n resp_2 = pd.Series(1+(train_data.groupby('date')['weight_resp_2'].mean())).cumprod()\n resp_3 = pd.Series(1+(train_data.groupby('date')['weight_resp_3'].mean())).cumprod()\n resp_4 = pd.Series(1+(train_data.groupby('date')['weight_resp_4'].mean())).cumprod()\n ax.set_xlabel (\"Day\", fontsize=18)\n ax.set_title (\"Cumulative daily return for resp and time horizons 1, 2, 3, and 4 (500 days)\", fontsize=18)\n resp.plot(lw=3, label='resp x weight')\n resp_1.plot(lw=3, label='resp_1 x weight')\n resp_2.plot(lw=3, label='resp_2 x weight')\n resp_3.plot(lw=3, label='resp_3 x weight')\n resp_4.plot(lw=3, label='resp_4 x weight')\n # day 85 marker\n ax.axvline(x=85, linestyle='--', alpha=0.3, c='red', lw=1)\n ax.axvspan(0, 85 , color=sns.xkcd_rgb['grey'], alpha=0.1)\n plt.legend(loc=\"lower left\");\n plt.savefig(\"./output/68.png\")\n plt.close()\n # 对于较短期的策略,resp_1 - resp_3,收益较低。\n \n # 现在画weight和resp之积(排除weight=0的)\n train_data_no_0 = train_data.query('weight > 0').reset_index(drop = True)\n train_data_no_0['wAbsResp'] = train_data_no_0['weight'] * (train_data_no_0['resp'])\n #plot\n plt.figure(figsize = (12,5))\n ax = sns.distplot(train_data_no_0['wAbsResp'], \n bins=1500, \n kde_kws={\"clip\":(-0.02,0.02)}, \n hist_kws={\"range\":(-0.02,0.02)},\n color='darkcyan', \n kde=False)\n values = np.array([rec.get_height() for rec in ax.patches])\n norm = plt.Normalize(values.min(), values.max())\n colors = plt.cm.jet(norm(values))\n for rec, col in zip(ax.patches, colors):\n \trec.set_color(col)\n plt.xlabel(\"Histogram of the weights * resp\", size=14)\n plt.savefig(\"./output/69.png\")\n plt.close()\n \n # 时间\n # 画每天的ts_id数量\n trades_per_day = train_data.groupby(['date'])['ts_id'].count()\n fig, ax = plt.subplots(figsize=(15, 5))\n plt.plot(trades_per_day)\n ax.set_xlabel (\"Day\", fontsize=18)\n ax.set_title (\"Total number of ts_id for each day\", fontsize=18)\n # day 85 marker\n ax.axvline(x=85, linestyle='--', alpha=0.3, c='red', lw=1)\n ax.axvspan(0, 85 , color=sns.xkcd_rgb['grey'], alpha=0.1)\n ax.set_xlim(xmin=0)\n ax.set_xlim(xmax=500)\n plt.savefig(\"./output/70.png\")\n plt.close()\n # 在85天那里画了线,是想看85天之后是否改变了交易策略。\n \n # 假设每个交易日6.5小时,看平均每天的交易次数\n fig, ax = plt.subplots(figsize=(15, 5))\n plt.plot(23400/trades_per_day)\n ax.set_xlabel (\"Day\", fontsize=18)\n ax.set_ylabel (\"Av. time between trades (s)\", fontsize=18)\n ax.set_title (\"Average time between trades for each day\", fontsize=18)\n ax.axvline(x=85, linestyle='--', alpha=0.3, c='red', lw=1)\n ax.axvspan(0, 85 , color=sns.xkcd_rgb['grey'], alpha=0.1)\n ax.set_xlim(xmin=0)\n ax.set_xlim(xmax=500)\n ax.set_ylim(ymin=0)\n ax.set_ylim(ymax=12)\n plt.savefig(\"./output/71.png\")\n plt.close()\n \n # 每个交易日的交易次数的分布\n plt.figure(figsize = (12,4))\n # the minimum has been set to 1000 so as not to draw the partial days like day 2 and day 294\n # the maximum number of trades per day is 18884\n # I have used 125 bins for the 500 days\n ax = sns.distplot(trades_per_day, \n bins=125, \n kde_kws={\"clip\":(1000,20000)}, \n hist_kws={\"range\":(1000,20000)},\n color='darkcyan', \n kde=True)\n values = np.array([rec.get_height() for rec in ax.patches])\n norm = plt.Normalize(values.min(), values.max())\n colors = plt.cm.jet(norm(values))\n for rec, col in zip(ax.patches, colors):\n rec.set_color(col)\n plt.xlabel(\"Number of trades per day\", size=14)\n plt.savefig(\"./output/72.png\")\n plt.close()\n # 注意到feature_64看起来像某类每日时钟\n \n # 来探索特征\n # feature_0很特别,全是1和-1\n print(train_data['feature_0'].value_counts())\n # feature_0是在features.csv中唯一有非True标签的特征\n fig, ax = plt.subplots(figsize=(15, 4))\n feature_0 = pd.Series(train_data['feature_0']).cumsum()\n ax.set_xlabel (\"Trade\", fontsize=18)\n ax.set_ylabel (\"feature_0 (cumulative)\", fontsize=18)\n feature_0.plot(lw=3)\n plt.savefig(\"./output/73.png\")\n plt.close()\n \n # 单独画feature_0 = 1和-1时的累计收益\n feature_0_is_plus_one = train_data.query('feature_0 == 1').reset_index(drop = True)\n feature_0_is_minus_one = train_data.query('feature_0 == -1').reset_index(drop = True)\n # the plot\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 4))\n ax1.plot((pd.Series(feature_0_is_plus_one['resp']).cumsum()), lw=3, label='resp')\n ax1.plot((pd.Series(feature_0_is_plus_one['resp']*feature_0_is_plus_one['weight']).cumsum()), lw=3, label='return')\n ax2.plot((pd.Series(feature_0_is_minus_one['resp']).cumsum()), lw=3, label='resp')\n ax2.plot((pd.Series(feature_0_is_minus_one['resp']*feature_0_is_minus_one['weight']).cumsum()), lw=3, label='return')\n ax1.set_title (\"feature 0 = 1\", fontsize=18)\n ax2.set_title (\"feature 0 = -1\", fontsize=18)\n ax1.legend(loc=\"lower left\")\n ax2.legend(loc=\"upper left\");\n plt.savefig(\"./output/74.png\")\n plt.close()\n del feature_0_is_plus_one\n del feature_0_is_minus_one\n # 两种不同的收益情况。\n\t\n # 看起来有四种不同的特征,各用一个例子画出来。\n fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2,figsize=(20,10))\n ax1.plot((pd.Series(train_data['feature_1']).cumsum()), lw=3, color='red')\n ax1.set_title (\"Linear\", fontsize=22)\n ax1.axvline(x=514052, linestyle='--', alpha=0.3, c='green', lw=2)\n ax1.axvspan(0, 514052 , color=sns.xkcd_rgb['grey'], alpha=0.1)\n ax1.set_xlim(xmin=0)\n ax1.set_ylabel (\"feature_1\", fontsize=18)\n\n ax2.plot((pd.Series(train_data['feature_3']).cumsum()), lw=3, color='green')\n ax2.set_title (\"Noisy\", fontsize=22)\n ax2.axvline(x=514052, linestyle='--', alpha=0.3, c='red', lw=2)\n ax2.axvspan(0, 514052 , color=sns.xkcd_rgb['grey'], alpha=0.1)\n ax2.set_xlim(xmin=0)\n ax2.set_ylabel (\"feature_3\", fontsize=18)\n\n ax3.plot((pd.Series(train_data['feature_55']).cumsum()), lw=3, color='darkorange')\n ax3.set_title (\"Hybryd (Tag 21)\", fontsize=22);\n ax3.set_xlabel (\"Trade\", fontsize=18)\n ax3.axvline(x=514052, linestyle='--', alpha=0.3, c='green', lw=2)\n ax3.axvspan(0, 514052 , color=sns.xkcd_rgb['grey'], alpha=0.1)\n ax3.set_xlim(xmin=0)\n ax3.set_ylabel (\"feature_55\", fontsize=18)\n\n ax4.plot((pd.Series(train_data['feature_73']).cumsum()), lw=3, color='blue')\n ax4.set_title (\"Negative\", fontsize=22)\n ax4.set_xlabel (\"Trade\", fontsize=18)\n ax4.set_ylabel (\"feature_73\", fontsize=18)\n\t\n plt.savefig(\"./output/75.png\")\n plt.close()\n \n # 标签14很有趣,其特征在整个交易日内只有离散值。(是股票价格吗?)\n # 画散点图看看\n day_0 = train_data.loc[train_data['date'] == 0]\n day_1 = train_data.loc[train_data['date'] == 1]\n day_3 = train_data.loc[train_data['date'] == 3]\n three_days = pd.concat([day_0, day_1, day_3])\n three_days.plot.scatter(x='ts_id', y='feature_41', s=0.5, figsize=(15,3))\n three_days.plot.scatter(x='ts_id', y='feature_42', s=0.5, figsize=(15,3))\n three_days.plot.scatter(x='ts_id', y='feature_43', s=0.5, figsize=(15,3))\n #del day_0\n del day_1\n del day_3\n plt.savefig(\"./output/76.png\")\n plt.close()\n \n # 延迟画图(不知道啥意思)\n from pandas.plotting import lag_plot\n fig, ax = plt.subplots(1, 3, figsize=(17, 4))\n lag_plot(day_0['feature_41'], lag=1, s=0.5, ax=ax[0])\n lag_plot(day_0['feature_42'], lag=1, s=0.5, ax=ax[1])\n lag_plot(day_0['feature_43'], lag=1, s=0.5, ax=ax[2])\n ax[0].title.set_text('feature_41')\n ax[0].set_xlabel(\"ts_id (n)\")\n ax[0].set_ylabel(\"ts_id (n+1)\")\n ax[1].title.set_text('feature_42')\n ax[1].set_xlabel(\"ts_id (n)\")\n ax[1].set_ylabel(\"ts_id (n+1)\")\n ax[2].title.set_text('feature_43')\n ax[2].set_xlabel(\"ts_id (n)\")\n ax[2].set_ylabel(\"ts_id (n+1)\")\n\n ax[0].plot(0, 0, 'r.', markersize=15.0)\n ax[1].plot(0, 0, 'r.', markersize=15.0)\n ax[2].plot(0, 0, 'r.', markersize=15.0)\n\t\n plt.savefig(\"./output/77.png\")\n plt.close()\n \n # Tag22 特征60-68\n fig, ax = plt.subplots(figsize=(15, 5))\n feature_60= pd.Series(train_data['feature_60']).cumsum()\n feature_61= pd.Series(train_data['feature_61']).cumsum()\n feature_62= pd.Series(train_data['feature_62']).cumsum()\n feature_63= pd.Series(train_data['feature_63']).cumsum()\n feature_64= pd.Series(train_data['feature_64']).cumsum()\n feature_65= pd.Series(train_data['feature_65']).cumsum()\n feature_66= pd.Series(train_data['feature_66']).cumsum()\n feature_67= pd.Series(train_data['feature_67']).cumsum()\n feature_68= pd.Series(train_data['feature_68']).cumsum()\n #feature_69= pd.Series(train_data['feature_69']).cumsum()\n ax.set_xlabel (\"Trade\", fontsize=18)\n ax.set_title (\"Cumulative plot for feature_60 ... feature_68 (Tag 22).\", fontsize=18)\n feature_60.plot(lw=3)\n feature_61.plot(lw=3)\n feature_62.plot(lw=3)\n feature_63.plot(lw=3)\n feature_64.plot(lw=3)\n feature_65.plot(lw=3)\n feature_66.plot(lw=3)\n feature_67.plot(lw=3)\n feature_68.plot(lw=3)\n #feature_69.plot(lw=3)\n plt.legend(loc=\"upper left\")\n del feature_60, feature_61, feature_62, feature_63, feature_64, feature_65, feature_66 ,feature_67, feature_68\n plt.savefig(\"./output/78.png\")\n plt.close()\n # 可以看到这些特征很相似。\n # 现在画直方图看看分布\n sns.set_palette(\"bright\")\n fig, axes = plt.subplots(2,2,figsize=(8,8))\n sns.distplot(train_data[['feature_60']], hist=True, bins=200, ax=axes[0,0])\n sns.distplot(train_data[['feature_61']], hist=True, bins=200, ax=axes[0,0])\n axes[0,0].set_title (\"features 60 and 61\", fontsize=18)\n axes[0,0].legend(labels=['60', '61'])\n sns.distplot(train_data[['feature_62']], hist=True, bins=200, ax=axes[0,1])\n sns.distplot(train_data[['feature_63']], hist=True, bins=200, ax=axes[0,1])\n axes[0,1].set_title (\"features 62 and 63\", fontsize=18)\n axes[0,1].legend(labels=['62', '63'])\n sns.distplot(train_data[['feature_65']], hist=True, bins=200, ax=axes[1,0])\n sns.distplot(train_data[['feature_66']], hist=True, bins=200, ax=axes[1,0])\n axes[1,0].set_title (\"features 65 and 66\", fontsize=18)\n axes[1,0].legend(labels=['65', '66'])\n sns.distplot(train_data[['feature_67']], hist=True, bins=200, ax=axes[1,1])\n sns.distplot(train_data[['feature_68']], hist=True, bins=200, ax=axes[1,1])\n axes[1,1].set_title (\"features 67 and 68\", fontsize=18)\n axes[1,1].legend(labels=['67', '68'])\n plt.savefig(\"./output/79.png\")\n plt.close()\n \n # 它们之间是feature_64\n plt.figure(figsize = (12,5))\n ax = sns.distplot(train_data['feature_64'], \n bins=1200, \n kde_kws={\"clip\":(-6,6)}, \n hist_kws={\"range\":(-6,6)},\n color='darkcyan', \n kde=False)\n values = np.array([rec.get_height() for rec in ax.patches])\n norm = plt.Normalize(values.min(), values.max())\n colors = plt.cm.jet(norm(values))\n for rec, col in zip(ax.patches, colors):\n \trec.set_color(col)\n plt.xlabel(\"Histogram of feature_64\", size=14)\n plt.savefig(\"./output/80.png\")\n plt.close()\n del values\n # 在0.7-1.38之间有间隙,像是(ln(2)=0.693, ln(4)=1.386)\n\t\n # Tag22还有很明显的每天的间隔,如feature64\n day_0 = train_data.loc[train_data['date'] == 0]\n\t\n day_1 = train_data.loc[train_data['date'] == 1]\n day_3 = train_data.loc[train_data['date'] == 3]\n three_days = pd.concat([day_0, day_1, day_3])\n\n # plot\n fig, ax = plt.subplots(2, 1, figsize=(15, 6), sharex=True)\n ax[0].scatter(three_days.ts_id, three_days.feature_64, s=0.5, color='b')\n ax[0].set_xlabel('')\n ax[0].set_ylabel('value')\n ax[0].set_title('feature_64 (days 0, 1 and 3)')\n ax[1].scatter(three_days.ts_id, pd.Series(three_days['feature_64']).cumsum(), s=0.5, color='r')\n ax[1].set_xlabel('ts_id')\n ax[1].set_ylabel('cumulative sum')\n ax[1].set_title('')\n plt.savefig(\"./output/81.png\")\n plt.close()\n # feature_64的全局最小值为-6.4,全局最大值为8,猜测其单位是30分钟\n # 用arcsin试试\n x = np.arange(-1, 1, 0.01)\n y = 2*np.arcsin(x)+1\n fig, ax = plt.subplots(1, 1, figsize=(7,4))\n ax.plot(x, y, lw=3)\n ax.set(xticklabels = [])\n ax.set(yticklabels = ['9:00','10:00','11:00','12:00','13:00','14:00','15:00' ,'16:00'])\n ax.set_title(\"2$\\it{arcsin}$(x) +1\", fontsize=18)\n plt.savefig(\"./output/82.png\")\n plt.close()\n\t\n # 再画feature_65看看\n three_days.plot.scatter(x='ts_id', y='feature_65', s=0.5, figsize=(15,4))\n\t\n # 再来看“Noisy”特征\n fig, ax = plt.subplots(figsize=(15, 5))\n feature_3= pd.Series(train_data['feature_3']).cumsum()\n feature_4= pd.Series(train_data['feature_4']).cumsum()\n feature_5= pd.Series(train_data['feature_5']).cumsum()\n feature_6= pd.Series(train_data['feature_6']).cumsum()\n ax.set_xlabel (\"Trade\", fontsize=18)\n ax.set_title (\"Cumulative plot for features 3, 4, 5 and 6\", fontsize=18)\n ax.axvline(x=514052, linestyle='--', alpha=0.3, c='black', lw=1)\n ax.axvspan(0, 514052, color=sns.xkcd_rgb['grey'], alpha=0.1)\n #ax.set_xlim(xmin=0)\n feature_3.plot(lw=3)\n feature_4.plot(lw=3)\n feature_5.plot(lw=3)\n feature_6.plot(lw=3)\n plt.legend(loc=\"upper left\")\n plt.savefig(\"./output/83.png\")\n plt.close()\n \n # Tag19 feature_51\n fig, ax = plt.subplots(figsize=(15, 4))\n ax.scatter(train_data_nonZero.weight, train_data_nonZero.feature_51, s=0.1, color='b')\n ax.set_xlabel('weight')\n ax.set_ylabel('feature_51')\n plt.savefig(\"./output/84.png\")\n plt.close()\n\t\n # Tag19 feature_52\n fig, ax = plt.subplots(figsize=(15, 3))\n feature_0 = pd.Series(train_data['feature_52']).cumsum()\n ax.set_xlabel (\"ts_id\", fontsize=18)\n ax.set_ylabel (\"feature_52 (cumulative)\", fontsize=12)\n feature_0.plot(lw=3)\n plt.savefig(\"./output/84.png\")\n plt.close()\n\t\n # 延迟画图\n fig, ax = plt.subplots(1,1, figsize=(4, 4))\n lag_plot(day_0['feature_52'], s=0.5, ax=ax)\n ax.title.set_text('feature_52')\n ax.set_xlabel(\"ts_id (n)\")\n ax.set_ylabel(\"ts_id (n+1)\")\n ax.plot(0, 0, 'r.', markersize=15.0)\n plt.savefig(\"./output/85.png\")\n plt.close()\n\t\n # \"Negative\"特征\n fig, ax = plt.subplots(figsize=(15, 5))\n feature_55= pd.Series(train_data['feature_55']).cumsum()\n feature_56= pd.Series(train_data['feature_56']).cumsum()\n feature_57= pd.Series(train_data['feature_57']).cumsum()\n feature_58= pd.Series(train_data['feature_58']).cumsum()\n feature_59= pd.Series(train_data['feature_59']).cumsum()\n ax.set_xlabel (\"Trade\", fontsize=18)\n ax.set_title (\"Cumulative plot for the 'Tag 21' features (55-59)\", fontsize=18)\n ax.axvline(x=514052, linestyle='--', alpha=0.3, c='black', lw=1)\n ax.axvspan(0, 514052, color=sns.xkcd_rgb['grey'], alpha=0.1)\n feature_55.plot(lw=3)\n feature_56.plot(lw=3)\n feature_57.plot(lw=3)\n feature_58.plot(lw=3)\n feature_59.plot(lw=3)\n plt.legend(loc=\"upper left\")\n plt.savefig(\"./output/86.png\")\t\n plt.close()\n\t\n # 再来看看features.csv\n # 先画图\n #plt.figure(figsize=(32,14))\n# sns.heatmap(feature_tags.T)\n# plt.savefig(\"./output/87.png\")\n# plt.close()\n\t\n # 看看标签总数\n tag_sum = pd.DataFrame(feature_tags.T.sum(axis=0),columns=['Number of tags'])\n print(tag_sum.T)\n # 可以看到所有特征都有至少一个标签,一些有4个。feature_0没有标签\n\t\n # 下面看Action\n # 先增加该列\n train_data['action'] = ((train_data['resp'])>0)*1\n # 看看统计情况\n print(train_data[\"action\"].value_counts())\n # 行动比不行动稍微好一点:0.4%,看看每天的情况\n daily_action_sum = train_data['action'].groupby(train_data['date']).sum()\n daily_action_count = train_data['action'].groupby(train_data['date']).count()\n daily_ratio = daily_action_sum/daily_action_count\n # now plot\n fig, ax = plt.subplots(figsize=(15, 5))\n plt.plot(daily_ratio)\n ax.set_xlabel (\"Day\", fontsize=18)\n ax.set_ylabel (\"ratio\", fontsize=18)\n ax.set_title (\"Daily ratio of action to inaction\", fontsize=18)\n plt.axhline(0.5, linestyle='--', alpha=0.85, c='r');\n ax.set_xlim(xmin=0)\n ax.set_xlim(xmax=500)\n plt.savefig(\"./output/88.png\")\n plt.close()\n\t\n # 分布非常均匀,没有特别的模式。\n daily_ratio_mean = daily_ratio.mean()\n print('The mean daily ratio is %.3f' % daily_ratio_mean)\n daily_ratio_max = daily_ratio.max()\n print('The maximum daily ratio is %.3f' % daily_ratio_max)\n\t\n # 现在来看看第0天\n day_0 = train_data.loc[train_data[\"date\"] == 0]\n fig, ax = plt.subplots(figsize=(15, 5))\n balance= pd.Series(day_0['resp']).cumsum()\n resp_1= pd.Series(day_0['resp_1']).cumsum()\n resp_2= pd.Series(day_0['resp_2']).cumsum()\n resp_3= pd.Series(day_0['resp_3']).cumsum()\n resp_4= pd.Series(day_0['resp_4']).cumsum()\n ax.set_xlabel (\"Trade\", fontsize=18)\n ax.set_title (\"Cumulative values for resp and time horizons 1, 2, 3, and 4 for day 0\", fontsize=18)\n balance.plot(lw=3)\n resp_1.plot(lw=3)\n resp_2.plot(lw=3)\n resp_3.plot(lw=3)\n resp_4.plot(lw=3)\n plt.legend(loc=\"upper left\")\n plt.savefig(\"./output/89.png\")\n plt.close()\n\t\n # 第0天的train.csv数据的统计学描述\n print(day_0.describe())\n\t\n # 看缺失值\n import missingno as msno\n msno.matrix(day_0, color=(0.35, 0.35, 0.75))\n plt.savefig(\"./output/90.png\")\n plt.close()\n \n feats_7_11 = day_0.iloc[:, [14,18]]\n msno.matrix(feats_7_11, color=(0.35, 0.35, 0.75), width_ratios=(1, 3))\n plt.savefig(\"./output/91.png\")\n plt.close()\n # 可以看到缺失值并不是随机分布的,中间有大段缺失值。\n\t\n # 下面看所有列的缺失值信息\n gone = train_data.isnull().sum()\n px.bar(gone, color=gone.values, title=\"Total number of missing values for each column\").write_image(\"./output/92.png\")\n # 79.6%的缺失值在Tag4组,代表resp_1特征\n # 15.2%的缺失值在Tag3组,代表resp_2特征\n # 上述两者包括了大于95%的缺失数据。\n # 很多特征有相同数量的缺失值。\n # 画图看看\n missing_features = train_data.iloc[:,7:137].isnull().sum(axis=1).groupby(train_data['date']).sum().to_frame()\n # now make a plot\n fig, ax = plt.subplots(figsize=(15, 5))\n plt.plot(missing_features)\n ax.set_xlabel (\"Day\", fontsize=18)\n ax.set_title (\"Total number of missing values in all features for each day\", fontsize=18)\n ax.axvline(x=85, linestyle='--', alpha=0.3, c='red', lw=2)\n ax.axvspan(0, 85, color=sns.xkcd_rgb['grey'], alpha=0.1)\n ax.set_xlim(xmin=0)\n ax.set_xlim(xmax=500)\n plt.savefig(\"./output/93.png\")\n plt.close()\n \n # 画每个交易的平均缺失特征数量\n count_weights = train_data[['date', 'weight']].groupby('date').agg(['count'])\n result = pd.merge(count_weights, missing_features, on = \"date\", how = \"inner\")\n result.columns = ['weights','missing']\n result['ratio'] = result['missing']/result['weights']\n missing_per_trade = result['ratio'].mean()\n\n # now make a plot\n fig, ax = plt.subplots(figsize=(15, 5))\n plt.plot(result['ratio'])\n plt.axhline(missing_per_trade, linestyle='--', alpha=0.85, c='r');\n ax.set_xlabel (\"Day\", fontsize=18)\n ax.set_title (\"Average number of missing feature values per trade, for each day\", fontsize=18)\n plt.savefig(\"./output/94.png\")\n plt.close()\n # 平均每个交易约有3个缺失特征。\n \n # 采用持续重要性计算(permutation importance calculation)\n X_train = day_0.loc[:, day_0.columns.str.contains('feature')]\n X_train = X_train.fillna(X_train.mean())\n # our target is the action\n y_train = day_0['resp']\n\n from sklearn.ensemble import RandomForestRegressor\n regressor = RandomForestRegressor(max_features='auto')\n regressor.fit(X_train, y_train)\n\n\n\nif __name__ == \"__main__\":\n # newpath = \"/home/code\"\n # os.chdir(newpath)\n\n \n # 真正开始干活\n data_explore()\n","repo_name":"zwdnet/JSMPwork","sub_path":"EDA.py","file_name":"EDA.py","file_ext":"py","file_size_in_byte":67839,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"77"}
+{"seq_id":"72343326009","text":"from typing import NamedTuple, Any, Iterator, Tuple, Dict\n\n\nimport string\nfrom types import SimpleNamespace\n\nimport pytest\n\nimport hypothesis.strategies as st\nfrom hypothesis import given\n\nfrom collectionish import AttyDict\nfrom collectionish.utils import is_valid_identifier, is_mapping\nfrom collectionish.ops import rgetattr, flatten_mapping\n\npy_names = st.text(string.ascii_lowercase + '_').filter(is_valid_identifier)\n\n\nclass Pair(NamedTuple):\n\n path: Tuple[str]\n value: Any\n\n\nclass Thing(SimpleNamespace):\n @classmethod\n def from_dict(cls, dct: Dict[str, Any]) -> 'Thing':\n kwargs = {}\n for k, v in dct.items():\n if is_mapping(v):\n kwargs[k] = cls.from_dict(v)\n else:\n kwargs[k] = v\n return cls(**kwargs)\n\n def paths(self, prefix=tuple([])) -> Iterator[Pair]:\n yield Pair(prefix, self)\n for k, v in self.__dict__.items():\n if isinstance(v, self.__class__):\n for path, v in v.paths(prefix + (k,)):\n yield Pair(path, v)\n else:\n yield Pair(prefix + (k,), v)\n\n\nthings = st.builds(\n Thing.from_dict, st.dictionaries(keys=py_names, values=st.text(string.ascii_lowercase))\n)\n\n\n@given(things)\ndef test_rgetattr(thing):\n for path, value in thing.paths():\n assert rgetattr(thing, *path) == value\n\n\n@given(things, st.data())\ndef test_rgetattr_raises_on_invalid(thing, data):\n path, _ = data.draw(st.sampled_from(list(thing.paths())))\n with pytest.raises(AttributeError):\n rgetattr(thing, *path, 'bullshit')\n\n\ndef test_flatten_attydict_with_keeptype_and_dot_delim_raises_error():\n attydict = AttyDict(this={'nested': {'number': 1, 'name': 'teddy'}}, other=2)\n expect_msg = (\n 'cannot use dot delimiter with AttyDict'\n ' try specifying a different delimiter such as an underscore'\n ' or set keep_type to False to return a regular dict.'\n )\n with pytest.raises(TypeError, match=expect_msg):\n flatten_mapping(attydict, keep_type=True)\n\n\ndef test_flatten_attydict_with_keeptype_and_underscore_delim_is_fine():\n attydict = AttyDict(this={'nested': {'number': 1, 'name': 'teddy'}}, other=2)\n flat = flatten_mapping(attydict, keep_type=True, delimiter='_')\n assert isinstance(flat, AttyDict)\n assert flat == AttyDict(this_nested_number=1, this_nested_name='teddy', other=2)\n","repo_name":"leaprovenzano/collectionish","sub_path":"tests/test_ops.py","file_name":"test_ops.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"27698082045","text":"import numpy as np\nimport matplotlib.pylab as plt\nimport utils\nimport matplotlib as mpl\nimport pandas as pd\nimport dask.dataframe as dd\nfrom satellites_forMC import *\nfrom plots import hists, plot_sizefunctions_MonteCarlo\nfrom multiprocessing import Pool\nmpl.use('Agg')\nmpl.rcParams['xtick.minor.visible']=True\nmpl.rcParams['font.size']=45\nmpl.rcParams['figure.figsize']=(16,16)\n#mpl.rcParams['xtick.minor.visible']=True\nmpl.rcParams['axes.linewidth']= 3.\nmpl.rcParams['axes.titlepad'] = 20\n#plt.rcParams['axes.linewidth']=5\nplt.rcParams['xtick.major.size'] =15\nplt.rcParams['ytick.major.size'] =15\nplt.rcParams['xtick.minor.size'] =10\nplt.rcParams['ytick.minor.size'] =10\nplt.rcParams['xtick.major.width'] =5\nplt.rcParams['ytick.major.width'] =5\nplt.rcParams['xtick.minor.width'] =5\nplt.rcParams['ytick.minor.width'] =5 \nmpl.rcParams['axes.titlepad'] = 20 \n\n\n\ndef run_satellites(Nboot, massrange, dict_SMHM,scatterevol,mu,zinfallrange,ax,ax1,ax2,HostHaloMassRange=None, HostHaloMassRange_axes=None):\n\n rebins = np.arange(-0.2,2.5,0.1)\n \n dimensions = (Nboot, len(rebins)-1)\n hcen = np.zeros(dimensions)\n hsat = {'all':np.zeros(dimensions),'highz':np.zeros(dimensions),'medz':np.zeros(dimensions),'lowz':np.zeros(dimensions)}\n hsat_highmass = {'all':np.zeros(dimensions),'highz':np.zeros(dimensions),'medz':np.zeros(dimensions),'lowz':np.zeros(dimensions)}\n hsat_medmass = {'all':np.zeros(dimensions),'highz':np.zeros(dimensions),'medz':np.zeros(dimensions),'lowz':np.zeros(dimensions)}\n hsat_lowmass = {'all':np.zeros(dimensions),'highz':np.zeros(dimensions),'medz':np.zeros(dimensions),'lowz':np.zeros(dimensions)}\n\n hcen_SF = np.zeros(dimensions)\n hsat_SF = {'all':np.zeros(dimensions),'highz':np.zeros(dimensions),'medz':np.zeros(dimensions),'lowz':np.zeros(dimensions)}\n hsat_highmass_SF = {'all':np.zeros(dimensions),'highz':np.zeros(dimensions),'medz':np.zeros(dimensions),'lowz':np.zeros(dimensions)}\n hsat_medmass_SF = {'all':np.zeros(dimensions),'highz':np.zeros(dimensions),'medz':np.zeros(dimensions),'lowz':np.zeros(dimensions)}\n hsat_lowmass_SF = {'all':np.zeros(dimensions),'highz':np.zeros(dimensions),'medz':np.zeros(dimensions),'lowz':np.zeros(dimensions)}\n\n hcen_Q = np.zeros(dimensions)\n hsat_Q = {'all':np.zeros(dimensions),'highz':np.zeros(dimensions),'medz':np.zeros(dimensions),'lowz':np.zeros(dimensions)}\n hsat_highmass_Q = {'all':np.zeros(dimensions),'highz':np.zeros(dimensions),'medz':np.zeros(dimensions),'lowz':np.zeros(dimensions)}\n hsat_medmass_Q = {'all':np.zeros(dimensions),'highz':np.zeros(dimensions),'medz':np.zeros(dimensions),'lowz':np.zeros(dimensions)}\n hsat_lowmass_Q = {'all':np.zeros(dimensions),'highz':np.zeros(dimensions),'medz':np.zeros(dimensions),'lowz':np.zeros(dimensions)}\n \n ###### to do: bins of parent halo mass\n \n for n in range(Nboot):\n print(n)\n df_high = make.make_censat(dict_SMHM=dict_SMHM,scatterevol=scatterevol,Mstar_low=massrange[0], Mstar_up=massrange[1], mu=mu, AK=0.013,sigmaK=0.1, AK_SF=0.022, sigmaK_SF=0.13, M0=2.)\n print()\n hcen[n], hsat['all'][n],hsat['highz'][n], hsat['medz'][n], hsat['lowz'][n] = hists(df_high, binsR=rebins, zinfallrange=zinfallrange)\n \n hcen_SF[n], hsat_SF['all'][n],hsat_SF['highz'][n], hsat_SF['medz'][n], hsat_SF['lowz'][n] = hists(df_high[df_high['TType']=='LTGs'], binsR=rebins,zinfallrange=zinfallrange)\n \n hcen_Q[n], hsat_Q['all'][n],hsat_Q['highz'][n], hsat_Q['medz'][n], hsat_Q['lowz'][n] = hists(df_high[df_high['TType']=='ETGs'], binsR=rebins,zinfallrange=zinfallrange)\n \n if HostHaloMassRange is not None: #REMEMBER TO ADD MPEAK CEN\n \n ############### star forming\n \n _,hsat_highmass_SF['all'][n],hsat_highmass_SF['highz'][n], hsat_highmass_SF['medz'][n], hsat_highmass_SF['lowz'][n] = hists(df_high.query(\" mvir_host>{} & TType=='LTGs'\".format(HostHaloMassRange[2])), binsR=rebins, zinfallrange=zinfallrange)\n \n _,hsat_medmass_SF['all'][n],hsat_medmass_SF['highz'][n], hsat_medmass_SF['medz'][n], hsat_medmass_SF['lowz'][n] = hists(df_high.query(\" {}{} & TType=='ETGs'\".format(HostHaloMassRange[2])), binsR=rebins, zinfallrange=zinfallrange)\n \n _,hsat_medmass_Q['all'][n],hsat_medmass_Q['highz'][n], hsat_medmass_Q['medz'][n], hsat_medmass_Q['lowz'][n] = hists(df_high.query(\" {}{}'.format(HostHaloMassRange[2])), binsR=rebins, zinfallrange=zinfallrange)\n \n _,hsat_medmass['all'][n],hsat_medmass['highz'][n], hsat_medmass['medz'][n], hsat_medmass['lowz'][n] = hists(df_high.query(' {}$'+str(HaloMassRange[2])]\n \n for a,lab in zip(ax,labels):\n a.set_title(lab)\n \n fig.savefig('./Pictures/fquench/Sizefunct_HaloMassRange_{}_MPeak_{}_{}_mu{}.png'.format(m,string,TType,mu), bbox_inches='tight')\n fig.clf() \n \n \n else:\n \n fig.tight_layout()\n fig.suptitle(str(massrange[0])+r'$<\\log{M_{\\rm star}}/M_\\odot<$'+str(massrange[1]),y=1.05)\n # plt.text(2,4.e-7,'satellites\\ninitialized\\nat peak mass')\n plt.xlim(0.,3)\n plt.ylim(5.e-9)\n fig.savefig('./Pictures/all/Sizefunct_{}_MPeak_{}.png'.format(m,string),bbox_inches='tight')\n fig.clf()\n \n \nif __name__=='__main__':\n \n \n for mu in [1.,2.]:\n for gamma11 in [None, 0,0.1]:\n for scatterevol in [True, False]:\n Nboot = 10\n make = make_satellites(use_peak=True) #initializes everything within the class\n\n # run parameters\n\n dict_SMHM = dict(gamma10=0.57, gamma11= gamma11, beta10=None, beta11=None,\\\n M10=11.95, SHMnorm10=None, M11=None, SHMnorm11=None) \n #scatterevol = False\n # mu = 2.5\n\n zinfallrange = [1,1.5,1.5]\n\n massrange = [11.2,12]\n m = 11.6\n fig, ax = plt.subplots(1,1)\n fig1,(ax1,ax2) = plt.subplots(1,2, figsize=(32,16), sharey=True)\n figSF,axSF = plt.subplots(1,3, figsize=(48,16), sharey=True)\n figQ,axQ = plt.subplots(1,3, figsize=(48,16), sharey=True)\n HaloMassRange = [12.5,13.3,14]\n print()\n ax,ax1,ax2, axSF, axQ = run_satellites(Nboot, massrange, dict_SMHM,scatterevol,mu,zinfallrange,ax,ax1,ax2,HaloMassRange, HostHaloMassRange_axes = [axSF,axQ])\n\n save(fig, ax, massrange, dict_SMHM, scatterevol)\n save(fig1, [ax1,ax2], massrange, dict_SMHM, scatterevol, choice='fquench')\n save(figSF, axSF,massrange,dict_SMHM, scatterevol, choice='fquench', HaloMassRange=HaloMassRange, TType='LTGs' )\n save(figQ, axQ,massrange,dict_SMHM, scatterevol, choice='fquench', HaloMassRange=HaloMassRange, TType='ETGs' )\n raise ValueError\n \n Nboot = 10\n make = make_satellites(use_peak=True) #initializes everything within the class\n\n # run parameters\n \n dict_SMHM = dict(gamma10=0.57, gamma11= None, beta10=None, beta11=None,\\\n M10=11.95, SHMnorm10=None, M11=None, SHMnorm11=None) \n scatterevol = False\n mu = 2.5\n \n zinfallrange = [1,1.5,1.5]\n \n massrange = [11.2,12]\n m = 11.6\n fig, ax = plt.subplots(1,1)\n fig1,(ax1,ax2) = plt.subplots(1,2, figsize=(32,16), sharey=True)\n \n ax,ax1,ax2 = run_satellites(Nboot, massrange, dict_SMHM,scatterevol,mu,zinfallrange,ax,ax1,ax2)\n \n save(fig, ax, massrange, dict_SMHM, scatterevol)\n save(fig1, [ax1,ax2], massrange, dict_SMHM, scatterevol, choice='fquench')\n \n\n \n \n Nboot = 10\n make = make_satellites(use_peak=True) #initializes everything within the class\n\n # run parameters\n \n dict_SMHM = dict(gamma10=0.57, gamma11= None, beta10=None, beta11=None,\\\n M10=11.95, SHMnorm10=None, M11=None, SHMnorm11=None) \n scatterevol = True\n mu = 2.5\n \n zinfallrange = [1,1.5,1.5]\n \n massrange = [11.2,12]\n m = 11.6\n fig, ax = plt.subplots(1,1)\n fig1,(ax1,ax2) = plt.subplots(1,2, figsize=(32,16), sharey=True)\n \n ax,ax1,ax2 = run_satellites(Nboot, massrange, dict_SMHM,scatterevol,mu,zinfallrange,ax,ax1,ax2)\n\n save(fig, ax, massrange, dict_SMHM, scatterevol)\n save(fig1, [ax1,ax2], massrange, dict_SMHM, scatterevol, choice='fquench')\n \n \n ###### to do: bins of parent halo mass\n \n \n \n \n ####################################### second set of parameters ####################\n \n ","repo_name":"lorenzozanisi/MassiveSatellites","sub_path":"run_satellites.py","file_name":"run_satellites.py","file_ext":"py","file_size_in_byte":15365,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"29334643079","text":"#Conversión de Decimal a Binario\nnumero = int(input(\"\"))\ns = []\nsum = 0\nn = numero\na = 0\nwhile(n > 0) : \n\ts.append(n%2)\n\tn = n//2\ns2 = s[::-1]\t\nfor i in s :\n\tsum = sum + i*(10**a)\n\ta = a + 1\nprint(\"resultado=\",sum)","repo_name":"pabloschwarzenberg/grader","sub_path":"hito1_ej4/hito1_ej4_3b64a46edacd278ceee36c63958c8ebb.py","file_name":"hito1_ej4_3b64a46edacd278ceee36c63958c8ebb.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"2055358406","text":"\n'''\nPrograma que resuleve un sudoku de tamaño 9x9 con un algoritmo iterativo\n\npara solucionar el sudoku este debe estar con casillas en calor 0 donde pueda iterar el algoritmo\n\n'''\n\n\ndef rangoSublista(x):\n if(x<3):\n return 0\n elif (x<6):\n return 1\n elif (x<9):\n return 2\n else:\n print(\"\\n----------- fallo rango: \",x)\n return -1\n\n\ndef rango0a3(x):\n rangoSublist = rangoSublista(x) \n indice = x-(rangoSublist*3)\n return rangoSublist,indice\n\n\ndef conformarColumna(TableroPrincipal, columna):\n NumerosColumna = []\n sublist,indice = rango0a3(columna)\n for i in TableroPrincipal:\n NumerosColumna.append(i[sublist][indice])\n return NumerosColumna\n\ndef conformarCaja(Tablero,fila,columna):\n caja = []\n limFSup = rangoSublista(fila)*3\n indiceCol = rangoSublista(columna)\n caja.append(Tablero[limFSup][indiceCol])\n caja.append(Tablero[limFSup+1][indiceCol])\n caja.append(Tablero[limFSup+2][indiceCol])\n return caja\n\n\ndef evaluar(list1,list2,list3,x):\n return (x not in list1 and x not in list2 and x not in list3)\n\n\n\ndef Valido(TableroPrincipal,fila,columna,num):\n validoFilas = evaluar(TableroPrincipal[fila][0],TableroPrincipal[fila][1],TableroPrincipal[fila][2],num)\n columnas = conformarColumna(TableroPrincipal,columna)\n validoColumnas = evaluar(columnas[0:3],columnas[3:6],columnas[6:],num)\n caja = conformarCaja(TableroPrincipal,fila,columna)\n validoCaja = evaluar(caja[0],caja[1],caja[2],num)\n return validoCaja and validoColumnas and validoFilas\n\n\ndef matrizAsociada(TableroPrincipal):\n matriz = []\n for i in TableroPrincipal:\n sublist = []\n for j in i:\n sublist.append(j[0]==0)\n sublist.append(j[1]==0)\n sublist.append(j[2]==0)\n matriz.append(sublist)\n return matriz\n\ndef retrocesoValido(fila,columna,matriz):\n if (matriz[fila][columna]):\n return fila,columna,True\n else:\n return retroceder(fila,columna,matriz)\n\ndef retroceder(fila,columna,matriz):\n if(columna == 0):\n fila = fila-1\n columna = 8\n if(fila < 0):\n return fila,columna,False\n else:\n return retrocesoValido(fila,columna,matriz)\n else:\n columna = columna-1\n return retrocesoValido(fila,columna,matriz)\n\n\ndef avanceValido(fila,columna,matriz):\n if (matriz[fila][columna]):\n return fila,columna,True\n else:\n return avanzar(fila,columna,matriz)\n\ndef avanzar(fila,columna,matriz):\n if(columna == 8):\n fila = fila+1\n columna = 0\n if(fila > 8):\n return fila,columna,False\n else:\n return avanceValido(fila,columna,matriz)\n else:\n columna = columna+1\n return avanceValido(fila,columna,matriz)\n\n\ndef imprimirSudoku(Tablero):\n a=1\n for i in Tablero:\n for j in i:\n print(j[0],end=\" \")\n print(j[1],end=\" \")\n print(j[2],end=\" \")\n print(end=\" \")\n if(a==3 or a==6):\n print(\"\\n\")\n else:\n print(\"\")\n a=a+1\n\ndef algoritmoSolucion(TableroPrincipal):\n num = 0 # numero a colocar en determinada posicion\n fila = 0 # fila sobre la cual se opera\n columna = 0\n subList = 0\n indice = 0\n matrizA = matrizAsociada(TableroPrincipal)\n continuar = True\n\n aux = 0\n\n if(not matrizA[0][0]):\n fila,columna,continuar = avanzar(fila,columna,matrizA)\n while(continuar):\n aux = aux+1\n if ( aux%1000 == 0):\n print(\"cuadro:\",aux)\n imprimirSudoku(TableroPrincipal)\n print(\"\\n\")\n input()\n if(num > 9):\n subList,indice = rango0a3(columna)\n TableroPrincipal[fila][subList][indice] = 0\n fila,columna,continuar = retroceder(fila,columna,matrizA)\n if(continuar):\n subList,indice = rango0a3(columna)\n num = TableroPrincipal[fila][subList][indice]+1\n TableroPrincipal[fila][subList][indice] = 0 \n elif (Valido(TableroPrincipal,fila,columna,num)):\n subList,indice = rango0a3(columna)\n TableroPrincipal[fila][subList][indice] = num\n num = 0\n fila,columna,continuar = avanzar(fila,columna,matrizA)\n else:\n num = num+1\n\n\n\n\n\nTablero = [[[1,0,0],[0,0,0],[0,0,0]],\n [[0,2,0],[0,0,0],[0,0,0]],\n [[0,0,3],[0,0,0],[0,0,0]],\n\n [[0,0,0],[4,0,0],[0,0,0]],\n [[0,0,0],[0,5,0],[0,0,0]],\n [[0,0,0],[0,0,6],[0,0,0]],\n\n [[0,0,0],[0,0,0],[7,0,0]],\n [[0,0,0],[0,0,0],[0,8,0]],\n [[0,0,0],[0,0,0],[0,0,9]]]\n\nalgoritmoSolucion(Tablero)\nprint(\"\\nSOLUCIONADO\")\nimprimirSudoku(Tablero)\n\n#matriz = matrizAsociada(Tablero)\n#print(retroceder(3,8,matriz))\n\n\n\n\n#----------------------- FINALIZADO .------------------------------ \nprint(\"\\n\\n\\n\\n Ejecucion completa\")\ninput()","repo_name":"BravorAndres/ResolverSudoku","sub_path":"SudokuEnPython.py","file_name":"SudokuEnPython.py","file_ext":"py","file_size_in_byte":4969,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"8302929141","text":"from decouple import config\nfrom datetime import datetime\nfrom uuid import uuid4\nimport jwt\n\nJWT_SECRET=config(\"JWT_SECRET\", default=\"a9ddbcaba8c0ac1a0a812dc0c2f08514b23f2db0a68343cb8199ebb38a6d91e4ebfb378e22ad39c2d01 d0b4ec9c34aa91056862ddace3fbbd6852ee60c36acbf\")\nJWT_ALGORITHM=config(\"JWT_ALGORITHM\", default=\"HS512\")\n\n\"\"\"\nHelper function which combines user claims and generates JWT token\n\"\"\"\ndef sign_JWT():\n\n now = datetime.utcnow()\n\n jwtClaims = {\n \"iat\": now,\n \"jti\": uuid4().hex,\n \"payload\": {\n \"username\": 'proxyUser' + str(uuid4().hex),\n \"date\": now.strftime(\"%Y-%m-%d\")\n }\n }\n\n return jwt.encode(jwtClaims, JWT_SECRET, algorithm=JWT_ALGORITHM)\n","repo_name":"itsbogdann/ProxyJWT","sub_path":"src/services/jwt.py","file_name":"jwt.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"71640530169","text":"\"\"\"Define functions to use in redis queue.\"\"\"\n\nimport time\n\nfrom rq import get_current_job\n\nfrom . import models\nfrom .database import SessionLocal, engine\n\nmodels.Base.metadata.create_all(bind=engine)\n\n\ndef some_long_function(some_input):\n \"\"\"An example function for redis queue.\"\"\"\n job = get_current_job()\n time.sleep(10)\n\n sql_db = SessionLocal()\n\n result = models.Result(\n job_id=job.id,\n job_enqueued_at=job.enqueued_at,\n job_started_at=job.started_at,\n input=some_input,\n result=some_input,\n )\n\n sql_db.add(result)\n sql_db.commit()\n sql_db.close()\n\n return {\n \"job_id\": job.id,\n \"job_enqueued_at\": job.enqueued_at.isoformat(),\n \"job_started_at\": job.started_at.isoformat(),\n \"input\": some_input,\n \"result\": some_input,\n }\n","repo_name":"edkrueger/rq-flask-sqlalchemy-template","sub_path":"app/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"77"}
+{"seq_id":"31921277022","text":"#!/usr/bin/python3\n#Trevor \nimport sys\n\ndef arg_count():\n argc = len(sys.argv) - 1\n counter = 1\n\n if argc != 1:\n print(\"{} arguments:\".format(argc))\n else:\n print(\"{} argument:\".format(argc))\n\n for arg in sys.argv[1:]:\n print(\"{}: {}\".format(counter, arg))\n counter += 1\n\nif __name__ == \"__main__\":\n arg_count()\n","repo_name":"Trevorvaizel/alx-higher_level_programming","sub_path":"0x02-python-import_modules/2-args.py","file_name":"2-args.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"23696863020","text":"from objects import *\nimport numpy as np\ndef availablePieces(pieceList,tossValue):\n freePieces = []\n for piece in pieceList:\n if(piece.ableToMoveWith(tossValue)):\n freePieces.append(piece)\n return freePieces\n\n\n\n\ndef getPlayerState(turn):\n state = []\n color = [\"red\", \"green\", \"yellow\", \"blue\"][turn]\n # print(\"=======================================\")\n # print(color)\n progress = 0\n pathLength=len(path[f\"{color}Path\"])\n for piece in pieces[turn]:\n progress+= piece.value\n # print(piece)\n \n # print(len(playerPath))\n # print(piece.cell)\n # print(playerPath)\n # print(playerPath[0])\n \n if(piece.cell.cellType==\"station\"):\n piece_state = [-1000 for i in range(12)]\n piece_state.insert(6,0)\n # print(piece_state)\n \n else:\n piecePosition = 0\n colorPath = path[f\"{color}Path\"]\n pathLength = len(colorPath)\n for i in range(pathLength):\n if(colorPath[i]==piece.cell):\n piecePosition=i\n break\n if (piece.cell.cellType in [\"start\" , \"open\"] ):\n piece_state = []\n # print(piecePosition)\n if(piecePosition not in range(0,7)):\n for cellIndex in [i+piecePosition if i + piecePosition < pathLength else pathLength-i + piecePosition for i in range(-6,7)]:\n # print(cellIndex,\" out of \",pathLength)\n cellPoint = 0\n for cellOccupant in colorPath[cellIndex].container:\n if(piece != cellOccupant and cellOccupant.color != piece.color):\n if(cellIndex > piecePosition):\n cellPoint += cellOccupant.value \n else:\n cellPoint -= cellOccupant.value\n elif (piece == cellOccupant):\n if(piece.color == cellOccupant.color):\n cellPoint += cellOccupant.value \n else:\n cellPoint -= cellOccupant.value \n \n piece_state.append(cellPoint)\n else:\n # edgePath\n prevCells = [edgePath[f\"{color}Path\"][piecePosition+6+i] for i in range(-6,1)]\n # prevCells.reverse()\n nextCells = [colorPath[i] for i in range(piecePosition+1,piecePosition+7)]\n edgeCells = prevCells+nextCells\n # for cell in edgeCells:\n # print(cell.id, end=\" => \")\n # print(len(prevCells),\"--\",len(nextCells))\n for cellIndex in range(len(edgeCells)):\n cellPoint = 0\n for cellOccupant in edgeCells[cellIndex].container:\n if(piece != cellOccupant and cellOccupant.color != piece.color):\n if(cellIndex > piecePosition+6):\n cellPoint += cellOccupant.value \n else:\n cellPoint -= cellOccupant.value \n piece_state.append(cellPoint)\n\n # state.append(piece_state)\n # print(piece_state)\n\n\n \n else:\n piece_state = [0 if i + piecePosition < pathLength else -1000 for i in range(-6,7)]\n # print([0 if i + piecePosition < pathLength else float(\"-inf\") for i in range(-6,7)])\n safeCellTypes = [\"home\",\"homeRun\",\"station\",\"swiss\"]\n if(piece.cell.cellType in safeCellTypes):\n piece_state.append(1)\n else:\n piece_state.append(0)\n state+=piece_state\n # state.append(dice.getValue())\n \n \n # for state in state:\n # print(state)\n # print(f\"======================================={color} => {100*(progress/ (4*pathLength))}% \")\n # print(state)\n return state\n \nif __name__==\"__main__\":\n getPlayerState(0)\n\n\n\n\n\n\n\n\n","repo_name":"tesfaye-abrham/LUDO-RL","sub_path":"RL/pygame_based/helper_methods.py","file_name":"helper_methods.py","file_ext":"py","file_size_in_byte":4304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"43575535242","text":"from flask import Flask, request\nfrom flask_pymongo import PyMongo\nimport json\n\n\napp = Flask(__name__)\napp.config[\"MONGO_URI\"] = \"mongodb://localhost:27017/Elevate\"\nmongo = PyMongo(app)\n\n@app.route(\"/\", methods=[\"POST\", \"GET\"])\ndef home():\n return \"hello\"\n\n@app.route(\"/review\", methods=['POST', 'GET'])\ndef review():\n try:\n if request.method == 'POST':\n data = request.get_json()\n print(data)\n one = {\"client_id\": data['client_id'], \"td_account\": data['td_account'], \"stars\": str(data['stars']), \"comment\": data['comment']}\n print(one)\n print(mongo.db.review.insert(one))\n return \"success\", 200\n if request.method == 'GET':\n total = []\n for one in mongo.db.review.find({}, {\"_id\": False}):\n print(one)\n total.append(one)\n return json.dumps(total), 200\n except Exception as error:\n print(error)\n return \"error\", 400\n\n@app.route(\"/restaurants\", methods=['GET'])\ndef restaurants():\n try:\n total = []\n for one in mongo.db.restaurants.find({}, {\"_id\": False}):\n total.append(one)\n return json.dumps(total), 200\n except Exception as error:\n print(error)\n return \"error\", 400\n","repo_name":"norchain/ElevateHackathon","sub_path":"backend/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"3750529158","text":"import torch\nimport logging\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport io\nfrom PIL import Image\nimport torchvision.transforms as transforms\n\n\nclass Net(nn.Module):\n def __init__(self):\n super().__init__()\n self.conv1 = nn.Conv2d(3, 6, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.fc1 = nn.Linear(16 * 5 * 5, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 2)\n \n\n def forward(self, x):\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = torch.flatten(x, 1) # flatten all dimensions except batch\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n \n\n\nmodel = Net()\n\nmodel.load_state_dict(torch.load('cifar_net.pth', map_location=torch.device('cpu')))\nmodel.eval()\n\n\ndef transform_image(img_bytes):\n transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Resize((32,32)),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ])\n image = Image.open(io.BytesIO(img_bytes))\n return transform(image).unsqueeze(0)\n\ndef get_predictions(image_tensor):\n images = image_tensor\n print(images.shape)\n outputs = model(images)\n _, predicted = torch.max(outputs, 1)\n return predicted\n","repo_name":"abhinav-TB/Classifier-Api","sub_path":"app/torch_utils.py","file_name":"torch_utils.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"43686470907","text":"from time import sleep\nfrom threading import Thread\n\nMAX_TPS_HOUR= 500\nMAX_TPS_DAY= 5000\n# Wrapper for the fut script to run for specified time. \ndef run_fut(duration):\n sleep(1)\n\nhoursToRun = int(input('Enter the amount of hours you want to run this: '))\nif hoursToRun <= 10:\n maxTPSHour = MAX_TPS_HOUR\nif 10 < hoursToRun < 24:\n maxTPSHour = MAX_TPS_DAY/hoursToRun\nif 24 < hoursToRun:\n maxTPSHour = 208\n\nt = Thread(target=run_fut, args=(maxTPSHour)) # run the fut func in another thread. \nt.daemon = True # Python will exit when the main thread\n # exits, even if this thread is still\n # running\n\nt.start()\nsecondsToRun = hoursToRun*3600\nsleep(secondsToRun)","repo_name":"kevinBenson3517/futTrading","sub_path":"src/futExecutor.py","file_name":"futExecutor.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"22590062520","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.metrics import classification_report\r\nfrom sklearn.metrics import confusion_matrix\r\n\r\nfrom keras.utils import to_categorical\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Dropout, Flatten\r\nfrom keras.layers import Conv2D, MaxPooling2D\r\nfrom keras.optimizers import Adam\r\nfrom keras.preprocessing import image\r\nfrom keras.preprocessing.image import ImageDataGenerator, load_img\r\nfrom keras.layers.normalization import BatchNormalization\r\nfrom keras.callbacks import EarlyStopping\r\n\r\nimport itertools\r\n\r\nimport PIL.Image\r\n\r\n# defining the variables\r\nnum_classes = 7\r\nepochs = 25\r\nbatch_size = 256\r\n\r\n\r\n# D:\\Users\\Stefano\\Desktop\\fer2013.csv\r\nwith open(r\"D:\\Users\\Stefano\\Desktop\\fer2013.csv\") as file:\r\n content = file.readlines()\r\n\r\nlines = np.array(content)\r\n\r\nnum_instances = lines.size\r\nprint(\"number of instances: \", num_instances)\r\nprint(\"instance length: \", len(lines[1].split(\",\")[1].split(\" \")))\r\n\r\nx_train, y_train, x_test, y_test, x_val, y_val = [], [], [], [], [], []\r\n\r\n# adding the training and test images to them variables\r\nfor i in range(1, num_instances):\r\n try:\r\n emotion, img, usage = lines[i].split(\",\")\r\n\r\n val = img.split(\" \")\r\n\r\n pixels = np.array(val, 'float32')\r\n\r\n emotion = to_categorical(emotion, num_classes)\r\n\r\n if 'Training' in usage:\r\n y_train.append(emotion)\r\n x_train.append(pixels)\r\n elif 'PublicTest' in usage:\r\n y_test.append(emotion)\r\n x_test.append(pixels)\r\n elif 'PrivateTest' in usage:\r\n y_val.append(emotion)\r\n x_val.append(pixels)\r\n except:\r\n print(\"\", end=\"\")\r\n\r\n# --------------------------------------------------------\r\n# data transformation for train and test sets\r\nx_train = np.array(x_train, 'float32')\r\ny_train = np.array(y_train, 'float32')\r\nx_test = np.array(x_test, 'float32')\r\ny_test = np.array(y_test, 'float32')\r\nx_val = np.array(x_val, 'float32')\r\ny_val = np.array(y_val, 'float32')\r\n\r\n# normalization\r\nx_train /= 255\r\nx_test /= 255\r\nx_val /= 255\r\n\r\n# reshaping images as 48x48\r\nx_train = x_train.reshape(x_train.shape[0], 48, 48, 1)\r\nx_train = x_train.astype('float32')\r\nx_test = x_test.reshape(x_test.shape[0], 48, 48, 1)\r\nx_test = x_test.astype('float32')\r\nx_val = x_val.reshape(x_val.shape[0], 48, 48, 1)\r\nx_val = x_val.astype('float32')\r\n\r\n# printing of the number of samples\r\nprint(x_train.shape[0], 'train samples')\r\nprint(x_test.shape[0], 'test samples')\r\nprint(x_val.shape[0], 'validation samples')\r\n\r\n# -----------------------------------------------------------------\r\n# defining callback to prevent overfitting\r\ncallbacks = [EarlyStopping(monitor='val_loss', patience=5, verbose=1)]\r\n\r\n# -----------------------------------------------------------------\r\n# construct CNN structure\r\nmodel = Sequential()\r\n\r\n# 1st layer\r\nmodel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(48, 48, 1), padding='same'))\r\nmodel.add(BatchNormalization())\r\n\r\n# 2nd layer\r\nmodel.add(Conv2D(32, (3, 3), activation='relu'))\r\nmodel.add(BatchNormalization())\r\nmodel.add(MaxPooling2D(pool_size=(2, 2), padding='same'))\r\n\r\nmodel.add(Dropout(0.25))\r\n\r\n# 3rd layer\r\nmodel.add(Conv2D(64, (3, 3), activation='relu', padding='same'))\r\nmodel.add(BatchNormalization())\r\nmodel.add(Conv2D(64, (3, 3), activation='relu', padding='same'))\r\nmodel.add(BatchNormalization())\r\nmodel.add(MaxPooling2D(pool_size=(2, 2), padding='same'))\r\n\r\nmodel.add(Dropout(0.25))\r\n\r\n# 4th layer\r\nmodel.add(Conv2D(128, (3, 3), activation='relu', padding='same'))\r\nmodel.add(BatchNormalization())\r\nmodel.add(Conv2D(128, (3, 3), activation='relu', padding='same'))\r\nmodel.add(BatchNormalization())\r\nmodel.add(MaxPooling2D(pool_size=(2, 2), padding='same'))\r\n\r\nmodel.add(Dropout(0.25))\r\n\r\n# classification\r\nmodel.add(Flatten())\r\nmodel.add(Dense(512, activation='relu'))\r\nmodel.add(BatchNormalization())\r\nmodel.add(Dropout(0.5))\r\nmodel.add(Dense(128, activation='relu'))\r\nmodel.add(Dense(num_classes, activation='softmax'))\r\n\r\n\r\n# ------------------------------\r\n\r\nmodel.compile(loss='categorical_crossentropy',\r\n optimizer=Adam(),\r\n metrics=['accuracy'])\r\n\r\n# ------------------------------\r\n# training the model\r\ngen = ImageDataGenerator()\r\ntrain_generator = gen.flow(x_train, y_train, batch_size=batch_size)\r\n\r\n\r\nmodel.fit(train_generator,\r\n steps_per_epoch=batch_size,\r\n epochs=epochs,\r\n validation_data=(x_val, y_val),\r\n callbacks=callbacks)\r\n\r\n# ------------------------------\r\n\r\n# evaluation\r\nscore = model.evaluate(x_test, y_test, verbose=0)\r\nprint('Test loss:', score[0])\r\nprint('Test accuracy:', 100*score[1])\r\n\r\n\r\n# ----------------------------------\r\n# function for drawing bar chart for emotion predictions\r\ndef emotion_analysis(emotions):\r\n objects = ('angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral')\r\n y_pos = np.arange(len(objects))\r\n\r\n plt.bar(y_pos, emotions, align='center', alpha=0.5)\r\n plt.xticks(y_pos, objects)\r\n plt.ylabel('percentage')\r\n plt.title('emotion')\r\n plt.show()\r\n\r\n\r\n#--------------------------------------------\r\n# function to print images from the dataset with their prediction\r\ndef check_img_dataset(first, second):\r\n # make predictions\r\n predictions = model.predict(x_test)\r\n # printing the images of the set from 2 to 34 with the emotion\r\n index = 0\r\n for i in predictions:\r\n if first < index < second:\r\n\r\n test_img = np.array(x_test[index], 'float32')\r\n test_img = test_img.reshape([48, 48]);\r\n\r\n plt.gray()\r\n plt.imshow(test_img)\r\n plt.show()\r\n\r\n emotion_analysis(i)\r\n # print(\"----------------------------------------------\")\r\n index = index + 1\r\n\r\n\r\n# ------------------------------------------------------\r\n# test the model with custom images (only face)\r\ndef check_img(img_path):\r\n img = load_img(img_path, color_mode='grayscale', target_size=(48, 48))\r\n\r\n x = image.img_to_array(img)\r\n x = np.expand_dims(x, axis=0)\r\n\r\n x /= 255\r\n\r\n custom = model.predict(x)\r\n emotion_analysis(custom[0])\r\n\r\n x = np.array(x, 'float32')\r\n x = x.reshape([48, 48])\r\n\r\n plt.gray()\r\n plt.imshow(x)\r\n plt.show()\r\n\r\n\r\n# printing the recall and precision-----------------------------------------\r\ndef get_metrics():\r\n y_pred = model.predict_classes(x_test, verbose=0)\r\n # get 1 D\r\n y_true = np.argmax(y_test, axis=1)\r\n\r\n target_names = ['angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral']\r\n\r\n print(classification_report(y_true, y_pred, target_names=target_names, digits=4))\r\n\r\n\r\n# ---------------------------------------------------------------------\r\n# print the confusion matrix\r\ndef conf_mat():\r\n y_pred = model.predict_classes(x_test, verbose=0)\r\n y_true = np.argmax(y_test, axis=1)\r\n cm = confusion_matrix(y_true, y_pred)\r\n\r\n labels = ['Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral']\r\n title = 'Confusion matrix'\r\n print(cm)\r\n\r\n plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)\r\n plt.title(title)\r\n plt.colorbar()\r\n tick_marks = np.arange(len(labels))\r\n plt.xticks(tick_marks, labels, rotation=45)\r\n plt.yticks(tick_marks, labels)\r\n fmt = 'd'\r\n thresh = cm.max() / 2.\r\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\r\n plt.text(j, i, format(cm[i, j], fmt),\r\n horizontalalignment=\"center\",\r\n color=\"white\" if cm[i, j] > thresh else \"black\")\r\n\r\n plt.ylabel('True label')\r\n plt.xlabel('Predicted label')\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n# -----------------------------------------------------------------------\r\n","repo_name":"delorenzostefano/FacialExpressionRecognition","sub_path":"emorec.py","file_name":"emorec.py","file_ext":"py","file_size_in_byte":7793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"22772799536","text":"from typing import Optional\n\n\nclass ListNode:\n def __init__(self, value, next=None):\n self.val = value\n self.next = next\n# A linked List class with a single head node\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n # Insert method for the linked list\n def insert(self, data):\n newNode = ListNode(data)\n if(self.head):\n current = self.head\n while(current.next):\n current = current.next\n current.next = newNode\n else:\n self.head = newNode\n\n # print all\n def printLL(self):\n current = self.head\n while(current):\n print(current.val)\n current = current.next\n\nclass Solution:\n def mergeTwoLists(self, list1:Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n curr1 = list1\n curr2 = list2\n prehead = ListNode(-1)\n prev = prehead\n while (curr1 and curr2):\n if curr1.val <= curr2.val:\n prev.next = curr1\n curr1 = curr1.next\n else:\n prev.next = curr2\n curr2 = curr2.next\n prev = prev.next\n if curr1 is not None:\n prev.next = curr1\n else:\n prev.next = curr2\n return prehead.next\n\n\nif __name__ == '__main__':\n sol = Solution()\n LL = LinkedList()\n LL.insert(2)\n LL.insert(4)\n LL.insert(6)\n LL2 = LinkedList()\n LL2.insert(1)\n LL2.insert(2)\n LL2.insert(3)\n\n # Before reversing\n # LL.printLL()\n res = sol.mergeTwoLists(LL.head, LL2.head)\n # After reversing\n print(res.val)\n print(res.next.val)\n print(res.next.next.val)\n print(res.next.next.next.val)\n print(res.next.next.next.next.val)\n print(res.next.next.next.next.next.val)\n \n","repo_name":"wangcong26/leetcode_python","sub_path":"a03_linked_list/Leetcode_21_MergeTwoSortedLists.py","file_name":"Leetcode_21_MergeTwoSortedLists.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"30946318871","text":"import requests\nfrom bs4 import BeautifulSoup\n\nr = requests.get(\"https://www.ptt.cc/bbs/MobileComm/index.html\") #將網頁資料GET下來\n#print(r.text)\n\nsoup = BeautifulSoup(r.text,\"html.parser\") #將網頁資料以html.parser\n#print(soup)\nsel = soup.select(\"div.title a\")\n#print(sel)\n\nfor s in sel:\n print(s[\"href\"],\"\", s.text)","repo_name":"HsuRicky/first-web","sub_path":"practice/20230210.py","file_name":"20230210.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"21839060251","text":"import logging\nimport requests\nimport os\nimport json\nimport xml.etree.ElementTree as ET\nfrom datetime import (timedelta, datetime)\nfrom random import randrange\n\nfrom homeassistant.const import (TIME_MINUTES, ATTR_ATTRIBUTION)\nfrom homeassistant.helpers.entity import Entity\n\nlog = logging.getLogger('prochains_rer.transilien')\n\ndef find_gare(gares, uic):\n for gare in gares:\n if (gare['uic'] == uic):\n return gare['nom']\n return uic\n\ndef get_trains(url, auth):\n log.debug('get_trains(%s)', url)\n r = requests.get(\n url,\n auth=auth,\n headers={'accept': 'application/vnd.sncf.transilien.od.depart+xml;vers=1'}\n )\n r.encoding = 'utf8'\n if not r.ok:\n log.error('unable to call api - %s', r.reason)\n return []\n\n # log.debug(r.text)\n \n root = ET.fromstring(r.text)\n \n with open(os.path.join(os.path.dirname(__file__), 'gares.json')) as file_gares:\n gares = json.load(file_gares)\n\n trains = []\n for train in root:\n date = datetime.strptime(train.findtext('date'), '%d/%m/%Y %H:%M')\n num = train.findtext('num')\n miss = train.findtext('miss')\n etat = train.findtext('etat', '')\n term = train.findtext('term', '')\n\n trains.append({\n 'date': date,\n 'num': num,\n 'mission': miss,\n 'code_term': term,\n 'terminus': find_gare(gares, term),\n 'etat': etat\n })\n\n return trains\n\nclass ProchainsTrains(Entity):\n def __init__(self, name, depart, arrivee, auth, debut_journee):\n self._name = name\n self.depart = depart\n self.arrivee = arrivee\n self.auth = auth\n self.debut_journee = debut_journee\n self.data = []\n self.last_update = None\n\n @property\n def name(self):\n return self._name\n\n @property\n def state(self):\n if self.data and len(self.data) > 0:\n # minutes till next train\n # first clean trains in the past\n self.data = list(filter(lambda x: x['date'] > datetime.now(), self.data))\n minutes = round((self.data[0]['date'] - datetime.now()).total_seconds() / 60)\n return minutes\n else:\n return None\n\n @property\n def unit_of_measurement(self):\n return TIME_MINUTES\n\n @property\n def icon(self):\n return 'mdi:train'\n\n @property\n def state_attributes(self):\n return {\n 'api': 'transilien',\n 'last_update': self.last_update,\n 'trains': self.data\n }\n\n def get_auth(self):\n if isinstance(self.auth['username'], list):\n idx = randrange(len(self.auth['username']))\n return (self.auth['username'][idx], self.auth['password'][idx])\n else:\n return (self.auth['username'], self.auth['password'])\n\n def update(self):\n log.debug('Updating %s...', self.name)\n if datetime.now().hour < self.debut_journee:\n self.data = []\n self.last_update = None\n elif self.last_update is None or (datetime.now() - self.last_update).total_seconds() > 5*60:\n url = 'http://api.transilien.com/gare/{}/depart/{}'.format(self.depart, self.arrivee)\n self.data = get_trains(url, self.get_auth())\n self.last_update = datetime.now()\n","repo_name":"niicojs/ha_prochains_rer","sub_path":"custom_components/transilien.py","file_name":"transilien.py","file_ext":"py","file_size_in_byte":3026,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"29934981019","text":"#!/usr/bin/python3\n\n#This script needs a csv-file as argument with following columns:\n#-\"Title\": | Title of movie\n#-\"TrackID\": | Number of subtitle(s) to extract. Will be increment by 2 to\n#-\"Subtitle Codec\": | Currently knows \"vobsub\" and \"pgs\". Prbably obsolete with higher mkvextract-version.\n#-\"Part File Combined\": | Full path incl. filename to mkv-file\n\n#Possible enhancement:\n#Instead of manually specifying the TrackIDs it's better to parse the mkv-file.\n#see https://gitlab.com/mbunkus/mkvtoolnix/-/wikis/Automation-examples#example-1-multiplex-files-change-audio-language-remove-subtitle-track\n\nimport os\nimport csv\nimport sys\n\nsubNames = [\"de.forced.\", \"en.forced.\"]\nextReplace = {\"vob\":\"sub\", \"pgs\":\"sup\"}\nerrorLog = \"\"\ncount = 0\n\nif not(os.path.isfile(sys.argv[1]) and sys.argv[1][-3:] == 'csv'):\n print(\"No/wrong CSV input specified.\\nUsage: \" + sys.argv[0] + \" pathToCsv [-e]\")\n exit(1)\n \nif len(sys.argv) > 2 and sys.argv[2] == \"-e\":\n dryrun = False\nelse:\n dryrun = True\n print(\"--------DRYRUN--------\\nNo changes are being made\\nAppend '-e' to execute programm without dryrun\\n-----------------------\")\n\nwith open(sys.argv[1], newline='') as csvfile:\n entries = sum(1 for line in csvfile if line.rstrip()) - 1\n csvfile.seek(0) #reset position\n reader = csv.DictReader(csvfile, delimiter=';')\n\n for row in reader:\n count += 1\n execmd = \"mkvextract '\" + row['Part File Combined'] + \"' tracks\"\n if os.path.isfile(row['Part File Combined']):\n z = 0\n IdOffset = len(row['Audio Languages'].split('-'))\n for i in row['TrackID'].split(','):\n execmd += \" \" + str(int(i)+IdOffset) + \":'\" + row['Part File Combined'][:-3] + \\\n subNames[z] + extReplace[row['Subtitle Codec'][:3]] + \"'\"\n z += 1\n print(\"[\" + str(count) + \"/\" + str(entries) + \"] \" + \"Executing:\\n\" + execmd)\n retval = 0 if dryrun else os.system(execmd)\n if retval != 0:\n errorLog += \"\\t\" + row['Title'] + \"\\n\"\n else:\n print (\"!!! NOT FOUND: \" + row['Title'])\n if errorLog:\n print(\"These items had non-zero return values:\\n\" + errorLog)\n","repo_name":"rabelux/homeserver","sub_path":"Video-Editing/ExtractForcedSubs.py","file_name":"ExtractForcedSubs.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"27643717144","text":"# link => https://leetcode.com/problems/unique-binary-search-trees/\n\n\nclass Solution:\n # dynamic programming\n def numTrees(self, n: int) -> int:\n\n res = [0] * (n+1)\n res[0] = 1\n\n for i in range(1, n+1):\n\n for j in range(i):\n\n res[i] += res[j]*res[i-j-1]\n\n return res[n]\n","repo_name":"simba28/daily-codes","sub_path":"uniqueBinarySearchTrees.py","file_name":"uniqueBinarySearchTrees.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"186144658","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Imports\nimport signal\nimport argparse\nimport logging\nimport socket\nimport re\nimport time\n\nfrom influxdb_client import InfluxDBClient, Point\nfrom influxdb_client.client.write_api import SYNCHRONOUS\nfrom influxdb_client.rest import ApiException\n\n\n# Logging\nlogging.basicConfig(\n level = logging.INFO,\n format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n)\nlog = logging.getLogger('adsb2influx')\n\n\n# Killer\nclass GracefulKiller(object):\n kill_now = False\n\n def __init__(self):\n signal.signal(signal.SIGINT, self.handler)\n signal.signal(signal.SIGTERM, self.handler)\n\n def handler(self, sig, frame):\n self.kill_now = True\n\n\n# AdsbProcessor\nclass AdsbError(Exception):\n pass\n\nclass AdsbProcessor(object):\n MSG_REGEX = r'^MSG,' \\\n r'(?P\\d),' \\\n r'(?P\\d*),' \\\n r'(?P\\d*),' \\\n r'(?P[0-9A-F]+),' \\\n r'(?P\\d*),' \\\n r'(?P[0-9/]*),' \\\n r'(?P[0-9:\\.]*),' \\\n r'(?P[0-9/]*),' \\\n r'(?P[0-9:\\.]*),' \\\n r'(?P[\\w\\s]*),' \\\n r'(?P\\d*),' \\\n r'(?P\\d*),' \\\n r'(?P[\\d\\-]*),' \\\n r'(?P[\\d\\-\\.]*),' \\\n r'(?P[\\d\\-\\.]*),' \\\n r'(?P[\\d\\-]*),' \\\n r'(?P\\d*),' \\\n r'(?P[\\d\\-]*),' \\\n r'(?P[\\d\\-]*),' \\\n r'(?P[\\d\\-]*),' \\\n r'(?P[\\d\\-]*)$'\n\n MSG_NORMAL = {\n 'transmission': (lambda v: int(v)),\n 'session': (lambda v: int(v)),\n 'aircraft': (lambda v: int(v)),\n 'flight': (lambda v: int(v)),\n 'callsign': (lambda v: v.strip()),\n 'altitude': (lambda v: int(v)),\n 'speed': (lambda v: int(v)),\n 'track': (lambda v: int(v)),\n 'latitude': (lambda v: float(v)),\n 'longitude': (lambda v: float(v)),\n 'verticalrate': (lambda v: int(v)),\n 'alert': (lambda v: True if v == '-1' else False),\n 'emergency': (lambda v: True if v == '-1' else False),\n 'spi': (lambda v: True if v == '-1' else False),\n 'onground': (lambda v: True if v == '-1' else False),\n }\n\n def __init__(self):\n self.re_msg = re.compile(self.MSG_REGEX)\n self.aircrafts = {}\n self.aircrafts_age = {}\n\n def __getitem__(self, key):\n return self.aircrafts[key]\n\n def __setitem__(self, key, value):\n self.aircrafts[key] = value\n\n def __delitem__(self, key):\n del self.aircrafts[key]\n\n def __contains__(self, key):\n return key in self.aircrafts\n\n def __len__(self):\n return len(self.aircrafts)\n\n def __repr__(self):\n return repr(self.aircrafts)\n\n def __cmp__(self, dict_):\n return self.__cmp__(self.aircrafts, dict_)\n\n def __iter__(self):\n return iter(self.aircrafts)\n\n def __unicode__(self):\n return unicode(repr(self.aircrafts))\n\n def __normalize_msg(self, msg):\n for field, fnc in self.MSG_NORMAL.items():\n if field in msg:\n msg[field] = fnc(msg[field])\n\n return msg\n\n def keys(self):\n return self.aircrafts.keys()\n\n def values(self):\n return self.aircrafts.values()\n\n def items(self):\n return self.aircrafts.items()\n\n def pop(self, *args):\n return self.aircrafts.pop(*args)\n\n def clear(self, age):\n for hexident in list(self.aircrafts_age.keys()):\n if hexident in self.aircrafts:\n del self.aircrafts_age[hexident]\n continue\n\n if (time.time() - self.aircrafts_age[hexident]) > age:\n log.info('Hexident {} is too old, deleting'.format(hexident))\n del self.aircrafts_age[hexident]\n del self.aircrafts[hexident]\n\n for hexident in self.aircrafts.keys():\n self.aircrafts[hexident]['count'] = 0\n\n def age(self, hexident):\n return (time.time() - self.aircrafts_age.get(hexident, 0))\n\n def msg(self, data):\n data = data.strip()\n log.debug(data)\n\n matches = self.re_msg.match(data)\n if not matches:\n log.error('Wrong format for MSG \\'{}\\', skipping...'.format(data))\n return\n\n msg = { k: v for k, v in matches.groupdict().items() if v }\n msg = self.__normalize_msg(msg)\n\n self.aircrafts_age[msg['hexident']] = time.time()\n\n if msg['hexident'] not in self.aircrafts:\n self.aircrafts[msg['hexident']] = msg\n self.aircrafts[msg['hexident']]['count'] = 1\n else:\n self.aircrafts[msg['hexident']].update(msg)\n self.aircrafts[msg['hexident']]['count'] += 1\n\n\n# dump1090\nclass Dump1090(object):\n def __init__(self, host, port):\n self.host = host\n self.port = port\n self.socket = None\n self.data = ''\n\n def connect(self):\n log.info('Connecting to dump1090 on {}:{}'.format(self.host, self.port))\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n connected = False\n\n while not connected:\n try:\n self.socket.connect((self.host, self.port))\n connected = True\n log.info('Connected OK, receiving data')\n except Exception as e:\n connected = False\n log.warning('Could not connect, retrying ({})'.format(e))\n\n self.socket.setblocking(False)\n self.socket.settimeout(1)\n\n def disconnect(self):\n self.socket.close()\n log.info('Disconnected from dump1090')\n\n def receive(self):\n ret = None\n\n try:\n self.data += self.socket.recv(1024).decode('UTF-8')\n self.socket.send(bytes(\"\\n\", 'UTF-8'))\n\n newline = self.data.find('\\n')\n if newline >= 0:\n ret = self.data[:newline]\n self.data = self.data[newline + 1:]\n except socket.timeout:\n pass\n except Exception as e:\n raise AdsbError('Error receiving data from dump1090: \\'{}\\''.format(e))\n\n return ret\n\n\n# InfluxDB\nclass InfluxDB(object):\n def __init__(self, url, token, org, bucket):\n self.org = org\n self.bucket = bucket\n\n self.client = InfluxDBClient(\n url = url,\n token = token,\n org = org\n )\n\n self.writeapi = self.client.write_api(\n write_options = SYNCHRONOUS\n )\n\n def write(self, data):\n log.debug('Write data to InfluxDB: {}'.format(data))\n\n try:\n self.writeapi.write(self.bucket, self.org, data)\n log.info('Written {} aircraft to InfluxDB'.format(len(data)))\n except ApiException as e:\n log.error('Writing data to InfluxDB failed, status code: {} {}'.format(e.status, e.reason))\n return False\n\n return True\n\n\n# Main\ndef main():\n parser = argparse.ArgumentParser(\n description = 'Write ADSB data from dump1090 to InfluxDB 2.0'\n )\n\n parser.add_argument(\n '-dh', '--dump1090-host',\n dest = 'dump1090_host',\n default = 'localhost',\n help = 'dump1090 host/ip (default: localhost)'\n )\n parser.add_argument(\n '-dp', '--dump1090-port',\n dest = 'dump1090_port',\n type = int,\n default = 30003,\n help = 'dump1090 port (default: 30003)'\n )\n parser.add_argument(\n '-iu', '--influxdb-url',\n dest = 'influxdb_url',\n required = True,\n help = 'InfluxDB url (e.g. http://url-to-influxdb:8086/)'\n )\n parser.add_argument(\n '-it', '--influxdb-token',\n dest = 'influxdb_token',\n required = True,\n help = 'InfluxDB API token'\n )\n parser.add_argument(\n '-io', '--influxdb-org',\n dest = 'influxdb_org',\n required = True,\n help = 'InfluxDB organisation'\n )\n parser.add_argument(\n '-ib', '--influxdb-bucket',\n dest = 'influxdb_bucket',\n default = 'adsb',\n help = 'InfluxDB bucket (default: adsb)'\n )\n parser.add_argument(\n '-im', '--influxdb-measurement',\n dest = 'influxdb_measurement',\n default = 'messages',\n help = 'InfluxDB measurement (default: messages)'\n )\n parser.add_argument(\n '-si', '--send-interval',\n dest = 'send_interval',\n type = int,\n default = 60,\n help = 'send interval in seconds (default: 60)'\n )\n parser.add_argument(\n '-d', '--debug',\n dest = 'debug',\n action = 'store_true',\n help = 'set logging to debug level'\n )\n\n args = parser.parse_args()\n\n\n # Logging\n if args.debug == True:\n log.setLevel(logging.DEBUG)\n\n log.debug('Arguments: {}'.format(args))\n\n\n # Killer\n killer = GracefulKiller()\n\n # AdsbProcessor\n ap = AdsbProcessor()\n\n # dump1090\n dump1090 = Dump1090(args.dump1090_host, args.dump1090_port)\n dump1090.connect()\n\n # InfluxDB\n influxdb = InfluxDB(\n url = args.influxdb_url,\n token = args.influxdb_token,\n org = args.influxdb_org,\n bucket = args.influxdb_bucket\n )\n\n\n measurement = args.influxdb_measurement\n send_interval = args.send_interval\n last_print = time.time()\n\n\n # This is where the magic happens\n while not killer.kill_now:\n if (time.time() - last_print) > send_interval:\n last_print = time.time()\n\n to_send = []\n\n for hexident, msg in ap.items():\n if not all(k in msg for k in ['callsign', 'squawk']):\n log.info('Missing callsign or squawk for {}'.format(hexident))\n continue\n\n if ap.age(hexident) > send_interval:\n log.info('Aircraft {} was not seen too long. Not sending'.format(hexident))\n continue\n\n to_send.append({\n 'measurement': measurement,\n 'tags': {\n 'hexident': hexident,\n 'callsign': msg['callsign'],\n 'squawk': msg['squawk'],\n },\n 'fields': {\n 'generated': time.time(),\n 'altitude': msg.get('altitude'),\n 'speed': msg.get('speed'),\n 'track': msg.get('track'),\n 'latitude': msg.get('latitude'),\n 'longitude': msg.get('longitude'),\n 'verticalrate': msg.get('verticalrate'),\n 'alert': msg.get('alert'),\n 'emergency': msg.get('emergency'),\n 'spi': msg.get('spi'),\n 'onground': msg.get('onground'),\n 'count': msg.get('count', 0),\n }\n })\n\n\n ap.clear(send_interval * 3)\n if len(to_send) > 0:\n influxdb.write(to_send)\n else:\n log.info('No aircrafts to be saved in InfluxDB')\n\n\n try:\n msg = dump1090.receive()\n except AdsbError as e:\n log.error(e)\n killer.kill_now = True\n else:\n if msg is not None:\n ap.msg(msg)\n\n\n # Exit\n dump1090.disconnect()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Dennis14e/docker-flighttracker","sub_path":"adsb2influx/adsb2influx.py","file_name":"adsb2influx.py","file_ext":"py","file_size_in_byte":11469,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"44842140681","text":"import pickle\nimport minorminer\nfrom dwave.system.samplers.dwave_sampler import DWaveSampler\n\nin_filename = 'bqm.pickle'\n\ntry:\n with open(in_filename, 'rb') as f:\n bqm = pickle.load(f)\nexcept FileNotFoundError:\n print('error: file \"%s\" does not exist' % filename)\n sys.exit(1)\n\nsampler = DWaveSampler(solver='DW_2000Q_LANL')\n\nhdw_adj = []\n\nfor node in sampler.adjacency:\n for neighbor_node in sampler.adjacency[node]:\n hdw_adj.append((node,neighbor_node))\n \nbest_total_qubits = 1000\nbest_longest_chain = 20\n\nfor i in range(100):\n embedding = minorminer.find_embedding(bqm.quadratic, hdw_adj)\n\n emb_filename = 'embedding.' + str(i) + '.pickle'\n with open(emb_filename, 'wb') as f:\n pickle.dump(embedding, f, pickle.HIGHEST_PROTOCOL)\n\n total_qubits = 0\n longest_chain = 0\n for var in embedding:\n total_qubits += len(embedding[var])\n if len(embedding[var]) > longest_chain:\n longest_chain = len(embedding[var])\n\n print('**************** i=%d ****************' % i)\n print('total qubits used = %d' % total_qubits)\n print('longest chain = %d' % longest_chain)\n\n if total_qubits < best_total_qubits and longest_chain < best_longest_chain:\n best_embedding = embedding\n best_total_qubits = total_qubits\n best_longest_chain = longest_chain\n\nprint('best total qubits used = %d' % best_total_qubits)\nprint('best longest chain = %d' % best_longest_chain)\n","repo_name":"albezanilla/my_dwave","sub_path":"embed.py","file_name":"embed.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"7117177187","text":"\nimport re\nimport warnings\nimport os\n\nfrom collections import OrderedDict\n\n\nclass FSL_template(OrderedDict):\n def __init__(self, analysis):\n self.analysis = analysis\n self.template = os.path.join(os.path.dirname(os.path.realpath(__file__)),\n 'fsl', 'template_' + self.analysis +'.fsf')\n if self.template:\n self.read(self.template)\n\n def read(self, template):\n self.template = template\n with open(self.template, 'rb') as infile:\n data = infile.read()\n self.parse(data)\n\n def parse(self, data):\n coding = 'utf-8'\n buff = [s.strip() for s in data.decode(coding).split('\\n')]\n self.data = buff\n\n def set_EV_values(self):\n assert self.analysis == 'second_level', 'EV values are only used in second_level analysis'\n grab_n_inputs = lambda s: re.match('# Higher-level EV value for EV 1 and input \\d+$', s)\n temp = [grab_n_inputs(s) for s in self.data if grab_n_inputs(s) != None]\n last_index = -1\n for i in range(self.n_inputs):\n if i < len(temp):\n self.data[self.data.index(temp[i].string) + 1] = 'set fmri(evg' + str(i + 1) + '.1) 1.0'\n last_index = self.data.index(temp[i].string) + 1\n else:\n self.data.insert(last_index + 2, '# Higher-level EV value for EV 1 and input ' + str(i + 1))\n self.data.insert(last_index + 3, 'set fmri(evg' + str(i + 1) + '.1) 1.0')\n self.data.insert(last_index + 4, '')\n last_index = last_index + 3\n\n def set_group_membership(self):\n assert self.analysis == 'second_level', 'Group membership is only used in second_level analysis'\n grab_n_inputs = lambda s: re.match('# Group membership for input \\d+$', s)\n temp = [grab_n_inputs(s) for s in self.data if grab_n_inputs(s) != None]\n last_index = -1\n for i in range(self.n_inputs):\n if i < len(temp):\n self.data[self.data.index(temp[i].string) + 1] = 'set fmri(groupmem.' + str(i + 1) + ') 1'\n last_index = self.data.index(temp[i].string) + 1\n else:\n self.data.insert(last_index + 2, '# Group membership for input ' + str(i + 1))\n self.data.insert(last_index + 3, 'set fmri(groupmem.' + str(i + 1) + ') 1')\n self.data.insert(last_index + 4, '')\n last_index = last_index + 3\n\n def set_output_directory(self, output_directory):\n # output directory\n self.data[self.data.index('# Output directory')+1] = 'set fmri(outputdir) ' + '\"' + output_directory + '\"'\n\n def set_4D_data(self, inputs_4D):\n grab_n_inputs = lambda s: re.match('# 4D AVW data or FEAT directory \\(\\d+\\)$', s)\n temp = [grab_n_inputs(s) for s in self.data if grab_n_inputs(s) != None]\n self.n_inputs = len(inputs_4D)\n last_index = -1\n for i in range(len(inputs_4D)):\n if i < len(temp):\n if self.analysis == 'first_level':\n self.data[self.data.index(temp[i].string) + 1] = 'set feat_files(' + str(i+1) + \\\n ') ' + '\"' + inputs_4D[i] + '\"'\n elif self.analysis == 'second_level':\n self.data[self.data.index(temp[i].string) + 1] = 'set feat_files(' + str(i + 1) + \\\n ') ' + '\"' + inputs_4D[i] + '.feat\"'\n else:\n warnings.warn('Should be first_level or second_level analysis')\n last_index = self.data.index(temp[i].string) + 1\n else:\n self.data.insert(last_index + 2, '# 4D AVW data or FEAT directory (' + str(i+1) + ')')\n if self.analysis == 'first_level':\n self.data.insert(last_index + 3, 'set feat_files(' + str(i+1) + ') ' + '\"' + inputs_4D[i] + '\"')\n elif self.analysis == 'second_level':\n self.data.insert(last_index + 3, 'set feat_files(' + str(i + 1) + ') ' + '\"' +\n inputs_4D[i] + '.feat\"')\n else:\n warnings.warn('Should be first_level or second_level analysis')\n self.data.insert(last_index + 4, '')\n last_index = last_index + 3\n self.data[self.data.index('# Number of first-level analyses') + 1] = 'set fmri(multiple) ' + str(len(inputs_4D))\n\n\n def set_structural_images(self, structural_images):\n assert self.analysis == 'first_level', 'Structural images are only used in first_level analysis'\n grab_n_inputs = lambda s: re.match('# Subject\\'s structural image for analysis \\d+$', s)\n temp = [grab_n_inputs(s) for s in self.data if grab_n_inputs(s) != None]\n last_index = -1\n for i in range(len(structural_images)):\n if i < len(temp):\n self.data[self.data.index(temp[i].string) + 1] = 'set highres_files(' + str(i+1) + ') ' + \\\n '\"' + structural_images[i] + '\"'\n last_index = self.data.index(temp[i].string) + 1\n else:\n self.data.insert(last_index + 2, '# Subject\\'s structural image for analysis ' + str(i+1))\n self.data.insert(last_index + 3, 'set highres_files(' + str(i+1) + ') ' +\n '\"' + structural_images[i] + '\"')\n self.data.insert(last_index + 4, '')\n last_index = last_index + 3\n\n def write(self, filename):\n self.filename = filename\n with open(self.filename, 'w') as outfile:\n outfile.write('\\n'.join(self.data))","repo_name":"UMCU-RIBS/ieeg-fmri-dataset-validation","sub_path":"ieeg_fmri_validation/fmri/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":5933,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"22518753237","text":"#!/usr/bin/env python\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\nclass Solution:\n def reverse(self, start, end):\n i, j = None, start\n while i is not end:\n tmp = j.next\n j.next = i\n i, j = j, tmp\n start.next = j # 翻转后的尾是最开始的start,将其next接到翻转前尾的next,从而实现翻转片段与后续片段的连接\n return end, start\n\n def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n if head is None or head.next is None: return head\n dummy = ListNode(0, next=head)\n prev = dummy\n while True:\n i = j = prev.next\n count = 1\n while j is not None and count < k:\n j = j.next\n count += 1\n if j is None: break\n rev_head, rev_end = self.reverse(i, j)\n prev.next = rev_head # 翻转片段与前序片段的连接\n prev = rev_end\n\n return dummy.next","repo_name":"ftakanashi/JobProjects","sub_path":"LeetCode/25.K个一组翻转链表/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"34386355426","text":"from datetime import date\nfrom decimal import Decimal\nfrom io import StringIO\n\nfrom ccp2qif.ccp import parse_csv, parse_xls\nfrom ccp2qif.core import (\n AccountInfo,\n QIFTransaction as QT,\n TransactionList,\n write_qif,\n)\n\n\ndef test_parsing_csv():\n cp_account = 'LU23 4567 8901 2345 1234'\n expected = TransactionList(\n account=AccountInfo('LU12 3456 7890 1234 5678', ''),\n transactions=[\n QT(date(2017, 1, 2), Decimal('-16.70'),\n 'description 1 | comm 1-1 | comm 1-2', cp_account, 'ref 1'),\n QT(date(2017, 1, 2), Decimal('20.10'),\n 'description 2 | comm 2-1 | comm 2-2', cp_account, 'ref 2'),\n QT(date(2017, 1, 3), Decimal('-20.00'),\n 'description 3 | comm 3-1 | comm 3-2', cp_account, 'ref 3'),\n QT(date(2017, 1, 4), Decimal('-20.00'),\n 'description 4 | comm 4-1 | comm 4-2', cp_account, 'ref 4'),\n QT(date(2017, 1, 5), Decimal('500'),\n 'description 5 | comm 5-1 | comm 5-2', cp_account, 'ref 5'),\n ]\n )\n\n with open('testdata/ccp/ccp_in.csv') as infile:\n result = parse_csv(infile)\n assert result.account == expected.account\n assert result.transactions == expected.transactions\n assert result == expected\n\n\ndef test_parsing_xls():\n expected = TransactionList(\n account=AccountInfo('foo', ''),\n transactions=[\n QT(date(2018, 3, 23), Decimal('-18.90'), 'Desc 1', 'LU12 2345 1111 2222 0001', ''),\n QT(date(2018, 3, 23), Decimal('-2.90'), 'Desc 2', 'LU12 2345 1111 2222 0002', ''),\n QT(date(2018, 3, 21), Decimal('200.00'), 'Desc 3', 'LU12 2345 1111 2222 0003', ''),\n QT(date(2018, 3, 21), Decimal('-11.40'), 'Desc 4', 'LU12 2345 1111 2222 0004', ''),\n QT(date(2018, 3, 21), Decimal('-19.20'), 'Desc 5', 'LU12 2345 1111 2222 0005', ''),\n QT(date(2018, 3, 20), Decimal('-2.90'), 'Desc 6', 'LU12 2345 1111 2222 0006', ''),\n ]\n )\n\n\n result = parse_xls('testdata/ccp/ccp_in.xlsx', 'foo')\n assert result.account == expected.account\n assert result.transactions == expected.transactions\n assert result == expected\n\n\ndef test_to_qif():\n with open('testdata/ccp/ccp_in.csv') as infile:\n input_data = parse_csv(infile)\n with open('testdata/ccp/ccp_out.qif') as infile:\n expected = infile.read()\n output = StringIO()\n write_qif(input_data, output)\n result = output.getvalue()\n assert result == expected\n","repo_name":"exhuma/ccp2qif","sub_path":"tests/test_ccp.py","file_name":"test_ccp.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"39745908785","text":"from ISS_Tracker import db\nfrom ISS_Tracker import Satellite\nimport csv\n\ndb.create_all()\nwith open('.data/Satellite_Database.csv', newline='\\n', encoding='utf-8') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n if(row['NORAD Number']):\n print(int(row['NORAD Number']))\n sat = Satellite(norad_number=int(row['NORAD Number']), name=row['Current Official Name of Satellite'], tle=None)\n db.session.add(sat)\n db.session.commit()\n","repo_name":"AndrewCramp/Satellite_Spotter","sub_path":"generate_db.py","file_name":"generate_db.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"33123871107","text":"import sys\n\nn = int(sys.stdin.readline())\narr = []\nfor i in range(n):\n arr.append(list(map(int, sys.stdin.readline().split())))\n\n# 수행할 수 있는 상담의 조합 찾기\nvisited = [False for _ in range(n)]\nstack = []\nans = []\n\n\ndef dfs(previous_end):\n # 뒤의 상담들 중에 병행할 수 있는 모든 경우의 수 탐색\n for i in range(previous_end, n):\n current_end = arr[i][0] + i\n if current_end < n:\n stack.append(arr[i][1])\n dfs(current_end)\n stack.pop()\n elif current_end == n:\n stack.append(arr[i][1])\n ans.append(sum(stack))\n stack.pop()\n else:\n ans.append(sum(stack))\n\n\ndfs(0)\nif len(ans) > 0:\n print(max(ans))\nelse:\n print(0)\n","repo_name":"kstew16/algorithm","sub_path":"boj/introduction/14501_Brute.py","file_name":"14501_Brute.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"30333520661","text":"from django.contrib.auth.models import AbstractUser\nfrom django.db import models\n\n\nclass CustomUser(AbstractUser):\n first_name = models.CharField('Имя', max_length=30)\n last_name = models.CharField('Фамилия', max_length=150)\n email = models.EmailField('Почта', unique=True)\n\n class Meta:\n ordering = ('username',)\n verbose_name = 'Пользователь'\n verbose_name_plural = 'Пользователи'\n\n def __str__(self):\n return self.username\n","repo_name":"StanislavRevolution/foodgram-project-react","sub_path":"backend/api_foodgram/users/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"31553704773","text":"from encodings import utf_8\nfrom random import *\n\nalphabet = [None for i in range(26)]\nfor i in range(26):\n alphabet[i] = chr(65 + i)\n\nwith open(\"discours.txt\", \"r\", encoding=\"utf-8\") as fichier:\n chaine = fichier.read()\n\n\ndef transi_markov1lettre(chaine):\n # permet de creer un dictionaire avec les caractères et le nombre d'occurences des carctères suivants\n dico = {}\n n = len(chaine)\n for i in range(n-1):\n if chaine[i] not in dico:\n\n dico[chaine[i]] = {}\n dico[chaine[i]][chaine[i+1]] = 1\n else:\n if chaine[i+1] not in dico[chaine[i]]:\n dico[chaine[i]][chaine[i+1]] = 1\n else:\n dico[chaine[i]][chaine[i+1]] += 1\n return dico\n\n\ndef suitelettre(car, dico):\n D = dico[car]\n somme = 0\n for cle in D:\n somme = somme + D[cle]\n somme = randint(1, somme)\n\n for cle in D:\n if somme > 0:\n prochain_caractere = cle\n somme = somme - D[cle]\n\n return prochain_caractere\n\n\ndef creation_texte(chaine, nbr):\n # creation d'un texte de n caractères en preant en compte les probas du dictionnaire des transiions\n texte = \"\"\n d = transi_markov1lettre(chaine)\n # premier caractère choisi aleatoirement\n premiere_lettre = alphabet[randint(1, 26)]\n premiere_lettre_mini = premiere_lettre.lower()\n\n print(premiere_lettre_mini)\n\n texte = texte + premiere_lettre_mini\n\n # reste des letres du texte\n for i in range(nbr-1):\n if i == 0:\n # suite de la premiere lettre\n car = suitelettre(premiere_lettre_mini, d)\n else:\n car = suitelettre(texte[i], d) # autre caractères\n texte = texte + car\n return texte\n\n\nprint(transi_markov1lettre(chaine))\nprint(creation_texte(chaine, 1000))\n","repo_name":"Baccussss/Generation-Texte","sub_path":"generation aleatoire.py","file_name":"generation aleatoire.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"224213472","text":"import frappe\nfrom frappe import _, msgprint\nfrom frappe.model.document import Document\n\nclass SellingPriceCalcJob(Document):\n\tdef on_submit(self):\n\t\titems = frappe.db.get_list('Item',\n\t\t\tfilters={\n\t\t\t\t'disabled': 0\n\t\t\t},\n\t\t\tfields=['name','margin']\n\t\t)\n\n\t\tfor i in items:\n\t\t\tconvt_margin = 0\n\t\t\tcal_margin = 0\n\t\t\tselling_rate = 0\n\n\t\t\td_warehouse = frappe.db.get_value('Item Default', {'parent': i.name}, ['default_warehouse'])\n\t\t\tval_rate = frappe.db.get_value('Bin', {'item_code': i.name, 'warehouse': d_warehouse}, ['valuation_rate'])\n\n\t\t\tif i.margin and val_rate:\n\t\t\t\tconvt_margin = i.margin/100\n\t\t\t\tcal_margin = convt_margin * val_rate\n\t\t\t\tselling_rate = cal_margin + val_rate\n\n\t\t\t\tif frappe.db.exists(\"Item Price\", {\"item_code\": i.name,\"price_list\":\"Standard Selling\",\"selling\":1}):\n\t\t\t\t\tname = frappe.get_value('Item Price',{'item_code': i.name,'price_list':'Standard Selling','selling':1},'name')\n\t\t\t\t\tp_record = frappe.get_doc(\"Item Price\",name)\n\t\t\t\t\tp_record.price_list_rate = selling_rate\n\t\t\t\t\tp_record.save()\n\t\t\t\telse:\n\t\t\t\t\tpr_add = frappe.new_doc(\"Item Price\")\n\t\t\t\t\tpr_add.item_code = i.name\n\t\t\t\t\tpr_add.price_list = \"Standard Selling\"\n\t\t\t\t\tpr_add.selling = 1\n\t\t\t\t\tpr_add.price_list_rate = selling_rate\n\t\t\t\t\tpr_add.save()\n\n\tdef submit(self):\n\t\tmsgprint(_(\"The Selling Price Calculation task has been enqueued as a background job. In case there is any issue on processing in background, the system will add a comment about the error on this Selling Price Calc Job and revert to the Draft stage\"))\n\t\tself.queue_action('submit', timeout=7000)\n","repo_name":"UsamaNaveed9/mashaan_selling_rate","sub_path":"mashaan_selling_rate/mashaan_selling_rate/doctype/selling_price_calc_job/selling_price_calc_job.py","file_name":"selling_price_calc_job.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"6310470279","text":"# import xgboost as xgb\nfrom xgboost import XGBClassifier\n\ntest_bdt = XGBClassifier(\n max_depth=7, # for 2018\n # max_depth=6,previous value\n n_estimators=100,\n # n_estimators=100,\n # objective='multi:softmax',\n objective=\"binary:logistic\",\n num_class=1,\n # learning_rate=0.001,#for 2018\n # learning_rate=0.0034,#previous value\n # reg_alpha=0.680159426755822,\n # colsample_bytree=0.47892268305051233,\n min_child_weight=20,\n # subsample=0.5606,\n # reg_lambda=16.6,\n # gamma=24.505,\n # n_jobs=5,\n tree_method=\"hist\",\n)\n","repo_name":"kondratyevd/hmumu-coffea","sub_path":"delphes/bdt_models.py","file_name":"bdt_models.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"39052292175","text":"def isBalanced(s):\n hashmap = {\")\":\"(\",\"}\":\"{\",\"]\":\"[\"}\n stack = []\n for i in s:\n if i in hashmap:\n if len(stack)==0:\n return False\n top_element = stack.pop()\n if hashmap[i]!=top_element:\n return False\n else:\n stack.append(i)\n return True if len(stack)==0 else False\ndef longestValidParentheses(s: str) -> int:\n stack = []\n maxi = 0\n hashmap = {\")\":\"(\"}\n c=0\n i=0\n j=len(s)-1\n while i int:\n \n memo = dict()\n \n m, n = len(mat), len(mat[0])\n \n for i in range(m):\n for j in range(n):\n memo[mat[i][j]] = [i, j]\n \n rows = [0]*m\n cols = [0]*n\n \n for i in range(len(arr)):\n x, y = memo[arr[i]]\n rows[x] += 1\n cols[y] += 1\n if rows[x] == n or cols[y] == m:\n return i\n \n return n-1","repo_name":"berthahsu-0217/leetcode-solutions","sub_path":"2661-first-completely-painted-row-or-column/2661-first-completely-painted-row-or-column.py","file_name":"2661-first-completely-painted-row-or-column.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"15211933141","text":"# vim: set tabstop=4:softtabstop=4:shiftwidth=4:noexpandtab\n#\n# Authors:\n#\tBandiola, Al Tristan\n#\tde Guia, Norman Roy\n#\n# This script is made specifically for the analysis of ezproxy logs,\n# which would later be used for the completion of our capstone project.\n#\n# Usage: $ python ezlogparse.py --argument value\n#\n# More details in github.com/nmdeguia/ezlogparse/README.md\n\nimport datetime\nimport ipaddress\nimport numpy as np\nfrom collections import Counter\n\nfrom src import ezparse\nfrom src import ezplot\n\nimport matplotlib.pyplot as plt; plt.rcdefaults()\nimport matplotlib.pyplot as plt\n\ndef generate(args, global_data, items, flag):\n\t# update args globally\n\tglobals().update(args.__dict__)\n\t# set initial value of lowerbound index to 0 in the first iteration\n\tbasetime = items.unixtime[0]\n\tfinaltime = items.unixtime[-1]\n\telapsedtime = finaltime - items.unixtime[0]\n\ttimeslices = int((elapsedtime/timewindow)+1)\n\n\tprint('Generating Statistics')\n\tprint('Initial timestamp: {0} [{1}]'.format(items.unixtime[0], 0))\n\tprint('Final timestamp: {0} [{1}]'.format(finaltime, len(items.unixtime)-1))\n\tprint('Per time slice: {0} seconds.'.format(timewindow))\n\t# print('Total number of items: {0}'.format(len(items.unixtime)))\n\tprint('Number of time slices: {0}'.format(timeslices))\n\n\tif (flag == 0): mode = 'w'\n\telse: mode = 'a'\n\n\tfor iter, x in enumerate(range(timeslices),1):\n\t\tif (verbose): print('--------------------------------------------------')\n\n\t\titems.string.append('Timeslice no. {0} ({1} - {2})'.format(\n\t\t\titer, basetime, basetime+timewindow))\n\t\tif (verbose): print(items.string[-1])\n\n\t\t# initialize time slice indices\n\t\tuppertime = basetime + timewindow\n\t\tbaseindex = items.locate_index(basetime)\n\n\t\t# set ceiling value for uppertime\n\t\tif uppertime >= items.unixtime[-1]: uppertime = items.unixtime[-1]\n\t\tupperindex = items.locate_index(uppertime)\n\n\t\tif upperindex != baseindex:\n\t\t\t#length = len(items.unixtime[baseindex:upperindex])\n\t\t\tif (x != timeslices-1): upperindex -= 1\n\t\t\telse: upperindex = items.locate_index(uppertime)\n\t\t# else: length = 0\n\n\t\t# get unixtime value of upperbound and lowerbound indices\n\t\tbaseindexvalue = items.unixtime[baseindex]\n\t\tupperindexvalue = items.unixtime[upperindex]\n\n\t\titems.string.append('{0} to {1}'.format(\n\t\t\tdatetime.datetime.fromtimestamp(\n\t\t\t\tint(baseindexvalue)).strftime('%Y-%m-%d %H:%M:%S'),\n\t\t\tdatetime.datetime.fromtimestamp(\n\t\t\t\tint(upperindexvalue)).strftime('%Y-%m-%d %H:%M:%S')\n\t\t\t))\n\t\tif (verbose): print(items.string[-1])\n\t\titems.string.append('Base: {0} [{1}], Upper: {2} [{3}]'.format(\n\t\t\tbaseindexvalue, baseindex, upperindexvalue, upperindex))\n\t\tif (verbose): print(items.string[-1])\n\t\t# items.string.append('Number of items in sublist: {0}'.format(length))\n\t\t# if (verbose): print(items.string[-1])\n\n\t\t# statistical function generation starts here\n\t\tunique_content,_,_ = items.get_unique_content(baseindex, upperindex)\n\t\ton_conn, off_conn = cnt_oncampus_requests(unique_content, oncampaddr, items.string)\n\n\t\t# get total number of unique items per logfile\n\t\tif (iter == 1):\n\t\t\tunique_items = len(unique_content)\n\t\t\tunique_on_conn = on_conn\n\t\t\tunique_off_conn = off_conn\n\t\telse:\n\t\t\tunique_items += len(unique_content)\n\t\t\tunique_on_conn += on_conn\n\t\t\tunique_off_conn += off_conn\n\n\t\t# checks if timeslice is the last one\n\t\t# ends loop if timeslice reaches EOL\n\t\tif x == timeslices-1: break\n\t\telse: basetime = uppertime\n\n\titems.finalize()\n\tcommon_sites = items.get_unique_sites()\t#[0] - site, [1] - frequency\n\n\t# gets frequency (ufreq) from unique items (end to end of month)\n\t_,_,ufreq = items.get_unique_content(0, len(items.unixtime)-1)\n\n\tglobal_data[1].append(unique_items)\n\tglobal_data[2].append(unique_on_conn)\n\tglobal_data[3].append(unique_off_conn)\n\tglobal_data[4].append(len(common_sites))\n\n\t# gets the sites and frequency of common sites used\n\tfor sites, sfreq in common_sites:\n\t\tglobal_data[5].append(sites)\n\t\tglobal_data[6].append(sfreq)\n\n\t# adds the frequency to the list and sorts it in descending order\n\tglobal_data[7] = sorted(global_data[7] + ufreq, reverse=True)\n\n\titems.string.append('Total no. of unique items in log: {0}'.format(unique_items))\n\tprint(items.string[-1])\n\ttemp = '\\n'.join(i for i in items.string) + '\\n'\n\tezparse.dump_string_to_out(temp, statfile, mode)\n\treturn items\n\ndef cnt_oncampus_requests(data, oncampaddr, strings):\n\ton_campus_count = 0\n\toff_campus_count = 0\n\tunicode_ip_net = str(oncampaddr)\n\tfor i in range(len(data)):\n\t\tunicode_ip_request = str(data[i][0])\n\t\tif ipaddress.ip_address(\n\t\t\tunicode_ip_request) in ipaddress.ip_network(unicode_ip_net):\n\t\t\ton_campus_count += 1\n\t\telse: off_campus_count += 1\n\tstrings.append('Number of on-campus accesses: {0}'.format(on_campus_count))\n\tif (verbose): print(strings[-1])\n\tstrings.append('Number of off-campus accesses: {0}'.format(off_campus_count))\n\tif (verbose): print(strings[-1])\n\treturn on_campus_count, off_campus_count\n\n# generate plots for statistical data\n# parameters: generate_bar_graph\n# (x_axis, item_label, x_items, y_items, x_label, y_label, title, filename, rotation_value)\n# paramters: generate_pie_chart\n# (sizes, labels, title, filename)\n# parameters: generate_line_graph\ndef plot_data(plot, global_data, dir):\n\tif (plot): #and dir!=None):\n\t\tezplot.generate_bar_graph(\n\t\t\tnp.arange(len(global_data[0])),[(datetime.date(year=int(str(\n\t\t\ts.strip((dir) + '\\\\ezp.'))[0:4]),month=int(str(s.strip((\n\t\t\tdir) + '\\\\ezp.'))[4:]), day=1).strftime(\"%b%Y\")) for s in global_data[0]],\n\t\t\tglobal_data[0], global_data[1], '', 'Total no. of Requests',\n\t\t\t'Total no. of Unique Requests in One Year', 'plot_requests_total.png', 0\n\t\t)\n\t\tezplot.generate_pie_chart(\n\t\t\t[sum(global_data[2]), sum(global_data[3])],\n\t\t\t['On Campus', 'Off Campus'], 'Percentage of Total Connections',\n\t\t\t'plot_connections_total.png'\n\t\t)\n\t\tezplot.generate_bar_graph(\n\t\t\tnp.arange(len(global_data[5])),\n\t\t\t[i.partition('.')[-1].partition('.')[0] for i in global_data[5]],\n\t\t\tglobal_data[5], global_data[6], '', 'Frequency',\n\t\t\t'Top Sites per Month', 'plot_sites_frequency.png', 85\n\t\t)\n\t\t# total zipf distribution of all months\n\t\t# FIXME: this only appends the unique for each month,\n\t\t# not the unique for the whole dataset\n\t\tezplot.generate_line_graph(\n\t\t\trange(len(global_data[7])), global_data[7],\n\t\t\t'Content ID Number', 'Frequency',\n\t\t\t'Zipf Distribution', 'zipf_distribution.png'\n\t\t)\n\telse: pass\n","repo_name":"nmdeguia/ezlogparse","sub_path":"src/ezstat.py","file_name":"ezstat.py","file_ext":"py","file_size_in_byte":6327,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"3217551324","text":"from time import ctime , sleep\ndef nufemit(func):\n\tdef cnufdepparw():\n\t\tprint(\" called at %s\"%(ctime()))\n\t\tfunc()\n\treturn cnufdepparw\n\n@nufemit\ndef foo():\n\tprint(\"I am foo\")\n\n@nufemit\ndef getInfo():\n\tx = '----I love python----'\n\tprint(x)\nwhile True:\n\tsleep(0.2)\n\tfoo()\n\tsleep(0.2)\n\ts = 0\n\ts = 156456455158945614474948646*2\n\tsleep(0.2)\n\tfoo()\n\tprint(\"def mak{}eBold(fn): _____de__ + fn() + \",\"def makeItalic(1():return hello world-@makeItalicdef test2():return hello world-2\")\n\tsleep(0.2)\n\tprint(a)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Hiref/2.1803-Python","sub_path":"14day/04-装饰器中的return.py","file_name":"04-装饰器中的return.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"33367743893","text":"from typing import Dict, Any\n\nparams: Dict[str, Any] = {\n # Maximal number of input tensors for variadic operators\n 'spec.max_in_num': 4,\n # Maximal number of output tensors for variadic operators\n 'spec.max_out_num': 3,\n # Maximal rank of tensor\n 'spec.max_rank': 5,\n # Maximal dimension value in tensor shape\n 'spec.max_dim': 4,\n\n # Maximal number of model candidates\n 'solver.max_model_cand': 1,\n # Length (in bits) of bit vector\n 'solver.bit_vec_len': 32,\n\n # Maximal number of operation vertices in a graph\n 'graph.max_opr_num': 32,\n # Penalty coefficient on number of uses of a value\n 'graph.use_penal': 4,\n # Number of records in diversity history of each operator\n 'graph.num_div_record': 16,\n # Scale of the normalized diversity score\n 'graph.div_score_scale': 0.2,\n # Probability of rejecting a non-unique operation\n 'graph.reject_prob': 0.9,\n # Number of trials for generating one operation\n # For variadic operators, this is the maximal number of trials of adding a new input value\n 'graph.opr_trials': 3,\n\n # Maximal kernel size of convolution\n 'op.max_kernel': 3,\n # Maximal stride of convolution\n 'op.max_stride': 2,\n # Maximal padding\n 'op.max_padding': 2,\n # Maximal dilation rate of convolution\n 'op.max_dilation': 2,\n}\n\n# Operators that are commonly supported by all the baselines\ncommon_ops = [\n 'sigmoid',\n 'add',\n 'subtract',\n 'multiply',\n 'maximum',\n 'minimum',\n 'reshape',\n 'transpose',\n 'concatenate',\n 'strided_slice',\n 'nn.relu',\n 'nn.leaky_relu',\n 'nn.prelu',\n 'nn.softmax',\n 'nn.conv1d',\n 'nn.conv2d',\n 'nn.max_pool2d',\n 'nn.avg_pool2d',\n 'nn.pad',\n 'nn.batch_norm',\n 'nn.dense',\n 'nn.bias_add',\n]\n","repo_name":"wzh99/GenCoG","sub_path":"gencog/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"77"}
+{"seq_id":"27790200978","text":"#!/usr/bin/python\n#\n# Author: Peter Prettenhofer \n#\n# License: BSD Style\n\n\"\"\"A mapper for hadoop task parallelism.\n\nTo test the mapper locally use:\n> cat tasks.txt| ./mapper.py\n\n\nTo send to Hadoop use:\nhadoop jar /usr/lib/hadoop/contrib/streaming/hadoop-0.18.3-2cloudera0.3.0-streaming.jar \\\n -input tmptasks.txt \\\n -output tmpout \\\n -mapper dumbo.py \\\n -file dumbo.py \\\n -file examples.npy \\\n -jobconf mapred.reduce.tasks=0 \\\n -jobconf mapred.input.format.class=org.apache.hadoop.mapred.lib.NLineInputFormat \\\n -jobconf mapred.line.input.format.linespermap=1\n\n\n\"\"\"\n \nimport sys\nimport os\nimport pickle\nimport numpy as np\n\ntry:\n import json\nexcept ImportError:\n import simplejson as json\n\nimport bolt\nimport util\nfrom auxtrainer import *\n\n\ndef serialize(arr):\n return \" \".join([\"%d:%.20f\" %(idx, arr[idx]) for idx in arr.nonzero()[0]])\n\n\ndef main(separator='\\t'):\n # input comes from STDIN (standard input)\n\n ds = bolt.io.MemoryDataset.load(\"examples.npy\", verbose=0)\n instances = ds.instances[ds._idx]\n task_masks = None\n if os.path.exists(\"task_masks.pkl\"):\n f = open(\"task_masks.pkl\", \"rb\")\n task_masks = pickle.load(f)\n f.close()\n\n for line in sys.stdin.xreadlines():\n line = line.rstrip()\n rid = \"rid\" + str(hash(line)) # run id\n line = line.split(\"\\t\")[-1]\n params = json.loads(line)\n taskid = params[u\"taskid\"]\n auxtask = np.array(params[u\"task\"])\n trainer = eval(params[u\"trainer\"])\n\n # label according to auxtask\n labels = util.autolabel(instances, auxtask)\n\n # mask features (either only auxtask or provided masks)\n mask = np.ones((ds.dim,), dtype=np.int32, order=\"C\")\n if task_masks != None:\n mask[task_masks[taskid]] = 0\n else:\n mask[auxtask] = 0\n\n new_dataset = bolt.io.MemoryDataset(ds.dim, instances, labels)\n\n w = trainer.train_classifier(new_dataset, mask)\n sw = serialize(w)\n print >> sys.stdout, \"%d\\t%s\" % (taskid, sw)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"pprett/nut","sub_path":"nut/structlearn/dumbomapper.py","file_name":"dumbomapper.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","stars":119,"dataset":"github-code","pt":"77"}
+{"seq_id":"13823866238","text":"# 1.creating a function and retuing calc\r\ndef calc(x,y):\r\n add = x+y\r\n sub = x-y\r\n mul = x*y\r\n div = x/y\r\n \r\n print(\"the sum is\",add)\r\n print(\"the diference is:\",sub)\r\n print(\"the multiplication is\",mul)\r\n print(\"the division is \",div)\r\nx = int(input(\"enter first value\"))\r\ny = int(input(\"enter second value\"))\r\ncalc(x,y)\r\n \r\n\r\n#2. using function covid()\r\n\r\ndef covid(name,temp):\r\n\r\n print(\"name of patient is\",name)\r\n if temp ==\"\":\r\n print(\"body temp is 98 \")\r\n else:\r\n print(\"body temp is\",temp)\r\n\r\n\r\nname = input(\"enter name\")\r\ntemp = input(\"enter body temp\")\r\ncovid(name,temp)\r\n","repo_name":"gopalreddy-developer/-python-boot-camp","sub_path":"day 7.py","file_name":"day 7.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"70244478330","text":"\"\"\"This script will return the the charge and spin into a more readable format.\"\"\"\n\n\ndef get_iteration_pairs():\n \"\"\"\n Reads through the qmscript.out and counts iterations per scan step.\n Then returns then as a dictionary: {scan_number:iterations}.\n\n Parameters\n ----------\n pdb_name : str\n The name of the PDB that the user would like processed.\n\n Returns\n -------\n iteraction_pairs : dictionary\n The scan step number as the key and iterations as the value.\n\n \"\"\"\n # Read in the TeraChem output, the charge, and the spin\n opt_count = 0\n scan_count = 0\n scan_step_pairs = {}\n with open(\"./qmscript.out\", \"r\") as qmscript:\n for line in qmscript:\n if line[:14] == \"FINAL ENERGY: \":\n opt_count += 1\n if line[:24] == \"-=#=- Optimized Energy: \":\n scan_count += 1\n scan_step_pairs[scan_count] = opt_count\n opt_count = 0\n\n # Convert dictionary to additive list\n final_scan_position = []\n running_count = 0\n for key, value in scan_step_pairs.items():\n running_count += value\n final_scan_position.append(running_count)\n\n return final_scan_position, scan_step_pairs\n\n\ndef get_scan_spins(final_scan_position):\n \"\"\"\n Extracts spin sections from mullpop for each scan and stores them as a dict.\n\n Parameters\n ----------\n iter_pairs : dictionary\n The scan step number as the key and iterations as the value.\n\n Returns\n -------\n spin_pairs : dictionary\n The scan step number as the key and the spin section as the key.\n \"\"\"\n section_count = 0\n section_content = \"\"\n sections = []\n current_section = 0\n section_found = False\n with open(\"./scr/mullpop\", \"r\") as spins:\n for line in spins:\n if line[29:42] == \"Spin-Averaged\":\n current_section += 1\n if current_section == final_scan_position[section_count]:\n section_count += 1\n section_found = True\n elif section_found:\n sections.append(section_content)\n section_found = False\n section_content = \"\"\n\n # Combine all lines of a final section into a single string\n if section_found:\n section_content += line\n\n # Add the last section of the file to the list of sections\n if section_found:\n sections.append(section_content)\n\n # Write the spin data for the final step of each scan step to a file\n with open(\"./scr/1.spin\", \"w\") as scan_spin_file:\n for index, section in enumerate(sections):\n scan_spin_file.write(section)\n scan_spin_file.write(f\"End scan {index + 1}\\n\")\n\n return sections\n\n\ndef get_scan_charges(final_scan_position):\n \"\"\"\n Extracts charges from charge_mull.xls for each scan and stores them as a dict.\n\n Parameters\n ----------\n iter_pairs : dictionary\n The scan step number as the key and iterations as the value.\n\n Returns\n -------\n charge_pairs : dictionary\n The scan step number as the key and the charge section as the key.\n \"\"\"\n section_count = 0\n section_content = \"\"\n sections = []\n current_section = 0\n section_found = False\n with open(\"./scr/charge_mull.xls\", \"r\") as charges:\n for line in charges:\n line_content = line.split()\n if line_content[0] == \"1\":\n current_section += 1\n if current_section == final_scan_position[section_count]:\n section_count += 1\n section_found = True\n elif section_found:\n sections.append(section_content)\n section_found = False\n section_content = \"\"\n\n # Combine all lines of a final section into a single string\n if section_found:\n section_content += line\n\n # Add the last section of the file to the list of sections\n if section_found:\n sections.append(section_content)\n\n # Write the charge data for the final step of each scan step to a file\n with open(\"./scr/1.charge\", \"w\") as scan_charge_file:\n for index, section in enumerate(sections):\n scan_charge_file.write(section)\n scan_charge_file.write(f\"End scan {index + 1}\\n\")\n\n return sections\n\n\ndef pes_organizer():\n print(\"\\n.---------------.\")\n print(\"| PES ORGANIZER |\")\n print(\".---------------.\\n\")\n print(\"Use the ml_prop keyword when running your TeraChem scan.\")\n print(\"Execute this script from the directory where the job was run.\")\n print(\"TeraChem scans only print the charge and spin of the final frame.\")\n print(\"With the ml_prop keyword, every optimization will print.\")\n print(\"However, we only need the final charge and spin.\")\n print(\"This script will return the charge and spin in a readable format.\")\n\n final_scan_position, scan_step_pairs = get_iteration_pairs()\n get_scan_spins(final_scan_position)\n get_scan_charges(final_scan_position)\n\n\nif __name__ == \"__main__\":\n pes_organizer()\n","repo_name":"davidkastner/pyQMMM","sub_path":"pyqmmm/qm/pes_organizer.py","file_name":"pes_organizer.py","file_ext":"py","file_size_in_byte":5174,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"77"}
+{"seq_id":"30282994456","text":"\"\"\"WebApp 기본 데이터를 DB에 추가\r\n+ 관리자 계정\r\n+ json\r\n\"\"\"\r\n\r\nfrom datetime import date, datetime, time, timedelta, timezone\r\nimport flask as fl\r\nimport werkzeug.security as wsec\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nimport json, sys\r\n\r\n#! import all models\r\nfrom .group import Group\r\nfrom .user import AppUser\r\nfrom .location import Location\r\nfrom .sensor import Sensor\r\nfrom .cams_info import Cams\r\nimport utility as util\r\n\r\n# seed data files\r\nSEED_MASTER_FILE = \"seed-master.json\" # 마스터 계정과 테스트용 센서 추가\r\nSEED_TEST_FILE = \"seed-test.json\" # 마스터 계정과 테스트용 센서 추가\r\n\r\n\r\ndef seed():\r\n \"\"\"DB 작업 수행\"\"\"\r\n\r\n dba: SQLAlchemy = fl.g.dba\r\n\r\n # 관리 정보 추가\r\n dba.session.add(Cams(\"cams_setup_date\", datetime.now().isoformat()))\r\n dba.session.add(Cams(\"cams_start_date\", datetime.now().isoformat()))\r\n dba.session.commit()\r\n\r\n # ----[ 마스터 계정 ]----\r\n seed_group_json(SEED_MASTER_FILE)\r\n\r\n # ----[ 추가 그룹 ]---- TODO: 파일목록을 셋팅스에\r\n files = fl.g.settings[\"Cams\"][\"DB_SEED_FILES\"]\r\n [seed_group_json(fn) for fn in files]\r\n\r\n # ----[ 테스트 그룹 ]----\r\n if getattr(sys, \"_test_\"):\r\n from . import sensor_data as sd\r\n\r\n groups = seed_group_json(SEED_TEST_FILE)\r\n for group in groups:\r\n sd.f3_seed(group.sensors) # 랜덤 센서 데이터 추가\r\n\r\n\r\n# json 파일에서 읽어와 DB에 추가\r\ndef seed_group_json(filename: str) -> Group:\r\n \"\"\"json 파일에서 group을 읽어들여 DB에 추가\"\"\"\r\n\r\n # read json\r\n with open(filename, \"r\", encoding=\"utf-8\") as fp:\r\n dics = json.load(fp)\r\n\r\n groups = []\r\n db: SQLAlchemy = fl.g.dba.session\r\n for jG in dics:\r\n\r\n # Group 생성\r\n if \"id\" in jG:\r\n gid = jG[\"id\"]\r\n group = Group(id=gid, name=jG[\"name\"], desc=jG[\"desc\"])\r\n if gid > 0:\r\n Group.reset_id_seq(gid)\r\n else:\r\n group = Group(name=jG[\"name\"], desc=jG[\"desc\"])\r\n\r\n # AppUser 생성\r\n for jUser in jG[\"users\"]:\r\n pw = jUser[\"password\"]\r\n pwHash = pw if pw.startswith(\"pbkdf2:\") else util.generate_password_hash(pw)\r\n user = AppUser(\r\n username=jUser[\"username\"],\r\n password=pwHash,\r\n email=jUser[\"email\"],\r\n realname=jUser[\"realname\"],\r\n )\r\n if \"level\" in jUser:\r\n user.level = jUser[\"level\"]\r\n group.users.append(user)\r\n\r\n # Location 생성\r\n for jLoc in jG[\"locations\"]:\r\n loc = Location(name=jLoc[\"name\"], desc=jLoc[\"desc\"])\r\n group.locations.append(loc)\r\n\r\n # Sensor 생성\r\n for jS in jLoc[\"sensors\"]:\r\n sensor = Sensor(sn=jS[\"sn\"], name=jS[\"name\"])\r\n sensor.activate(active=jS[\"active\"])\r\n loc.sensors.append(sensor)\r\n \r\n group.sensors.extend(loc.sensors)\r\n\r\n db.add(group)\r\n db.commit()\r\n\r\n # set group.storage_id\r\n group.storage_id = min([l.id for l in group.locations])\r\n db.commit()\r\n\r\n groups.append(group)\r\n\r\n return groups\r\n\r\n\r\ndef save_groups_json(groups, filename):\r\n \"\"\"group 리스트를 json 파일에 저장\"\"\"\r\n\r\n dic = [_group_to_dic(group) for group in groups]\r\n\r\n with open(filename, \"w\", encoding=\"utf-8\") as fp:\r\n json.dump(dic, fp, indent=4, ensure_ascii=False)\r\n\r\n util.info(f\"{filename} saved\")\r\n\r\n\r\ndef _group_to_dic(group):\r\n \"\"\"group을 json 직렬화에 적합한 dict으로 변환\"\"\"\r\n\r\n dic = group.to_dict()\r\n dic[\"users\"] = [u.to_dict() for u in group.users]\r\n\r\n locs = []\r\n for l in group.locations:\r\n locDic = l.to_dict()\r\n locDic[\"sensors\"] = [s.to_dict() for s in l.sensors]\r\n locs.append(locDic)\r\n\r\n # python3.9: z = x|y\r\n dic[\"locations\"] = [\r\n {**l.to_dict(), **{\"sensors\": [s.to_dict() for s in l.sensors]}}\r\n for l in group.locations\r\n ]\r\n\r\n dic = _clean_nones(dic)\r\n return dic\r\n # return json.dumps(dic, indent=4, ensure_ascii=False)\r\n\r\n\r\ndef _clean_nones(value):\r\n \"\"\"리스트와 사전에서 None값을 제거하여 새 객체 리턴\"\"\"\r\n\r\n # 리스트\r\n if isinstance(value, list):\r\n return [_clean_nones(x) for x in value if x is not None]\r\n\r\n # 사전\r\n elif isinstance(value, dict):\r\n return {key: _clean_nones(val) for key, val in value.items() if val is not None}\r\n\r\n # 그외값\r\n else:\r\n return value\r\n\r\n\r\n# def reset_id_seq(modelName, id):\r\n# dba: SQLAlchemy = fl.g.dba\r\n# dba.session.execute(f\"ALTER SEQUENCE {modelName}_id_seq RESTART WITH {id + 1}\")\r\n","repo_name":"free302-b2f/cams-server","sub_path":"cams/db/_seed.py","file_name":"_seed.py","file_ext":"py","file_size_in_byte":4778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"2494318038","text":"import random\r\nimport glob\r\n\r\nimport os\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport seaborn as sns\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\nimport plotly as py\r\n\r\nimport plotly.graph_objs as go\r\nfrom plotly.offline import iplot\r\n\r\nfrom IPython.display import display\r\nfrom IPython.display import Image\r\n\r\nfrom sklearn.utils import all_estimators\r\nfrom sklearn.decomposition import PCA\r\nfrom sklearn.cluster import *\r\nfrom sklearn.preprocessing import *\r\n\r\nclass MD_clustering:\r\n\r\n def __init__(self):\r\n self.colors = ['rgba(255, 128, 255, 0.8)','rgba(255, 128, 2, 0.8)','rgba(0, 255, 200, 0.8)','rgba(0, 0, 255, 0.8)','rgba(255, 255,115, 0.8)','rgba(255, 0,0, 0.8)','rgba(98, 0,131, 0.8)', 'rgba(255,235,215,0.8)', 'rgba(125,38,205,0.8)','rgba(0, 0, 0, 0.8)','rgba(139,69,19,0.8)','rgba(238,232,205,0.8)','rgba(193,255,193,0.8)','rgba(153,50,204,0.8)']\r\n self.label_col_bool = False\r\n self.label_col = None\r\n self.plotX = None\r\n self.data_clustered = None\r\n self.data_scaled = None\r\n self.data_inverse_scaled = None\r\n self.save_col = None\r\n self.data_final = None\r\n self.loadings = None\r\n self.get_clusters()\r\n\r\n def get_clusters(self):\r\n estimators = all_estimators(type_filter='cluster')\r\n self.all_clusters = []\r\n for name, RegressorClass in estimators:\r\n try:\r\n reg = RegressorClass\r\n self.all_clusters.append(reg)\r\n except Exception as e:\r\n print(e)\r\n \r\n\r\n def load_data(self, filename='', sep=',',decimal='.',label_column_name=None, preprocessed = False):\r\n \"\"\"\r\n Function loads data from a csv file only based on filename/path.\r\n\r\n Args:\r\n filename (str, non-optional): Origin filename/path.\r\n sep (str, optional): Seperator for csv file. Defaults to ','.\r\n decimal (str, optional): Decimal for csv file. Defaults to '.'.\r\n label_column_name (str, optional): If data set contains a label column (i.e., company names). Defaults to None.\r\n preprocessed (bool, optional): If data has been preprocessed prior then it will save it to according variables. Defaults to False.\r\n \"\"\"\r\n if filename == '':\r\n print('File path for loading data is empty.')\r\n else:\r\n self.data = pd.read_csv(filepath_or_buffer=filename, sep=sep, decimal=decimal)\r\n\r\n if label_column_name != None:\r\n self.label_column_name = label_column_name\r\n self.label_col = pd.DataFrame(self.data[self.label_column_name])\r\n self.data.drop(self.label_column_name, inplace=True, axis=1)\r\n self.label_col_bool = True\r\n\r\n if preprocessed:\r\n self.data_scaled = self.data\r\n \r\n def save_data(self, filename = 'final_result_MD.csv', X = '', sep = ';', decimal='.'):\r\n \"\"\"\r\n Function saves the final resulting dataframe into a csv file within the current folder.\r\n Args:\r\n filename (str, optional): Output filename. Defaults to 'final_result_MD.csv'.\r\n X (str, optional): [description]. Defaults to self.data_clustered / self.data_final.\r\n sep (str, optional): Seperator for csv file. Defaults to ';'.\r\n decimal (str, optional): Decimal for csv file. Defaults to '.'.\r\n \"\"\"\r\n \r\n if not(isinstance(X, pd.DataFrame)) and X == '' and not(isinstance(self.data_final, pd.DataFrame)):\r\n X = self.data_clustered\r\n elif isinstance(self.data_final, pd.DataFrame):\r\n X = self.data_final\r\n \r\n if not os.path.exists('output_data'):\r\n os.makedirs('output_data')\r\n print('Created new folder @output_data where all results will be stored.')\r\n X.to_csv('output_data/'+filename, sep=sep, decimal=decimal)\r\n\r\n \r\n\r\n def scale_data(self, X='', scaler=MinMaxScaler()):\r\n \"\"\"\r\n Function scales data 'X' from user inputed desired 'scaler'. (i.e., MaxAbsScaler, MinMaxScaler, StandardScaler)\r\n \r\n Args:\r\n X (pd.DataFrame, optional): A data set given as a dataframe to be scaled. Defaults to self.data. \r\n scaler (function, optional): A scaling function from sklearn, or one that has the functionality of 'fit_transform' and 'inverse_transform'. Defaults to MinMaxScaler.\r\n \"\"\"\r\n if not(isinstance(X, pd.DataFrame)) and X == '':\r\n X = self.data.copy()\r\n self.scaler = scaler\r\n X = pd.DataFrame(self.scaler.fit_transform(X), columns = X.columns)\r\n self.data_scaled = X\r\n\r\n def inverse_scale(self, X=''):\r\n if not(isinstance(X, pd.DataFrame)) and X == '':\r\n X = self.data_scaled.copy()\r\n self.data_inverse_scaled = pd.DataFrame(self.scaler.inverse_transform(X), columns= X.columns)\r\n self.data_inverse_scaled = pd.concat([self.label_col, self.data_inverse_scaled], axis=1)\r\n\r\n if 'Cluster' not in self.data_inverse_scaled.columns:\r\n self.data_inverse_scaled = pd.concat([self.clusters_l, self.data_inverse_scaled], axis=1)\r\n\r\n\r\n def drop_cols(self, cols='',save_cols=''):\r\n \"\"\"\r\n Function drops an entire column from loaded self.data.\r\n \r\n Args:\r\n cols (list, optional): A list of column names to be dropped.\r\n save_cols (list, optional): A list of column names to be dropped but will be saved for the possibility of later re-attachment. \r\n All operations such as scaling will be perfomed on this DF too.\r\n \"\"\"\r\n if isinstance(self.data_scaled, pd.DataFrame):\r\n if isinstance(cols, list):\r\n self.dropped_columns = self.data[cols]\r\n self.data_scaled.drop(cols, inplace=True, axis=1)\r\n elif cols != '':\r\n self.dropped_columns = self.data[[cols]]\r\n self.data_scaled.drop([cols], inplace=True, axis=1)\r\n \r\n if isinstance(save_cols, list):\r\n self.save_col = self.data_scaled[save_cols]\r\n self.data_scaled.drop(save_cols, inplace=True, axis=1)\r\n elif save_cols != '':\r\n self.save_col = self.data_scaled[save_cols]\r\n self.data_scaled.drop([save_cols], inplace=True, axis=1)\r\n elif isinstance(self.data, pd.DataFrame):\r\n if isinstance(cols, list):\r\n self.dropped_columns = self.data[cols]\r\n self.data.drop(cols, inplace=True, axis=1)\r\n elif cols != '':\r\n self.dropped_columns = self.data[[cols]]\r\n self.data.drop([cols], inplace=True, axis=1)\r\n \r\n if isinstance(save_cols, list):\r\n self.save_col = self.data[save_cols]\r\n self.data.drop(save_cols, inplace=True, axis=1)\r\n elif save_cols != '':\r\n self.save_col = self.data[save_cols]\r\n self.data.drop([save_cols], inplace=True, axis=1)\r\n \r\n def concat_saved_cols(self, X=''):\r\n if not(isinstance(X, pd.DataFrame)) and X == '':\r\n if isinstance(self.data_inverse_scaled, pd.DataFrame):\r\n X = self.data_inverse_scaled.copy()\r\n else:\r\n X = self.data_clustered.copy()\r\n self.data_final = pd.concat([X, self.save_col], axis =1)\r\n\r\n def drop_rows(self, rows):\r\n \"\"\"\r\n Function drops [row_index_1, row_index_n, ...] from loaded data set in self.data and also from label_col if it exists.\r\n Make sure rows is a list.\r\n \r\n Args:\r\n rows (list, non-optional): A list of row indices.\r\n \"\"\"\r\n self.data.drop(rows, axis=0, inplace=True)\r\n self.data.reset_index(drop=True, inplace=True)\r\n\r\n if isinstance(self.label_col, pd.DataFrame):\r\n self.label_col.drop(list(rows), inplace=True, axis=0)\r\n self.label_col.reset_index(drop=True, inplace=True)\r\n\r\n if isinstance(self.save_col, pd.DataFrame):\r\n self.save_col.drop(list(rows), inplace=True, axis=0)\r\n self.save_col.reset_index(drop=True, inplace=True)\r\n\r\n def get_n_clusters(self, X='', min_n = 1, max_n = 11, show=True):\r\n \"\"\"\r\n This function visualizes the 'Elbow Method' for KMeans, showing the \r\n predicted optimal n_clusters for 'X' based on inertia.\r\n \r\n Args:\r\n X (pd.DataFrame, non-optional): Unclustered original data set.\r\n min_n (int, optional): Minimum desired clusters. Defaults to 1.\r\n max_n (int, optional): Maximum desired clusters. Defaults to 11.\r\n \"\"\"\r\n\r\n if not(isinstance(X, pd.DataFrame)) and X == '':\r\n if isinstance(self.data_scaled, pd.DataFrame):\r\n X = self.data_scaled.copy()\r\n elif isinstance(self.data, pd.DataFrame):\r\n X = self.data.copy()\r\n\r\n pca = PCA(n_components=np.shape(X)[1])\r\n principalComponents = pca.fit_transform(X)\r\n PCA_components = pd.DataFrame(principalComponents) \r\n ks = range(min_n,max_n)\r\n inertias = []\r\n\r\n for k in ks:\r\n # Create a KMeans instance with k clusters: model\r\n km_model = KMeans(n_clusters=k)\r\n\r\n # Fit model to samples\r\n km_model.fit(PCA_components.iloc[:,:3])\r\n\r\n # Append the inertia to the list of inertias\r\n inertias.append(km_model.inertia_)\r\n if show:\r\n plt.plot(ks, inertias, '-o', color='black')\r\n plt.xlabel('number of clusters, k')\r\n plt.ylabel('inertia')\r\n plt.xticks(ks)\r\n plt.show()\r\n \r\n\r\n def get_loading_scores(self, X='', pca_components=3, positive_cor = False, show=True):\r\n \"\"\"\r\n The function visualizes the importance of each feature in data set 'X' to n 'pca_components'.\r\n \r\n Args:\r\n X (pd.DataFrame, non-optional): Original unclustered data set.\r\n pca_components (int, non-optional): Desired amount of visualized principal components. Defaults to 3.\r\n positive_cor (bool, optional): If user only wants to see the positive correlated features to each PC. Defaults to False.\r\n show (bool, optional): If user wants to see the graphical displays. Defaults to True\r\n \"\"\"\r\n \r\n if not(isinstance(X, pd.DataFrame)) and X == '':\r\n if isinstance(self.data_scaled, pd.DataFrame):\r\n X = self.data_scaled.copy()\r\n elif isinstance(self.data, pd.DataFrame):\r\n X = self.data.copy()\r\n\r\n # Train PCA\r\n pca = PCA().fit(X)\r\n\r\n if show:\r\n # Cumulative Variance Plot\r\n plt.plot(pca.explained_variance_ratio_.cumsum(), lw=3, color='#087E8B')\r\n plt.title('Cumulative explained variance by number of principal components', size=20)\r\n plt.show()\r\n\r\n # PCA Loading Score Plots\r\n self.loadings = pd.DataFrame(data=pca.components_.T * np.sqrt(pca.explained_variance_), columns=[f'PC{i}' for i in range(1, len(X.columns) + 1)], index = X.columns)\r\n self.pca_loadings_list = []\r\n for i in range(1, pca_components+1):\r\n pc_loadings = self.loadings.sort_values(by='PC{}'.format(i), ascending=False)[['PC{}'.format(i)]]\r\n pc_loadings = pc_loadings.reset_index()\r\n pc_loadings.columns = ['Attribute', 'CorrelationWithPC{}'.format(i)]\r\n self.pca_loadings_list.append(pc_loadings)\r\n\r\n # Get positive correlation, remove if want to see all correlations to a PC\r\n if positive_cor:\r\n pc_loadings = pc_loadings[pc_loadings['CorrelationWithPC{}'.format(i)] >= 0]\r\n\r\n if show:\r\n plt.bar(x=pc_loadings['Attribute'], height=pc_loadings['CorrelationWithPC{}'.format(i)], color='#087E8B')\r\n plt.title('PCA loading scores (principal component #{}'.format(i), size=20)\r\n plt.xticks(rotation='vertical')\r\n plt.show()\r\n\r\n # Display values as a dataframe\r\n display(pd.DataFrame(pc_loadings))\r\n \r\n def cluster(self, X='', model=None, clusters_n=3,seed=None):\r\n \"\"\"\r\n Function clusters the data 'X' into 'clusters_n' clusters'. It then also finds the 1st, 2nd and 3rd PC.\r\n\r\n Args:\r\n X (pd.DataFrame, non-optional): A dataframe of X unclustered data.\r\n clusters_n (int, non-optional): An integer to cluster the data 'X' into n clusters. Defaults to 3.\r\n \"\"\"\r\n\r\n if not(isinstance(X, pd.DataFrame)) and X == '':\r\n if isinstance(self.data_scaled, pd.DataFrame):\r\n X = self.data_scaled.copy()\r\n elif isinstance(self.data, pd.DataFrame):\r\n X = self.data.copy()\r\n x = X.copy()\r\n \r\n if model==None:\r\n self.model = KMeans(n_clusters=clusters_n, random_state=seed)\r\n elif type(model) in self.all_clusters:\r\n self.model = model\r\n elif not(type(model) in self.all_clusters):\r\n print('Given model is not recognized or part of sklearn.cluster classes. Please provide a model from the following list: \\n {}'.format(self.all_clusters))\r\n\r\n self.clusters_l = pd.DataFrame(self.model.fit_predict(x), columns=['Cluster'])\r\n x = pd.concat([self.clusters_l, x],axis=1)\r\n self.get_PCA(x)\r\n if self.label_col_bool: x = pd.concat([self.label_col,x],axis=1)\r\n\r\n self.data_clustered = x\r\n self.n_clusters = self.data_clustered['Cluster'].unique()\r\n\r\n def get_PCA(self, X=''):\r\n \"\"\"\r\n Function gets the PCA with 1, 2 and 3 principal components from clustered data; these are needed for plotting in visualize. \r\n See following link for more information on PCA: https://builtin.com/data-science/step-step-explanation-principal-component-analysis\r\n\r\n Args:\r\n X (pd.DataFrame): A clustered pandas DataFrame. Must include a column with 'Cluster' labels.\r\n \"\"\"\r\n if not(isinstance(X, pd.DataFrame)) and X == '':\r\n if isinstance(self.data_clustered, pd.DataFrame):\r\n X = self.data_clustered.copy()\r\n elif isinstance(self.data, pd.DataFrame):\r\n X = self.data.copy()\r\n \r\n plotX = X.copy()\r\n plotX.columns = X.columns\r\n\r\n pca_1d = PCA(n_components=1) # PCA with one principal components\r\n pca_2d = PCA(n_components=2) # PCA with two principal components\r\n pca_3d = PCA(n_components=3) # PCA with three principal components\r\n\r\n # We build our new DataFrames:\r\n PCs_1d = pd.DataFrame(pca_1d.fit_transform(plotX.drop(['Cluster'], axis=1))) # This DataFrame holds 1 principal component\r\n PCs_2d = pd.DataFrame(pca_2d.fit_transform(plotX.drop(['Cluster'], axis=1))) # This DataFrame holds 2 principal component\r\n PCs_3d = pd.DataFrame(pca_3d.fit_transform(plotX.drop(['Cluster'], axis=1))) # This DataFrame holds 3 principal component\r\n\r\n # Rename the columns of these newly created DataFrames:\r\n PCs_1d.columns = ['PC1_1d']\r\n PCs_2d.columns = ['PC1_2d', 'PC2_2d']\r\n PCs_3d.columns = ['PC1_3d', 'PC2_3d', 'PC3_3d']\r\n\r\n # WE concatenate these newly created DataFranes to plotX so that they can be used by plotX as columns.\r\n plotX = pd.concat([plotX, PCs_1d, PCs_2d, PCs_3d], axis=1, join='inner')\r\n\r\n # and we create one new column for plotX so that we can use it for 1-D visualization\r\n plotX['dummy'] = 0\r\n\r\n self.plotX = plotX\r\n \r\n def visualize(self, graph='2D', X='', show_loading_scores=False, show_mesh=False):\r\n \"\"\"\r\n The function is able to visualize clustered data 'X' in different dimensions 1D || 2D || 3D projected from prinicipal components of the data set features.\r\n\r\n Args:\r\n X (pd.DataFrame): A clustered DataFrame. \r\n graph (str, optional): A string '1D', '2D' or '3D' for the desired graph representation. Defaults to 2D. \r\n show_loading_scores (bool, optional): If user wants the loading scores desplayed on the 2D and 3D graph. Defaults to False.\r\n show_mesh (bool, optional): If the user wants a vague representation of the cluster boundary in the 3D space. Defaults to False.\r\n \"\"\"\r\n if not(isinstance(X, pd.DataFrame)) and X == '': \r\n X = self.data_clustered.copy() \r\n \r\n if not(isinstance(self.data_clustered, pd.DataFrame)):\r\n print('''Data has not been clustered, either use 'cluster()' or 'set_cluster_data()'. \\n \r\n Data will now be clustered with n_clusters = 4.''')\r\n self.cluster(X, 4)\r\n \r\n if not(isinstance(self.plotX, pd.DataFrame)):\r\n self.get_PCA(X)\r\n \r\n if not(isinstance(self.loadings, pd.DataFrame)):\r\n self.get_loading_scores(show=False)\r\n\r\n clusters = []\r\n\r\n if isinstance(self.data_scaled, pd.DataFrame):\r\n features = self.data_scaled.columns\r\n elif isinstance(self.data, pd.DataFrame):\r\n features = self.data.columns\r\n\r\n PLOT = go.Figure()\r\n\r\n for i in range(len(self.n_clusters)):\r\n clusters.append(self.plotX[self.plotX['Cluster'] == self.n_clusters[i]])\r\n\r\n if self.label_col_bool:\r\n names = self.data_clustered[self.data_clustered['Cluster']==self.n_clusters[i]]\r\n names = names[self.label_column_name]\r\n else:\r\n names = None\r\n\r\n if graph == '3D':\r\n title = \"Visualizing Clusters in Three Dimensions Using PCA\"\r\n PLOT.add_trace(go.Scatter3d(\r\n x = clusters[i][\"PC1_3d\"],\r\n y = clusters[i][\"PC2_3d\"],\r\n z = clusters[i][\"PC3_3d\"],\r\n mode = \"markers\",\r\n name = \"Cluster {}\".format(self.n_clusters[i]),\r\n marker = dict(color = self.colors[i]),\r\n text = names))\r\n if show_mesh:\r\n PLOT.add_trace(go.Mesh3d(\r\n alphahull = 7,\r\n name = \"y\",\r\n opacity = 0.1,\r\n x = clusters[i][\"PC1_3d\"],\r\n y = clusters[i][\"PC2_3d\"],\r\n z = clusters[i][\"PC3_3d\"]\r\n ))\r\n PLOT.update_layout(width=1600, height=800, autosize=True, showlegend=True,\r\n scene=dict(xaxis=dict(title='PC1',ticklen= 5, zeroline= False), \r\n yaxis=dict(title='PC2',ticklen=5,zeroline= False), \r\n zaxis=dict(title='PC3',ticklen=5,zeroline= False)))\r\n if show_loading_scores and i == len(self.n_clusters)-1:\r\n for j, feature in enumerate(features):\r\n PLOT.add_trace(go.Scatter3d(\r\n x = [0,list(self.loadings.iloc[j][['PC1']])[0]],\r\n y = [0,list(self.loadings.iloc[j][['PC2']])[0]],\r\n z = [0,list(self.loadings.iloc[j][['PC3']])[0]],\r\n name=feature,\r\n text=feature,\r\n marker = dict(\r\n size=2,\r\n color=self.colors[-1],\r\n ),\r\n line = dict(\r\n color=self.colors[-1],\r\n width=10\r\n )\r\n ))\r\n\r\n elif graph == '2D':\r\n PLOT.add_trace(go.Scatter(\r\n x = clusters[i][\"PC1_2d\"],\r\n y = clusters[i][\"PC2_2d\"],\r\n mode = \"markers\",\r\n name = \"Cluster {}\".format(self.n_clusters[i]),\r\n marker = dict(color = self.colors[i]),\r\n text = names))\r\n title = \"Visualizing Clusters in Two Dimensions Using PCA\"\r\n PLOT.update_layout(dict(title = title,\r\n xaxis= dict(title= 'PC1',ticklen= 5,zeroline= False),\r\n yaxis= dict(title= 'PC2',ticklen= 5,zeroline= False)\r\n ))\r\n if show_loading_scores and i == len(self.n_clusters)-1:\r\n for j, feature in enumerate(features):\r\n PLOT.add_shape(\r\n type='line',\r\n x0=0, y0=0,\r\n x1=self.loadings.iloc[j][0],\r\n y1=self.loadings.iloc[j][1],\r\n )\r\n PLOT.add_annotation(\r\n x=self.loadings.iloc[j][0],\r\n y=self.loadings.iloc[j][1],\r\n ax=0,ay=0,\r\n xanchor='center',\r\n yanchor='bottom',\r\n text=feature\r\n )\r\n\r\n elif graph == '1D':\r\n PLOT.add_trace(go.Scatter(\r\n x = clusters[i][\"PC1_1d\"],\r\n y = clusters[i][\"dummy\"],\r\n mode = \"markers\",\r\n name = \"Cluster {}\".format(self.n_clusters[i]),\r\n marker = dict(color = self.colors[i]),\r\n text = names))\r\n title = \"Visualizing Clusters in One Dimension Using PCA\"\r\n PLOT.update_layout(dict(title = title,\r\n xaxis= dict(title= 'PC1', ticklen= 5, zeroline= False), \r\n ))\r\n\r\n iplot(PLOT)\r\n\r\n def pairwise_plot(self, X='', save_img = False, img_name = 'pairplot.png'):\r\n \"\"\"\r\n The function creates a seaborn pairwise plot. Plotting the clustering results against each feature combination.\r\n Args:\r\n X (pd.DataFrame, optional): A clustered dataframe. Defaults to self.data_clustered.\r\n save_img (bool, optional): Boolean if the image should be saved within the current file. Defaults to False.\r\n img_name (str, optional): The desired file name for the image, should end in '.png'. Defaults to 'pairplot.png'.\r\n \"\"\"\r\n if not(isinstance(X, pd.DataFrame)) and X == '':\r\n X = self.data_clustered.copy()\r\n\r\n sns_plot = sns.pairplot(X, hue = 'Cluster')\r\n plt.show()\r\n\r\n if save_img:\r\n plt.clf()\r\n img_name = str(random.randint(0,1000))+'_'+img_name\r\n sns_plot.savefig(img_name)\r\n filename = glob.glob('./'+img_name)[0]\r\n Image(filename=filename)\r\n\r\n def set_label_column_name(self, label_column_name):\r\n self.label_column_name = label_column_name\r\n \r\n def set_data(self, x):\r\n if isinstance(x, pd.DataFrame):\r\n self.data = x\r\n else:\r\n self.data = pd.DataFrame(x)\r\n \r\n def set_data_scaled(self, x):\r\n if isinstance(x, pd.DataFrame):\r\n self.data_scaled = x\r\n else:\r\n self.data_scaled = pd.DataFrame(x)\r\n\r\n def set_data_clustered(self, x):\r\n if isinstance(x, pd.DataFrame):\r\n self.data_clustered = x\r\n else: \r\n self.data = pd.DataFrame(x)\r\n","repo_name":"PieterMey/multi_dimensional_clustering","sub_path":"multi_dimensional_clustering/multi_D_clustering.py","file_name":"multi_D_clustering.py","file_ext":"py","file_size_in_byte":23791,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"19000427035","text":"\"\"\"\nCrear un programa:\n(HECHO) - Ventana \n(HECHO) - Tamaño fijo\n(HECHO) - No redimensionable\n(HECHO) - Un menu (Inicio, Añadir, Información, Salir)\n(HECHO) - Opción de salir\n(HECHO) - Diferentes pantallas\n(HECHO) - Formulario de añadir productos\n(HECHO) - Guardar datos temporalmente\n(HECHO) - Mostrar datos listados en la pantalla home\n\"\"\"\n\nfrom tkinter import *\nfrom tkinter import ttk #r Sirve para organizar mejor visualmente la pantalla con una tabla\n\n#az Definir ventana\nventana = Tk() #r Crear el objeto\n\"\"\"ventana.geometry(\"410x350\")\"\"\" #r Tamaño de la ventana\nventana.title(\"Proyecto Tkinter - MIDEZA\") #r Titulo\nventana.minsize(410,395) #r Tamaño mínimo de la ventana, se ajusta a la cantidad de contenido de la ventana\nventana.resizable(0,0) #r Ventana no redimencionable\n\n#az Pantallas:\ndef home(): #r Aqui se definirá las diferentes cosas y \"labels\" que tendra la pantalla home\n \n #az Montar pantalla\n home_label.config(\n fg=\"white\", #r Color de la letra\n bg=\"black\", #r Fondo de la letra\n font=(\"Arial\", 30), #r Tipo de fuente de la letra y numero de fuente\n padx=160, #r Margenes con respecto al \"text\" en el eje x\n pady=20 #r Margenes con respecto al \"text\" en el eje y\n )\n home_label.grid(row=0, column=0)\n \n productos_box.grid(row=2)\n\n #az Listar productos\n \"\"\"\n for producto in productos:\n if len(producto) == 3:\n producto.append(\"AÑADIDO\") #r ARTIFICIO = Cuando entra el producto tiene 3 CAMPOS, para que ya no entre a la proxima el mismo producto se le agrega un elemento(\"AÑADIDO\")\n Label(productos_box, text=producto[0]).grid() #r producto[0] mostrará \"name_data\"\n Label(productos_box, text=producto[1]).grid() #r producto[1] mostrará \"precio_data\"\n Label(productos_box, text=producto[2]).grid() #r producto[2] mostrará \"add_descripcion_entry\"\n Label(productos_box, text=\"*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\").grid() #r linea separadora\n \"\"\"\n\n for producto in productos:\n if len(producto) == 3:\n producto.append(\"AÑADIDO\") #r ARTIFICIO = Cuando entra el producto tiene 3 CAMPOS, para que ya no entre a la proxima el mismo producto se le agrega un elemento(\"AÑADIDO\")\n productos_box.insert(\"\", 0, text=producto[0], values=(producto[1])) #r insertar una nueva fila para la tabla\n\n #az Ocultar otras pantallas (QUE NO SEA LA MISMA PANTALLA DENTRO DE LA FUNCION)\n add_label.grid_remove() #r grid_remove() sirve para quitar la pantalla de otras pantallas\n add_frame.grid_remove()\n info_label.grid_remove()\n data_label.grid_remove()\n\ndef add():\n \n #az Montar pantalla\n add_label.config(\n fg=\"white\",\n bg=\"black\",\n font=(\"Arial\", 30),\n padx=65,\n pady=20\n )\n add_label.grid(row=0, column=0, columnspan=10)\n\n #az Campos del formulario\n add_frame.grid(row=1)\n\n add_name_label.grid(row=1, column=0, padx=5, pady=5, sticky=E)\n add_name_entry.grid(row=1, column=1, padx=5, pady=5, sticky=W)\n\n add_precio_label.grid(row=2, column=0, padx=5, pady=5, sticky=E)\n add_precio_entry.grid(row=2, column=1, padx=5, pady=5, sticky=W)\n\n add_descripcion_label.grid(row=3, column=0, padx=5, pady=5, sticky=E)\n add_descripcion_entry.grid(row=3, column=1, padx=5, pady=5, sticky=W) \n add_descripcion_entry.config(\n width=30,\n height=5,\n font=(\"Consolas\", 12),\n padx=15,\n pady=15\n )\n \n add_separacion.grid(row=4)\n\n boton.grid(row=5, column=1, sticky=N)\n boton.config(\n padx=15,\n pady=5, \n bg=\"green\",\n fg=\"white\"\n )\n\n #az Ocultar otras pantallas\n home_label.grid_remove()\n productos_box.grid_remove()\n info_label.grid_remove()\n data_label.grid_remove()\n\ndef info():\n \n #az Montar pantalla\n info_label.config(\n fg=\"white\",\n bg=\"black\",\n font=(\"Arial\", 30),\n padx=105,\n pady=20\n )\n info_label.grid(row=0, column=0)\n\n data_label.grid(row=1, column=0)\n\n #az Ocultar otras pantallas\n home_label.grid_remove()\n productos_box.grid_remove()\n add_frame.grid_remove()\n add_label.grid_remove()\n\ndef add_productos():\n productos.append([\n name_data.get(),\n precio_data.get(),\n add_descripcion_entry.get(\"1.0\", \"end-1c\") #r Como es un campo de texto(add_descripcion_entry) tiene que llevar parametros especiales (\"1.0\", \"end-1c\")\n ])\n\n name_data.set(\"\") #r Borrar el contenido del campo y colocar un espacion vacio (\"\")\n precio_data.set(\"\") #r Borrar el contenido del campo y colocar un espacion vacio (\"\")\n add_descripcion_entry.delete(\"1.0\", END) #r El campo \"Text\" tiene metodos mas específicos para borrar el campo .delete(\"1.0\", END) \n\n home()\n\n#az Variables importantes\nproductos = []\nname_data = StringVar()\nprecio_data = StringVar()\n\n#az Definir campo de pantalla (HOME) \nhome_label = Label(ventana, text=\"Inicio\") #r Era una VARIABLE LOCAL, se tuvo que convertir a una VARIABLE GLOBAL(sacar afuera de la def) para que no salgue error \nproductos_box = Frame(ventana, width=250)\n\nLabel(ventana).grid(row=1) #r Separador entre la palabra \"Inicio\" y la TABLA creada\n\n#an Crear tabla para mostrar Producto y Precio\nproductos_box = ttk.Treeview(height=12, column=2) #r \".Treeview\" es para crear la tabla - (height=12) es para el numero de filas que tendra la tabla \nproductos_box.grid(row=1, column=0, columnspan=2)\nproductos_box.heading(\"#0\", text=\"Producto\", anchor=W) #r \".heading\" sirve para crear una columna \nproductos_box.heading(\"#1\", text=\"Precio\", anchor=W)\n\n#az Definir campo de pantalla (ADD)\nadd_label = Label(ventana, text=\"Añadir producto\") #r Era una VARIABLE LOCAL, se tuvo que convertir a una VARIABLE GLOBAL(sacar afuera de la def) para que no salgue error\n\n#az Campos del formulario (ADD)\nadd_frame = Frame(ventana) #r Se crea el Frame para meter hay los Entry y Label para luego ocultarlos en cada función y ya no aparesca el contenido en cada pestaña\n\nadd_name_label = Label(add_frame, text=\"Nombre: \")\nadd_name_entry = Entry(add_frame, textvariable=name_data)\n\nadd_precio_label = Label(add_frame, text=\"Precio: \")\nadd_precio_entry = Entry(add_frame, textvariable=precio_data)\n\nadd_descripcion_label = Label(add_frame, text=\"Descripción: \")\nadd_descripcion_entry = Text(add_frame)\n\nadd_separacion = Label(add_frame)\n\nboton = Button(add_frame, text=\"Guardar\", command=add_productos) #r Vincular el boton con la función add_productos\n\n#az Definir campo de pantalla (INFO)\ninfo_label = Label(ventana, text=\"Información\") #r Era una VARIABLE LOCAL, se tuvo que convertir a una VARIABLE GLOBAL(sacar afuera de la def) para que no salgue error\ndata_label = Label(ventana, text=\"Creado por © 2022, MIDEZA\") #r Era una VARIABLE LOCAL, se tuvo que convertir a una VARIABLE GLOBAL(sacar afuera de la def) para que no salgue error\n\n#az Cargar pantalla inicio\nhome() #r para que cargue automaticamente en la primera pantalla la pantalla de home\n\n#az Menú superior\nmenu_superior = Menu(ventana)\nmenu_superior.add_command(label=\"Inicio\", command=home)\nmenu_superior.add_command(label=\"Añadir\", command=add)\nmenu_superior.add_command(label=\"Información\", command=info)\nmenu_superior.add_command(label=\"Salir\", command=ventana.quit) #r ventana.quit sirve para salir de la ventana\n\n#az Cargar menú\nventana.config(menu=menu_superior)\n\n#az Cargar ventana\nventana.mainloop()","repo_name":"MIDEZA-22/Master-Python","sub_path":"21-tkinter/13-proyecto.py","file_name":"13-proyecto.py","file_ext":"py","file_size_in_byte":7468,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"33551051251","text":"dims = []\nwith open(\"../../data/2.txt\", \"r\") as f:\n for line in f:\n dims.append([int(x) for x in line.split(\"x\")])\n\ntotalArea = 0\nfor dim in dims:\n totalArea += 2 * (dim[0]*dim[1] + dim[1]*dim[2] + dim[0]*dim[2]) + sorted(dim)[0]*sorted(dim)[1]\n \nprint (totalArea)\n","repo_name":"zac112/adventOfCode","sub_path":"code2015/py3/day2/day2_1.py","file_name":"day2_1.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"74450072567","text":"import os\nimport sys\nimport subprocess\n\n\nthis_dir = os.path.abspath(os.path.dirname(__file__))\ndist_dir = os.path.join(this_dir, \"dist\")\n\n# Get what executable to run\nif sys.platform.startswith(\"win\"):\n exe = os.path.join(dist_dir, \"pyzo\", \"pyzo.exe\")\nelif sys.platform.startswith(\"darwin\"):\n exe = os.path.join(dist_dir, \"pyzo.app\", \"Contents\", \"MacOS\", \"pyzo\")\nelse:\n exe = os.path.join(dist_dir, \"pyzo\", \"pyzo\")\n\n# Prepare log file\nlogfilename = os.path.abspath(os.path.join(__file__, \"..\", \"..\", \"log.txt\"))\nwith open(logfilename, \"wt\") as f:\n f.write(\"\")\n\n# Run Pyzo\nos.environ[\"PYZO_LOG\"] = logfilename\nsubprocess.run([exe, \"--test\"], cwd=this_dir)\n","repo_name":"pyzo/pyzo","sub_path":"freeze/pyzo_test_frozen.py","file_name":"pyzo_test_frozen.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":265,"dataset":"github-code","pt":"77"}
+{"seq_id":"8329412186","text":"import pandas as pd\nimport tensorflow as tf\n\n# Data Loading\ndf = pd.read_csv(\"https://raw.githubusercontent.com/jyotiyadav99111/Node-Classification/master/data/wiki/wiki_edges.csv\", header = None)\ndf_full = pd.read_csv(\"https://raw.githubusercontent.com/jyotiyadav99111/Node-Classification/master/data/wiki/wiki_labels.csv\", header = None)\n\ndf.columns = ['A','B']\ndf_full.columns = ['node', 'label']\n\ndf = df[df['A'] != df['B']]\ndf_array = np.asarray(df)\n\n\n# Data Preprocessing\ndata = {}\nfor line in df_array:\n if line[0] in data:\n data[line[0]].append(line[1])\n else:\n data[line[0]] = [line[1]]\n \nnew_data = [''] * df_full.shape[0]\nfor key in data.keys():\n new_data[key] = data[key]\n\nX= pd.DataFrame.from_dict(data, orient='index')\ndf_full['col']= new_data\n\n# Data Seg\nY = df_full['label']\nX = df_full.drop('label', axis = 1)\n\nmlb = MultiLabelBinarizer()\nfinal_X = pd.DataFrame(mlb.fit_transform(X['col']))\nfinal_X['node'] = X['node']\n\n# Split test and triaining data set\nX_train, X_test, y_train, y_test = train_test_split(final_X, Y, test_size=0.2, random_state=42)\n\ndataset = tf.data.Dataset.from_tensor_slices((final_X, Y))\n\nfor feat, targ in dataset.take(5):\n print ('Features: {}, Target: {}'.format(feat, targ))\n \ntrain_dataset = dataset.shuffle(len(final_X)).batch(1)\n\n\nmodel = tf.keras.Sequential([\n tf.keras.layers.Dense(10, activation='relu'),\n tf.keras.layers.Dense(50, activation='relu'),\n tf.keras.layers.Dense(17)\n])\n\nmodel.compile(optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\n\nmodel.fit(train_dataset, epochs=100)\n\ntest_loss, test_acc = model.evaluate(X_test, y_test, verbose=2)\n\nprint('\\nTest accuracy:', test_acc)\n","repo_name":"jyotiyadav99111/Node-Classification","sub_path":"classification/neural_networks.py","file_name":"neural_networks.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"43220205183","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pylab\n \nCOLOR_THRESH = {'black': {'lower': (0,0,0), 'upper': (180, 255, 80)}}\n\ndef midsearch(img):\n # img = cv2.imread(\"curve85.jpg\", -1) #导入图片,参数请自行修改\n h,w,c= img.shape\n # print(h,w)\n mid=img[int(h*0.7):int(h),int(0.25*w):int(0.75*w)] #ROI选区,选择图像前面的一块区域\n hm, wm, cm = mid.shape \n\n # hsv = cv2.cvtColor(mid, cv2.COLOR_BGR2HSV)\n # mask = cv2.inRange(hsv, COLOR_THRESH['black']['lower'], COLOR_THRESH['black']['upper'])\n\n gray = cv2.cvtColor(mid, cv2.COLOR_BGR2GRAY) #设置图像为灰度图\n ret, gray = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY) #大津法二值化\n gray = cv2.medianBlur(gray, 11) #高斯滤波\n \n edges = cv2.Canny(gray, 50, 150, apertureSize=3)\n orgb = cv2.cvtColor(mid, cv2.COLOR_BGR2RGB)\n oShow = orgb.copy()\n # cv2.imshow(\"666\",edges)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 1, minLineLength=20, maxLineGap=30)#边缘检测之后霍夫变换得出直线\n fn=0\n n=0\n tan=0\n T=0.0 # 斜率\n delta=0 # 线相对于图像中心的偏移量\n # print(lines)\n if lines is not None:\n for line in lines:\n print(line)\n x1, y1, x2, y2 = line[0]\n cv2.line(orgb, (x1, y1), (x2, y2), (255, 0, 0), 2)\n n+=2\n fn+=x1\n fn+=x2\n if x1!=x2:\n tan+=(y1-y2)/(x1-x2)\n else:\n tan=99 #通过检测直线斜率检测是否遇到直角\n average=fn/n\n delta=(average-wm/2)/wm \n\n T=np.arctan(tan/len(lines))/np.pi*180\n print(f'delta: {delta}, T: {T}')\n\n plt.subplot(121)\n plt.imshow(orgb)\n plt.axis('off')\n plt.subplot(122)\n plt.imshow(edges)\n plt.axis('off')\n pylab.show()\n return delta,T\n\n\n\ndef midjudge(delta,T,delta_thres=0.13,T_thres=8):\n R_v=12 #右轮:左轮4:3\n L_v=9\n\n if delta==0 and T==0: # 检测失败\n return L_v/3,R_v/3 #缓慢直行\n\n\n\n # right and need to turn right\n if delta>=delta_thres:\n print(\"turn right\")\n return L_v+1.5,R_v\n if delta_thres<= -delta_thres:\n print(\"turn left\")\n return L_v,R_v+2\n if delta>-delta_thres and delta= -90+T_thres:\n # Turn right\n print(\"turn right\")\n return L_v+1.5,R_v\n else:\n return L_v,R_v\n if T>=0:\n if T<= 90 - T_thres:\n # Turn left\n print(\"turn left\")\n return L_v,R_v+2\n else:\n return L_v,R_v\n return L_v, R_v\n \n\n\n\nif __name__==\"__main__\":\n img= cv2.imread('./testimg/curve139.jpg')\n midsearch(img)\n\n \n# delta,T=midsearch()\n# midjudge(delta,T)\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()","repo_name":"Vicent0205/gkc_lab","sub_path":"client/linefollowing.py","file_name":"linefollowing.py","file_ext":"py","file_size_in_byte":3169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"37772376722","text":"import bs4\r\nimport requests\r\n\r\nurl = \"https://www.mysmartprice.com/mobile/oneplus-6t-msp14895\"\r\n\r\npage = requests.get(url)\r\nsoup = bs4.BeautifulSoup(page.text, \"html.parser\")\r\n\r\ncontainers = soup.findAll(\"div\", {\"class\": \"prc-tbl__row-wrpr\"})\r\ncpu = soup.findAll(\"li\", {\"class\": \"kyspc__item kyspc__item--cpu\"})\r\nram = soup.findAll(\"li\", {\"class\": \"kyspc__item kyspc__item--ram\"})\r\nstorage = soup.findAll(\"li\", {\"class\": \"kyspc__item kyspc__item--strge\"})\r\nbattery = soup.findAll(\"li\", {\"class\": \"kyspc__item kyspc__item--bttry\"})\r\ncamera = soup.findAll(\"li\", {\"class\": \"kyspc__item kyspc__item--cmra\"})\r\nscreensize = soup.findAll(\"li\", {\"class\": \"kyspc__item kyspc__item--aspct\"})\r\nsim = soup.findAll(\"li\", {\"class\": \"kyspc__item kyspc__item--sim\"})\r\nos = soup.findAll(\"li\", {\"class\": \"kyspc__item kyspc__item--os\"})\r\n\r\nproductdata = []\r\nfor item in cpu:\r\n productdata.append(item.getText())\r\nfor item in ram:\r\n productdata.append(item.getText())\r\nfor item in storage:\r\n productdata.append(item.getText())\r\nfor item in battery:\r\n productdata.append(item.getText())\r\nfor item in camera:\r\n productdata.append(item.getText())\r\nfor item in screensize:\r\n productdata.append(item.getText())\r\nfor item in sim:\r\n productdata.append(item.getText())\r\nfor item in os:\r\n productdata.append(item.getText())\r\n\r\nstores = []\r\nprices = []\r\nfor items in containers:\r\n stores.append(items[\"data-storename\"])\r\n prices.append(items.getText())\r\n\r\nj = 0\r\nfor i in stores:\r\n j += 1\r\ns = \" \"\r\nfor i in range(0, 8):\r\n if i == 0:\r\n s = productdata[i]\r\n else:\r\n s = s + \", \" + productdata[i]\r\n\r\nd = [\"\", \"\", \"\", \"\"]\r\nif j > 4:\r\n j = 4\r\nfor i in range(0, j):\r\n\r\n d[i] = stores[i] + prices[i]\r\n\r\nprint(s)\r\nfor i in range(0, j):\r\n print(d[i])\r\n","repo_name":"themagicalmammal/Reasonabot","sub_path":"Scripts/pricedyna.py","file_name":"pricedyna.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"77"}
+{"seq_id":"23948106379","text":"\"\"\"Nest and unnest\n\nhttps://github.com/tidyverse/tidyr/blob/master/R/nest.R\n\"\"\"\nfrom typing import Callable, Mapping, Union, Iterable, List\nimport re\n\nimport pandas\nfrom pandas import DataFrame, Series\nfrom pipda import register_verb\nfrom pipda.utils import CallingEnvs\n\nfrom ..core.types import Dtype, is_scalar\nfrom ..core.utils import vars_select, recycle_value, to_df, reconstruct_tibble\nfrom ..core.grouped import DataFrameGroupBy, DataFrameRowwise\nfrom ..core.contexts import Context\n\nfrom ..base import setdiff, NA\nfrom ..dplyr import distinct, bind_cols, group_vars, group_by_drop_default\n\nfrom .chop import unchop, _vec_split\nfrom .pack import unpack\n\n\n@register_verb(DataFrame, context=Context.SELECT)\ndef nest(\n _data: DataFrame,\n _names_sep: str = None,\n base0_: bool = None,\n **cols: Union[str, int],\n) -> DataFrame:\n \"\"\"Nesting creates a list-column of data frames\n\n Args:\n _data: A data frame\n **cols: Columns to nest\n _names_sep: If `None`, the default, the names will be left as is.\n Inner names will come from the former outer names\n If a string, the inner and outer names will be used together.\n The names of the new outer columns will be formed by pasting\n together the outer and the inner column names, separated by\n `_names_sep`.\n base0_: Whether `**cols` are 0-based\n if not provided, will use `datar.base.get_option('index.base.0')`\n\n Returns:\n Nested data frame.\n \"\"\"\n if not cols:\n raise ValueError(\"`**cols` must not be empty.\")\n\n all_columns = _data.columns\n colgroups = {}\n usedcols = set()\n for group, columns in cols.items():\n old_cols = all_columns[vars_select(all_columns, columns, base0=base0_)]\n usedcols = usedcols.union(old_cols)\n newcols = (\n old_cols\n if _names_sep is None\n else _strip_names(old_cols, group, _names_sep)\n )\n colgroups[group] = dict(zip(newcols, old_cols))\n\n asis = setdiff(_data.columns, usedcols, __calling_env=CallingEnvs.REGULAR)\n keys = _data[asis]\n u_keys = distinct(keys, __calling_env=CallingEnvs.REGULAR)\n nested = []\n for group, columns in colgroups.items():\n if _names_sep is None: # names as is\n # out <- map(cols, ~ vec_split(.data[.x], keys)$val)\n val = _vec_split(_data[list(columns)], keys).val\n else:\n # out <- map(\n # cols,\n # ~ vec_split(set_names(.data[.x], names(.x)), keys)$val\n # )\n to_split = _data[list(columns.values())]\n to_split.columns = list(columns)\n val = _vec_split(to_split, keys).val\n nested.append(val.reset_index(drop=True))\n\n out = pandas.concat(nested, ignore_index=True, axis=1)\n out.columns = list(colgroups)\n if u_keys.shape[1] == 0:\n return out if isinstance(out, DataFrame) else out.to_frame()\n return bind_cols(\n u_keys,\n recycle_value(out, u_keys.shape[0]),\n __calling_env=CallingEnvs.REGULAR,\n )\n\n\n@nest.register(DataFrameGroupBy, context=Context.SELECT)\ndef _(\n _data: DataFrameGroupBy,\n _names_sep: str = None,\n base0_: bool = None,\n **cols: Mapping[str, Union[str, int]],\n) -> DataFrameGroupBy:\n \"\"\"Nesting grouped dataframe\"\"\"\n if not cols:\n cols = {\n \"data\": setdiff(\n _data.columns,\n group_vars(_data, __calling_env=CallingEnvs.REGULAR),\n __calling_env=CallingEnvs.REGULAR,\n )\n }\n out = nest.dispatch(DataFrame)(\n _data, **cols, _names_sep=_names_sep, base0_=base0_\n )\n return reconstruct_tibble(_data, out, keep_rowwise=True)\n\n\n@register_verb(DataFrame, context=Context.SELECT)\ndef unnest(\n data: DataFrame,\n *cols: Union[str, int],\n keep_empty: bool = False,\n ptype: Union[Dtype, Mapping[str, Dtype]] = None,\n names_sep: str = None,\n names_repair: Union[str, Callable] = \"check_unique\",\n base0_: bool = None,\n) -> DataFrame:\n \"\"\"Flattens list-column of data frames back out into regular columns.\n\n Args:\n data: A data frame to flatten.\n *cols: Columns to unnest.\n keep_empty: By default, you get one row of output for each element\n of the list your unchopping/unnesting.\n This means that if there's a size-0 element\n (like NULL or an empty data frame), that entire row will be\n dropped from the output.\n If you want to preserve all rows, use `keep_empty` = `True` to\n replace size-0 elements with a single row of missing values.\n ptype: Providing the dtypes for the output columns.\n Could be a single dtype, which will be applied to all columns, or\n a dictionary of dtypes with keys for the columns and values the\n dtypes.\n names_sep: If `None`, the default, the names will be left as is.\n Inner names will come from the former outer names\n If a string, the inner and outer names will be used together.\n The names of the new outer columns will be formed by pasting\n together the outer and the inner column names, separated by\n `names_sep`.\n names_repair: treatment of problematic column names:\n - \"minimal\": No name repair or checks, beyond basic existence,\n - \"unique\": Make sure names are unique and not empty,\n - \"check_unique\": (default value), no name repair,\n but check they are unique,\n - \"universal\": Make the names unique and syntactic\n - a function: apply custom name repair\n base0_: Whether `cols` are 0-based\n if not provided, will use `datar.base.get_option('index.base.0')`\n\n Returns:\n Data frame with selected columns unnested.\n \"\"\"\n if not cols:\n raise ValueError(\"`*cols` is required when using unnest().\")\n\n all_columns = data.columns\n cols = vars_select(all_columns, cols, base0=base0_)\n cols = all_columns[cols]\n\n if isinstance(data, DataFrameGroupBy):\n out = data.copy(copy_grouped=True)\n else:\n out = data.copy()\n\n for col in cols:\n out[col] = _as_df(data[col])\n\n out = unchop(\n out,\n cols,\n keep_empty=keep_empty,\n ptype=ptype,\n base0_=base0_,\n __calling_env=CallingEnvs.REGULAR,\n )\n return unpack(\n out,\n cols,\n names_sep=names_sep,\n names_repair=names_repair,\n __calling_env=CallingEnvs.REGULAR,\n )\n\n\n@unnest.register(DataFrameRowwise, context=Context.SELECT)\ndef _(\n data: DataFrameRowwise,\n *cols: Union[str, int],\n keep_empty: bool = False,\n ptype: Union[Dtype, Mapping[str, Dtype]] = None,\n names_sep: str = None,\n names_repair: Union[str, Callable] = \"check_unique\",\n base0_: bool = None,\n) -> DataFrameGroupBy:\n \"\"\"Unnest rowwise dataframe\"\"\"\n out = unnest.dispatch(DataFrame)(\n data,\n *cols,\n keep_empty=keep_empty,\n ptype=ptype,\n names_sep=names_sep,\n names_repair=names_repair,\n base0_=base0_,\n )\n return DataFrameGroupBy(\n out,\n _group_vars=group_vars(data, __calling_env=CallingEnvs.REGULAR),\n _group_drop=group_by_drop_default(data),\n )\n\n\ndef _strip_names(names: Iterable[str], base: str, sep: str) -> List[str]:\n \"\"\"Strip the base names with sep\"\"\"\n out = []\n for name in names:\n if not sep:\n out.append(name[len(base) :] if name.startswith(base) else name)\n else:\n parts = re.split(re.escape(sep), name, maxsplit=1)\n out.append(parts[1] if parts[0] == base else name)\n return out\n\n\ndef _as_df(series: Series) -> List[DataFrame]:\n \"\"\"Convert series to dataframe\"\"\"\n out = []\n for val in series:\n if isinstance(val, DataFrame):\n if val.shape[1] == 0: # no columns\n out.append(NA)\n elif val.shape[0] == 0:\n out.append(\n DataFrame([[NA] * val.shape[1]], columns=val.columns)\n )\n else:\n out.append(val)\n elif is_scalar(val) and pandas.isnull(val):\n out.append(val)\n else:\n out.append(to_df(val, name=series.name))\n return out\n","repo_name":"Gedevan-Aleksizde/datar","sub_path":"datar/tidyr/nest.py","file_name":"nest.py","file_ext":"py","file_size_in_byte":8379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"77"}
+{"seq_id":"29432276629","text":"# por favor escribe aquí tu función\ndef es_primo(numero):\n if numero <= 1:\n return False\n elif numero <= 3:\n return True\n elif numero % 2 == 0 or numero % 3 == 0:\n return False\n else:\n divisor = 5\n while divisor * divisor <= numero:\n if numero % divisor == 0 or numero % (divisor + 2) == 0:\n return False\n divisor += 6\n return True\nnumero = int(input(\"Ingrese un número: \"))\nif es_primo(numero):\n print(\"El número es primo.\")\nelse:\n print(\"El número no es primo.\")","repo_name":"pabloschwarzenberg/grader","sub_path":"tema2_p1/tema2_p1_652f213f758e733bb106bb710f7e5f09.py","file_name":"tema2_p1_652f213f758e733bb106bb710f7e5f09.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"23842967675","text":"\n# -*- coding: utf-8 -*-\n\n# Test L{ellipsoids} module.\n\n__all__ = ('Tests',)\n__version__ = '23.08.27'\n\nfrom bases import TestsBase\n\nfrom pygeodesy import EcefKarney, Ellipsoid, Ellipsoid2, Ellipsoids, \\\n a_b2f_, a_b2f2, a_b2n, a_f2Tuple, \\\n b_f2a, b_f_2a, circle4, e2f, ellipsoids, f_2f, fstr, \\\n hypot_, n2e2, n2f, PI_2, R_M, sincos2d\nfrom math import fabs\n\n\nclass Tests(TestsBase):\n\n def testEllipsoids(self): # MCCABE 14\n # datum module tests\n E = Ellipsoid(1000, 1000, 0, name='TestEllipsoid')\n self.test('ellipsoid', E is Ellipsoids.TestEllipsoid, True)\n# print(Ellipsoid())\n\n e = Ellipsoids.unregister('TestEllipsoid')\n self.test(e.name, e, E)\n\n # WGS84 and GRS80/NAD83 are identical up to 3 decimals\n for E in (Ellipsoids.WGS84, Ellipsoids.GRS80): # NAD83\n self.subtitle(ellipsoids, E.name)\n self.test('R1', E.R1, R_M, fmt='%.4f')\n self.test('R2', E.R2, '6371007.2', fmt='%.1f')\n self.test('R3', E.R3, '6371000.8', fmt='%.1f')\n self.test('A', E.A, '6367449.1', fmt='%.1f')\n self.test('L', E.L, '10001965.7', fmt='%.1f')\n\n self.test('Rrectifying', E.Rrectifying, '6367449.1', fmt='%.1f') # 6367445.0\n self.test('Rgeometric', E.Rgeometric, '6367435.7', fmt='%.1f')\n self.test('Rgeocentric', E.Rgeocentric(0), '6378137.000', fmt='%.3f')\n self.test('Rgeocentric', E.Rgeocentric(45), '6367489.544', fmt='%.3f')\n self.test('Rgeocentric', E.Rgeocentric(90), '6356752.314', fmt='%.3f')\n\n self.test('Rlat', E.Rlat(0), '6378137.000', fmt='%.3f')\n self.test('Rlat', E.Rlat(45), '6367444.657', fmt='%.3f')\n self.test('Rlat', E.Rlat(90), '6356752.314', fmt='%.3f')\n\n self.test('circle4.radius', E.circle4(0).radius, '6378137.000', fmt='%.3f')\n self.test('circle4.radius', E.circle4(45).radius, '4517590.879', fmt='%.3f')\n self.test('circle4.radius', E.circle4(90).radius, '0.000', fmt='%.3f')\n\n self.test('distance2', fstr(E.distance2( 0, 0, 1, 1), prec=3), '156903.472, 45.192')\n self.test('distance2', fstr(E.distance2( 0, 0, 10, 10), prec=3), '1569034.719, 45.192')\n self.test('distance2', fstr(E.distance2(40, 40, 50, 50), prec=3), '1400742.676, 37.563')\n self.test('distance2', fstr(E.distance2(70, 70, 80, 80), prec=3), '1179164.848, 18.896')\n\n self.test('roc2', fstr(E.roc2(0), prec=3), '6335439.327, 6378137.0')\n self.test('roc2', fstr(E.roc2(45), prec=3), '6367381.816, 6388838.29')\n self.test('roc2', fstr(E.roc2(90), prec=3), '6399593.626, 6399593.626')\n\n self.test('rocBearing', E.rocBearing( 0, 0), '6335439.327', fmt='%.3f')\n self.test('rocBearing', E.rocBearing(45, 45), '6378092.008', fmt='%.3f')\n self.test('rocBearing', E.rocBearing(90, 0), '6399593.626', fmt='%.3f')\n\n self.test('rocGauss', E.rocGauss(0), '6356752.314', fmt='%.3f')\n self.test('rocGauss', E.rocGauss(45), '6378101.030', fmt='%.3f')\n self.test('rocGauss', E.rocGauss(90), '6399593.626', fmt='%.3f')\n\n self.test('rocMean', E.rocMean(0), '6356716.465', fmt='%.3f')\n self.test('rocMean', E.rocMean(45), '6378092.008', fmt='%.3f')\n self.test('rocMean', E.rocMean(90), '6399593.626', fmt='%.3f')\n\n self.test('rocMeridional', fstr(E.rocMeridional(0), prec=3), '6335439.327')\n self.test('rocMeridional', fstr(E.rocMeridional(45), prec=3), '6367381.816')\n self.test('rocMeridional', fstr(E.rocMeridional(90), prec=3), '6399593.626')\n\n self.test('rocPrimeVertical', fstr(E.rocPrimeVertical(0), prec=3), '6378137.0')\n self.test('rocPrimeVertical', fstr(E.rocPrimeVertical(45), prec=3), '6388838.29')\n self.test('rocPrimeVertical', fstr(E.rocPrimeVertical(90), prec=3), '6399593.626')\n\n self.subtitle(ellipsoids, Ellipsoid.__init__)\n self.test('a, b, None', Ellipsoid(1000, 500, None, name='_f_None').f_, 2.0) # coverage\n self.test('a, None, f_', Ellipsoid(1000, None, 2, name='_b_None').b, 500.0) # coverage\n\n E = Ellipsoids.WGS84.copy() # coverage\n self.subtitle(ellipsoids, E.name)\n self.test('WGS84.copy', E is not Ellipsoids.WGS84, True)\n self.test('WGS84.copy', E == Ellipsoids.WGS84, True)\n self.test('WGS84.find', Ellipsoids.find(E), None)\n\n self.test('WGS84.a2_b', E.a2_b, E.a2 / E.b, prec=6)\n self.test('WGS84.b2_a', E.b2_a, E.b2 / E.a, prec=6)\n self.test('WGS84.R2', E.R2, E.Rauthalic, prec=6) # obvious\n self.test('WGS84.c2', E.c2, E.R2**2, fmt='%.0f')\n self.test('WGS84.es', E.es, E.e, prec=6)\n self.test('WGS84.e22', E.e22, E.e2 / E.e21, prec=6) # .albers\n self.test('WGS84.f2', E.f2, (E.a - E.b) / E.b, prec=6)\n self.test('WGS84.m2degrees', int(E.m2degrees(E.a * PI_2)), 90)\n self.test('WGS84.degrees2m', int(E.degrees2m(90)), int(E.a * PI_2))\n self.test('WGS84.area', E.area, '5.101e+14', fmt='%.3e')\n self.test('WGS84.volume', E.volume, '1.083e+21', fmt='%.3e')\n\n self.test('WGS84.ecef', E.ecef().__class__, EcefKarney)\n self.test('WGS84.ecef', E.ecef().name, E.name)\n\n t = E.toStr(prec=10)\n self.test('WGS84', t, \"name='WGS84', a=6378137, b=6356752.3142451793, f_=298.257223563, f=0.0033528107, f2=0.0033640898, n=0.0016792204, e=0.0818191908, e2=0.00669438, e21=0.99330562, e22=0.0067394967, e32=0.0033584313, A=6367449.1458234144, L=10001965.7293127235, R1=6371008.7714150595, R2=6371007.1809184738, R3=6371000.7900091587, Rbiaxial=6367453.6345163295, Rtriaxial=6372797.5559594007\",\n known=' L=10001965.7293127216, ' in t or ' R2=6371007.1809184728, ' in t) # on Intel macOS\n e = (E.a - E.b) / (E.a + E.b) - E.n\n t = 'A=%.10f, e=%.10f, f_=%.10f, n=%.10f (%.10e)' % (E.A, E.e, E.f_, E.n, e)\n self.test('WGS84.', t, 'A=6367449.1458234144, e=0.0818191908, f_=298.2572235630, n=0.0016792204 (1.5612511284e-17)')\n\n self.subtitle(ellipsoids, 'Kruegers')\n\n def _AB(E, K, A, B):\n E.KsOrder = K\n self.test('WGS84.AlphaKs', fstr(E.AlphaKs, prec=12, fmt='e', ints=True), A)\n self.test('WGS84.BetaKs ', fstr(E.BetaKs, prec=12, fmt='e', ints=True), B)\n\n _AB(E, 8, '8.377318206245e-04, 7.608527773572e-07, 1.197645503242e-09, 2.429170680397e-12, 5.711818370428e-15, 1.47999793138e-17, 4.107624109371e-20, 1.210785038923e-22',\n '8.377321640579e-04, 5.90587015222e-08, 1.673482665344e-10, 2.164798110491e-13, 3.787930968626e-16, 7.236769021816e-19, 1.493479824778e-21, 3.259522545838e-24')\n\n _AB(E, 6, '8.377318206245e-04, 7.608527773572e-07, 1.197645503329e-09, 2.429170607201e-12, 5.711757677866e-15, 1.491117731258e-17',\n '8.377321640579e-04, 5.90587015222e-08, 1.673482665284e-10, 2.164798040063e-13, 3.787978046169e-16, 7.248748890694e-19')\n\n _AB(E, 4, '8.377318206304e-04, 7.608527714249e-07, 1.197638001561e-09, 2.443376194522e-12',\n '8.377321640601e-04, 5.905869567934e-08, 1.673488880355e-10, 2.167737763022e-13')\n\n P = Ellipsoid(E.b, E.a, name='Prolate')\n _TOL = ellipsoids._TOL\n\n self.subtitle(ellipsoids, P.name)\n for p, e in ((P.a, E.b), (P.b, E.a), (P.n, -E.n),\n (P.R1, 6363880.543), (P.R2, 6363878.941), (P.R3, 6363872.564),\n (P.Rbiaxial, E.Rbiaxial), (P.Rgeometric, E.Rgeometric),\n (P.c2, 40498955180263.188), (P.area, 508924880289508.500),\n (P.volume, 1079575530747445379072.000)):\n t = '%s [%s]' % (p.name, p.units)\n self.test(t, p, e, fmt='%.3f', known=fabs(p - e) < _TOL)\n\n for E, el, ob, pr in ((E, True, True, False),\n (P, True, False, True),\n (Ellipsoids.Sphere, False, False, False)):\n self.subtitle(ellipsoids, 'AuxiliaryLats ' + E.name)\n self.test('isEllipsoidal', E.isEllipsoidal, el)\n self.test('isOblate', E.isOblate, ob)\n self.test('isProlate', E.isProlate, pr)\n self.test('isSpherical', E.isSpherical, not el)\n for d in range(-90, 91, 30):\n x = 'lat (%d.0)' % (d,)\n for aux in (E.auxAuthalic, E.auxConformal, E.auxGeocentric,\n E.auxIsometric, E.auxParametric, E.auxRectifying):\n a = aux(d)\n t = fstr(a, prec=9)\n self.test('%s(%d)' % (aux.__name__, d), t, t)\n self.test('name', a.name, aux.__name__)\n self.test('inverse', aux(a, inverse=True).toRepr(prec=2), x)\n\n self.subtitle(ellipsoids, 'Flattenings')\n\n self.test('_TOL', _TOL, _TOL)\n for n, E in Ellipsoids.items(all=True, asorted=True): # includes f_None, b_None, Prolate\n if E.f and E.f_:\n e = E.f_ - 1 / E.f\n self.test(n + '.f_ - 1 / .f', e, e if fabs(e) < _TOL else _TOL, nl=1)\n e = E.f - 1 / E.f_\n self.test(n + '.f - 1 / .f_', e, e if fabs(e) < _TOL else _TOL) # PYCHOK attr\n\n self.subtitle(ellipsoids, Ellipsoid2.__name__)\n for n, E in Ellipsoids.items(all=True, asorted=True): # includes f_None, b_None, Prolate\n n = '_2_' + n\n E2 = Ellipsoid2(E.a, E.f, name=n)\n self.test(n, E2.toStr(name=None, prec=7), E.toStr(name=None, prec=7))\n\n self.subtitle(ellipsoids, a_f2Tuple.__name__)\n for n, E in Ellipsoids.items(all=True, asorted=True): # includes f_None, b_None, Prolate\n n = 'a_b_' + n\n a_f = a_f2Tuple(E.a, E.f, name=n)\n E2 = Ellipsoid(a_f.a, a_f.b) # PYCHOK a\n self.test(n, E2.toStr(name=None, prec=7), E.toStr(name=None, prec=7))\n n = '_a_f_ellipsoid'\n E = Ellipsoids.WGS84\n E2 = E.a_f.ellipsoid(name=n)\n self.test(n, E2.toStr(name=None), E.toStr(name=None))\n n = '_toEllipsoid2'\n E2 = E.toEllipsoid2(name=n)\n self.test(n, E2.toStr(name=None), E.toStr(name=None))\n\n self.subtitle(ellipsoids, 'Functions')\n t = 0\n for _, E in Ellipsoids.items(all=True, asorted=True): # includes f_None, b_None, Prolate\n f_ = a_b2f_(E.a, E.b)\n self.test('%s(%s)' % (a_b2f_.__name__, E.name), f_, E.f_, fmt='%.8f', known=fabs(f_ - E.f_) < _TOL, nl=1)\n f2 = a_b2f2(E.a, E.b)\n self.test('%s(%s)' % (a_b2f2.__name__, E.name), f2, E.f2, fmt='%.8f', known=fabs(f2 - E.f2) < _TOL)\n n = a_b2n(E.a, E.b)\n self.test('%s(%s)' % (a_b2n.__name__, E.name), n, E.n, fmt='%.8f', known=fabs(n - E.n) < _TOL)\n a = b_f2a(E.b, E.f)\n self.test('%s(%s)' % (b_f2a.__name__, E.name), a, E.a, fmt='%.3f', known=fabs(a - E.a) < _TOL) # millimeter\n a = b_f_2a(E.b, E.f_)\n self.test('%s(%s)' % (b_f_2a.__name__, E.name), a, E.a, fmt='%.3f', known=fabs(a - E.a) < _TOL) # millimeter\n f = f_2f(E.f_)\n self.test('%s(%s)' % (f_2f.__name__, E.name), f, E.f, fmt='%.8f', known=fabs(f - E.f) < _TOL)\n f = e2f(E.e)\n self.test('%s(%s)' % (e2f.__name__, E.name), f, E.f, fmt='%.8f', known=True) # fabs(f - fabs(E.f)) < _TOL\n e2 = n2e2(E.n)\n self.test('%s(%s)' % (n2e2.__name__, E.name), e2, E.e2, fmt='%.8f', known=fabs(e2 - E.e2) < _TOL)\n f = n2f(E.n)\n self.test('%s(%s)' % (n2f.__name__, E.name), f, E.f, fmt='%.8f', known=fabs(f - E.f) < _TOL)\n t += 1\n self.test('total', t, 49, nl=1)\n\n t = P.roc1_.__name__ + ' '\n for E, x in ((Ellipsoids.WGS84, 1.863e-9), (P, 1.863e-9),\n (Ellipsoids.SphereAuthalic, '0.0')):\n self.subtitle(ellipsoids, E.name)\n for d in range(0, 91, 5):\n s, c = sincos2d(d)\n n = E.roc1_(s)\n h = E.roc1_(s, c)\n e = fabs(n - h) # delta in meter\n self.test(t + str(d), e, x, known=e < 1.864e-9)\n n = E.roc2(d).prime_vertical\n e = fabs(n - h) # delta in meter\n self.test(t + str(d), e, x, known=e < 1.864e-9)\n\n n = circle4.__name__ + ' '\n self.subtitle(ellipsoids, circle4.__name__)\n for E in (Ellipsoids.WGS84, Ellipsoids.Sphere):\n self.subtitle(ellipsoids, E.name)\n for d in range(0, 91, 10):\n r = E.Rgeocentric(d)\n t = E.circle4(d)\n self.test(n + str(d), hypot_(t.radius, t.height), r, prec=6)\n t = circle4(E, d)\n self.test(n + str(d), hypot_(t.radius, t.height), r, prec=6)\n\n\nif __name__ == '__main__':\n\n t = Tests(__file__, __version__, ellipsoids)\n t.testEllipsoids()\n t.results()\n t.exit()\n","repo_name":"mrJean1/PyGeodesy","sub_path":"test/testEllipsoids.py","file_name":"testEllipsoids.py","file_ext":"py","file_size_in_byte":13380,"program_lang":"python","lang":"en","doc_type":"code","stars":265,"dataset":"github-code","pt":"77"}
+{"seq_id":"69818086968","text":"# -*- coding: utf-8 -*-\n\"\"\"\n trace_simexp.cmdln_args.reset\n *****************************\n\n Module to parse command line arguments used for reset\n\"\"\"\nfrom .._version import __version__\n\n__author__ = \"Damar Wicaksono\"\n\n\ndef get() -> list:\n \"\"\"Get the command line arguments of the execute phase\n\n :return: list of string, the contents of an info file\n \"\"\"\n import argparse\n\n parser = argparse.ArgumentParser(\n description=\"%(prog)s - trace-simexp Reset: Return prior to a phase\"\n )\n\n # The fullname of info_file from the pre-processing phase\n parser.add_argument(\n \"-info\", \"--info_file\",\n type=argparse.FileType(\"rt\"),\n help=\"The info file of a phase\",\n required=True\n )\n\n # Print the version\n parser.add_argument(\n \"-V\", \"--version\",\n action=\"version\",\n version=\"%(prog)s (trace-simexp version {})\" .format(__version__)\n )\n\n # Get the command line arguments\n args = parser.parse_args()\n\n # Read file argument contents\n with args.info_file as info_file:\n info_file_contents = info_file.read().splitlines()\n\n return info_file_contents\n","repo_name":"damar-wicaksono/trace-simexp","sub_path":"trace_simexp/cmdln_args/reset.py","file_name":"reset.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"29478420843","text":"import requests\nimport logging\nimport json\n\nfrom airflow.models import BaseOperator\nfrom airflow.exceptions import AirflowException\n\n\nclass SJushanov9RamOperator(BaseOperator):\n \"\"\"\n Select top 3 locations with largest number of residents\n \"\"\"\n\n template_fields = ('top_count',)\n ui_color = \"#e0ffff\"\n\n def __init__(self, top_count: int = 3, **kwargs) -> None:\n super().__init__(**kwargs)\n self.top_count = top_count\n\n def get_page_count(self, api_url: str) -> int:\n \"\"\"Load page count\n Args:\n api_url (str): Url to API\n Raises:\n AirflowException: Error in load page count\n Returns:\n int: Page count\n \"\"\"\n r = requests.get(api_url)\n if r.status_code == 200:\n logging.info(\"GET PAGE COUNT SUCCESS\")\n page_count = r.json().get('info').get('pages')\n logging.info(f'page_count = {page_count}')\n return int(page_count)\n else:\n logging.warning(\"HTTP STATUS {}\".format(r.status_code))\n raise AirflowException('Error in load page count')\n\n def execute(self, context):\n \"\"\"Operator execution\n Args:\n context (_type_): \n Raises:\n AirflowException: Error in load from Rick&Morty API\n Returns:\n list: Top locations\n \"\"\"\n result = []\n ram_char_url = 'https://rickandmortyapi.com/api/location?page={pg}'\n for page in range(self.get_page_count(ram_char_url.format(pg='1'))):\n r = requests.get(ram_char_url.format(pg=str(page + 1)))\n if r.status_code == 200:\n logging.info(f'PAGE {page + 1}')\n data = json.loads(r.text)\n for value in data['results']:\n result.append([\n value['id'],\n value['name'],\n value['type'],\n value['dimension'],\n len(value['residents']),\n ])\n else:\n logging.warning(\"HTTP STATUS {}\".format(r.status_code))\n raise AirflowException('Error in load from Rick&Morty API')\n return sorted(result, key=lambda x: x[-1], reverse=True)[:self.top_count]\n","repo_name":"skarfex/education.courses_data_engineer","sub_path":"karpov_airflow_fullrep/plugins/s_jushanov_9_plugins/s_jushanov_9_ram_operator.py","file_name":"s_jushanov_9_ram_operator.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"10993561332","text":"import config\nimport requests\nfrom bs4 import BeautifulSoup\nimport logging\n\nlogging.basicConfig(level=logging.WARNING, filename=config.BUG_FILE)\n\ndef get_info(rank, url):\n\n title = get_title(url)\n\n if title != None and title != '' and \\\n title.__contains__(\"404 Page\") == False and \\\n title.__contains__(\"403 Page\") == False and \\\n title.__contains__(\"503 -\") == False and \\\n title.__contains__(\"Attention Required\") == False:\n text = \"{},{},{}\\n\".format(rank, url, title)\n store_result(text)\n print(rank + \"- <3 - \" + url)\n\ndef get_title(url):\n try:\n hearders = {'headers':config.USER_AGENT}\n response = requests.get(url, timeout=config.TIMEOUT, headers=hearders)\n html = BeautifulSoup(response.text, \"html.parser\")\n return html.title.text\n except Exception as e:\n logging.exception(\"Oops: \" + \"Stop at: \" + url)\n print(\"Stop at - \" + url)\n\ndef get_url(string):\n output = string.split(',')\n return 'http://' + output[1]\n\ndef get_rank(string):\n output = string.split(',')\n return output[0]\n\ndef store_result(string):\n with open(config.RESULT_FILE, 'a', encoding=\"utf-8\") as f:\n f.writelines(str(string))","repo_name":"tieutantan/1m-Alexa-Website-Titles-Crawler","sub_path":"CoreModules/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"22180039206","text":"from typing import Dict, Any\n\nfrom dev_tools import modules\n\n\ndef test_versions_are_the_same():\n mods = modules.list_modules(include_parent=True)\n versions = {m.name: m.version for m in mods}\n assert len(set(versions.values())) == 1, f\"Versions should be the same, instead: \\n{versions}\"\n\n\ndef _get_version(package: str):\n version_file = f'{package}/_version.py'\n resulting_locals: Dict[str, Any] = {}\n exec(open(version_file).read(), globals(), resulting_locals)\n __version__ = resulting_locals['__version__']\n assert __version__, f\"__version__ should be defined in {version_file}\"\n return __version__\n","repo_name":"quantumlib/Cirq","sub_path":"dev_tools/version_test.py","file_name":"version_test.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","stars":3974,"dataset":"github-code","pt":"77"}
+{"seq_id":"73795786808","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\n\nfrom django.core.urlresolvers import reverse\nfrom exam import fixture\n\nfrom sentry.testutils import TestCase\n\n\nclass EnvStatusTest(TestCase):\n @fixture\n def path(self):\n return reverse('sentry-admin-status')\n\n def test_requires_auth(self):\n resp = self.client.get(self.path)\n self.assertEquals(resp.status_code, 302)\n\n def test_renders_template(self):\n self.login_as(self.user)\n\n resp = self.client.get(self.path)\n self.assertEquals(resp.status_code, 200)\n self.assertTemplateUsed(resp, 'sentry/admin/status/env.html')\n\n\nclass PackageStatusTest(TestCase):\n @fixture\n def path(self):\n return reverse('sentry-admin-packages-status')\n\n def test_requires_auth(self):\n resp = self.client.get(self.path)\n self.assertEquals(resp.status_code, 302)\n\n def test_renders_template(self):\n self.login_as(self.user)\n\n resp = self.client.get(self.path)\n self.assertEquals(resp.status_code, 200)\n self.assertTemplateUsed(resp, 'sentry/admin/status/packages.html')\n\n\nclass MailStatusTest(TestCase):\n @fixture\n def path(self):\n return reverse('sentry-admin-mail-status')\n\n def test_requires_auth(self):\n resp = self.client.get(self.path)\n self.assertEquals(resp.status_code, 302)\n\n def test_renders_template(self):\n self.login_as(self.user)\n\n resp = self.client.get(self.path)\n self.assertEquals(resp.status_code, 200)\n self.assertTemplateUsed(resp, 'sentry/admin/status/mail.html')\n\n\nclass ManageUsersTest(TestCase):\n @fixture\n def path(self):\n return reverse('sentry-admin-users')\n\n def test_does_render(self):\n self.login_as(self.user)\n resp = self.client.get(self.path)\n assert resp.status_code == 200\n self.assertTemplateUsed(resp, 'sentry/admin/users/list.html')\n assert self.user in resp.context['user_list']\n\n\nclass ManageTeamsTest(TestCase):\n @fixture\n def path(self):\n return reverse('sentry-admin-teams')\n\n def test_does_render(self):\n team = self.create_team()\n self.create_project(team=team)\n self.create_project(team=team)\n self.login_as(self.user)\n resp = self.client.get(self.path)\n assert resp.status_code == 200\n self.assertTemplateUsed(resp, 'sentry/admin/teams/list.html')\n assert team in resp.context['team_list']\n\n\nclass ManageProjectsTest(TestCase):\n @fixture\n def path(self):\n return reverse('sentry-admin-projects')\n\n def test_does_render(self):\n project = self.create_project()\n project2 = self.create_project()\n self.login_as(self.user)\n resp = self.client.get(self.path)\n assert resp.status_code == 200\n self.assertTemplateUsed(resp, 'sentry/admin/projects/list.html')\n assert project in resp.context['project_list']\n assert project2 in resp.context['project_list']\n","repo_name":"NetEaseGame/Sentry","sub_path":"tests/sentry/web/frontend/test_admin.py","file_name":"test_admin.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"77"}
+{"seq_id":"37445197513","text":"import streamlit as st\nfrom datetime import datetime\n\nimport random\nimport numpy as np\nfrom PIL import Image\nfrom scipy import stats\nfrom imageio import imsave\nimport matplotlib.pyplot as plt\nfrom skimage.util.shape import view_as_blocks\n\nimport image_slicer\nimport skimage.io\n\nimport utils.filemgmt as filemgmt\nimport utils.display as udisp\nimport utils.globalDefine as globalDefine\nimport core.ImageFormater as ImageFormater\nimport core.ImageScrambler as ImageScrambler\nimport core.ImageToTrainAndTestData as ImageToTrainAndTestData\nimport core.ModelBuilder as ModelBuilder\n\ndef run_main(title, subtitle):\n st.write(\"Solve your Puzzle\") \n frameST = st.empty()\n\n st.sidebar.title(\"Choose selection..\")\n\n if st.checkbox(\"Read Instructions before start? \"):\n udisp.render_md(\"resources/beforeyoustart.md\")\n\n puzzlesize_keys = globalDefine.PUZZLE_SIZE.keys() \n puzzlesize_id = st.sidebar.selectbox(\"Select Puzzle Size: \", list(puzzlesize_keys))\n puzzle_size = globalDefine.PUZZLE_SIZE.get(puzzlesize_id)\n\n model_list_keys = globalDefine.MODELS_LIST.keys()\n model_master_id = st.sidebar.selectbox(\"Select Network type: \", list(model_list_keys), 0)\n model_master = globalDefine.MODELS_LIST.get(model_master_id)\n\n input_img_type_keys = globalDefine.INPUT_TYPES.keys()\n input_img_type_id = st.sidebar.selectbox(\"Select Image Location: \", list(input_img_type_keys))\n input_img_type = globalDefine.INPUT_TYPES.get(input_img_type_id)\n\n problem_img_path = st.text_input('Please input puzzle image file/url here...')\n solution_file_path = st.text_input('Please input target solution file/url here...')\n\n progress_start = False\n if st.checkbox(\"Validate input images and solve puzzle\"):\n st.write(\"Validating input path....\")\n if input_img_type == \"LOCAL\":\n problem_valid = filemgmt.validateLocalPath(problem_img_path)\n solution_valid = filemgmt.validateLocalPath(solution_file_path)\n else:\n ##problem_valid = filemgmt.validateUrlPath(problem_img_path)\n ##if problem_valid:\n problem_valid, problem_img_path = filemgmt.processPuzzleUrl(problem_img_path)\n\n ##solution_valid = filemgmt.validateUrlPath(solution_file_path)\n ##if solution_valid:\n solution_valid, solution_file_path = filemgmt.processSolutionUrl(solution_file_path)\n\n st.write(problem_img_path)\n st.write(solution_file_path)\n\n if (problem_valid and solution_valid):\n st.write(\"Success: Both file contents are valid..\")\n progress_start = True\n else:\n st.write(\"Error: Both file contents are invalid..\")\n\n if progress_start:\n ##st.image(problem_img_path)\n ##st.image(solution_file_path)\n\n ## Step 1.1 - Original Input Image (Selected) >>> SOLUTION\n input_img_url = ImageFormater.setup_image_requirements(solution_file_path, puzzle_size)\n original_image_np=np.array(Image.open(input_img_url).convert('RGB'))\n st.image(original_image_np)\n\n ## Step 1.2 - Shuffled Image (Auto) >>>> PROBLEM\n ##shuffled_image_np, original_image_blocks, key_map_orig, blk_size, shuffle_img_blks = ImageScrambler.shuffle_image(problem_img_path, puzzle_size)\n problem_img_url = ImageFormater.setup_image_requirements(problem_img_path, puzzle_size)\n shuffled_image_np=np.array(Image.open(problem_img_url).convert('RGB'))\n st.image(shuffled_image_np)\n blk_size, shuffle_img_blks = ImageScrambler.zigsaw_image(shuffled_image_np, puzzle_size)\n\n st.title(\" Start Solving Puzzle......\")\n ## Using Shuffled Image\n st.write(\"Generating Training Data...\")\n training_image_files = ImageToTrainAndTestData.generate_training_data(shuffled_image_np, puzzle_size)\n st.write(\"Total \", len(training_image_files), \" training image files are generated!!\")\n ## TODO: Verify all the files on disk to make sure they do exist\n\n ## Using Original Image\n st.write(\"Generating Test Data...\")\n test_image_files = ImageToTrainAndTestData.generate_test_data(input_img_url, puzzle_size)\n st.write(\"Total \", len(test_image_files), \" test image files are generated!!\")\n ## TODO: Verify all the files on disk to make sure they do exist\n\n st.write(\"Loading Training and Test Data for Deep Learning... \")\n imgs_train = ImageToTrainAndTestData.load_images_into_memory(training_image_files, \"train_img\", 'train')\n imgs_test = ImageToTrainAndTestData.load_images_into_memory(test_image_files, \"test_img\", 'test')\n st.write(\"Total \", len(imgs_train), \" training and \", len(imgs_test), \" test images are loaded into memory for deep learning\")\n\n st.title(\"Now starting deep learning using {} Network..\".format(model_master))\n\n n_epochs = None\n\n st.write(\"Preparing model configuration...\")\n shape_img = imgs_train[0].shape\n model, shape_img_resize, input_shape_model, output_shape_model, n_epochs, outDir = ModelBuilder.config_model_builder(model_master, shape_img)\n \n st.write(\"Displaying model summary.. \")\n if model_master in [\"simpleAE\", \"convAE\"]:\n st.write(model.info)\n elif model_master in [\"vgg19\"]:\n st.write(model.summary())\n\n st.write(\"Transforming training and test data based on selected model type.. \")\n X_train, X_test = ModelBuilder.applying_transformer(shape_img_resize, imgs_train, imgs_test, input_shape_model)\n\n st.write(\"First checking the stored model and if not found then building it..\")\n all_model_files = ModelBuilder.get_saved_models_info(outDir)\n if (len(all_model_files)) == 0:\n st.write(\"Start building model (The batch counts are {} for this process.)... Please wait...\".format(n_epochs))\n model = ModelBuilder.start_batch_process(model_master, X_train, model, n_epochs)\n else:\n st.write(\"Model is already available so we are not building it to expedite the demo......\")\n\n\n st.write(\"Verifing model stored into disk..\")\n all_model_files = ModelBuilder.get_saved_models_info(outDir)\n st.write(all_model_files)\n\n st.write(\"Generate embeddings by using model.. \")\n E_train_flatten, E_test_flatten = ModelBuilder.generate_embedding_from_model(model, X_train, X_test, output_shape_model)\n \n st.write(\"Fitting KNN Model..\")\n knn_neighbors = 5\n knn_metric = \"cosine\"\n knn = ModelBuilder.fit_knn_model(E_train_flatten, knn_neighbors, knn_metric)\n st.write(knn)\n \n st.title(\"Generate final result map (image sequence)...\")\n final_list_map = ModelBuilder.generate_final_mapping_list(knn, E_test_flatten)\n st.write(final_list_map)\n\n st.write(\"Reconstructing result image based on image sequence generate in previoud step... \")\n final_image_np = ModelBuilder.generate_final_result_image(shuffled_image_np, blk_size, puzzle_size, shuffle_img_blks, final_list_map)\n st.image(final_image_np)","repo_name":"Avkash/demoapps","sub_path":"PuzzleSolver/core/CustomSolver.py","file_name":"CustomSolver.py","file_ext":"py","file_size_in_byte":7107,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"77"}
+{"seq_id":"73078605687","text":"import math\nimport statistics\nimport warnings\n\nimport numpy as np\nfrom hmmlearn.hmm import GaussianHMM\nfrom sklearn.model_selection import KFold\nfrom asl_utils import combine_sequences\n\n\nclass ModelSelector(object):\n '''\n base class for model selection (strategy design pattern)\n '''\n\n def __init__(self, all_word_sequences: dict, all_word_Xlengths: dict, this_word: str,\n n_constant=3,\n min_n_components=2, max_n_components=10,\n random_state=14, verbose=False):\n self.words = all_word_sequences\n self.hwords = all_word_Xlengths\n self.sequences = all_word_sequences[this_word]\n self.X, self.lengths = all_word_Xlengths[this_word]\n self.this_word = this_word\n self.n_constant = n_constant\n self.min_n_components = min_n_components\n self.max_n_components = max_n_components\n self.random_state = random_state\n self.verbose = verbose\n\n def select(self):\n raise NotImplementedError\n\n def base_model(self, num_states):\n # with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n # warnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n try:\n hmm_model = GaussianHMM(n_components=num_states, covariance_type=\"diag\", n_iter=1000,\n random_state=self.random_state, verbose=False).fit(self.X, self.lengths)\n if self.verbose:\n print(\"model created for {} with {} states\".format(self.this_word, num_states))\n return hmm_model\n except:\n if self.verbose:\n print(\"failure on {} with {} states\".format(self.this_word, num_states))\n return None\n\n\nclass SelectorConstant(ModelSelector):\n \"\"\" select the model with value self.n_constant\n\n \"\"\"\n\n def select(self):\n \"\"\" select based on n_constant value\n\n :return: GaussianHMM object\n \"\"\"\n\n warnings.filterwarnings(\"ignore\", message=\"divide by zero encountered in log\")\n\n best_num_components = self.n_constant\n return self.base_model(best_num_components)\n\n\nclass SelectorBIC(ModelSelector):\n \"\"\" select the model with the lowest Baysian Information Criterion(BIC) score\n\n http://www2.imm.dtu.dk/courses/02433/doc/ch6_slides.pdf\n Bayesian information criteria: BIC = -2 * logL + p * logN\n \"\"\"\n\n def select(self):\n \"\"\" select the best model for self.this_word based on\n BIC score for n between self.min_n_components and self.max_n_components\n\n :return: GaussianHMM object\n \"\"\"\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n warnings.filterwarnings(\"ignore\", message=\"divide by zero encountered in log\")\n\n # TODO implement model selection based on BIC scores\n best_n_state = self.n_constant\n best_bic = None\n\n for n_state in range(self.min_n_components, self.max_n_components+1):\n # of features = d\n # of HMM states = n\n # of free parameters p = n*(n-1) + (n-1) + 2*d*n = n^2 + 2*d*n - 1\n\n try:\n hmm_model = self.base_model(n_state) #got this from base_model function\n d = len(self.X[0])\n p = n_state**2 + (2 * d * n_state) - 1\n logL = hmm_model.score(self.X, self.lengths)\n bic = -2 * logL + p * np.log(n_state)\n if best_bic is None or best_bic > bic:\n best_bic = bic\n best_n_state = n_state\n except:\n\n bic = float('-inf')\n\n return self.base_model(best_n_state)\n\n\n\nclass SelectorDIC(ModelSelector):\n ''' select best model based on Discriminative Information Criterion\n\n Biem, Alain. \"A model selection criterion for classification: Application to hmm topology optimization.\"\n Document Analysis and Recognition, 2003. Proceedings. Seventh International Conference on. IEEE, 2003.\n http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.58.6208&rep=rep1&type=pdf\n DIC = log(P(X(i)) - 1/(M-1)SUM(log(P(X(all but i))\n '''\n\n\n\n def select(self):\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n warnings.filterwarnings(\"ignore\", message=\"divide by zero encountered in log\")\n\n best_dic = None\n best_n_state = self.n_constant\n\n # Create a list of all words except the current word\n other_words = list(self.words)\n other_words.remove(self.this_word)\n\n for n_state in range(self.min_n_components, self.max_n_components+1):\n try:\n # Fits model for this word\n hmm_model = self.base_model(n_state)\n # Gets score for this word\n logL_thisword = hmm_model.score(self.X, self.lengths)\n\n sum_other_scores = 0.0\n\n # Check the scores of all other words so we can compare\n for word in other_words:\n # X, lengths corresponding to that other word\n X, lengths = self.hwords[word]\n\n # Total up the scores for all the other words\n sum_other_scores += hmm_model.score(X, lengths)\n\n # calculate the total number of other words, need to subtract one since this_word not included in average\n m = len(self.words) - 1\n\n # Calculate DIC Score as DIC = log(P(thisword)) - average(log(P(otherwords)))\n dic = logL_thisword - (sum_other_scores / m)\n\n # Keep the highest DIC score\n if best_dic is None or best_dic < dic:\n best_dic = dic\n best_n_state = n_state\n except:\n pass\n\n return self.base_model(best_n_state)\n\n\n\nclass SelectorCV(ModelSelector):\n ''' select best model based on average log Likelihood of cross-validation folds\n\n '''\n\n def select(self):\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n warnings.filterwarnings(\"ignore\", message=\"divide by zero encountered in log\")\n\n best_kf_score = None\n best_n_state = self.n_constant\n\n for n_state in range(self.min_n_components, self.max_n_components + 1):\n try:\n scores = []\n score = 0.0\n\n if (len(self.sequences) > 1): #only use CV if there are at least 2 sequences\n # Generate K folds by choosing the min of either the num sequences (2) or 3\n folds = min(len(self.sequences),3)\n kf = KFold(shuffle=True, n_splits=folds)\n\n for cv_train_idx, cv_test_idx in kf.split(self.sequences):\n\n test_scores = []\n # Training data\n self.X, self.lengths = combine_sequences(cv_train_idx, self.sequences)\n\n # Testing data\n X_test, lengths_test = combine_sequences(cv_test_idx, self.sequences)\n\n # Fit model with training data\n model = GaussianHMM(n_components=n_state, covariance_type=\"diag\", n_iter=1000,\n random_state=self.random_state, verbose=False).fit(X_train, lengths_train)\n\n # Get the scores using test data\n test_scores.append(model.score(X_test,lengths_test))\n\n\n # Calculate the average score of all test scores which is the one we will use\n score = scores.append(np.mean(test_scores))\n\n else:\n # If the length of sequence is less than 2 then then we can't use CV\n score = scores.append(np.mean(model.score(self.X, self.lengths)))\n\n # Keep model with best score\n if best_kf_score is None or best_kf_score < score:\n best_kf_score = score\n best_n_state = n_state\n\n except:\n pass\n\n return self.base_model(best_n_state)\n","repo_name":"jamesrequa/AI-Sign-Language-Recognizer","sub_path":"my_model_selectors.py","file_name":"my_model_selectors.py","file_ext":"py","file_size_in_byte":8152,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"77"}
+{"seq_id":"29656423523","text":"# 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 asyncio.futures import CancelledError\nfrom datetime import datetime\nfrom random import random\nimport asyncio\nimport atexit\nimport logging\n\nfrom bndl.net.messages import Ping\n\n\nlogger = logging.getLogger(__name__)\n\n\n# The time in seconds between checking connections\nWATCHDOG_INTERVAL = 2\n\n# allow at most 10 connection attempts\n# after that, drop the peer connection from the\n# peer table\nMAX_CONNECTION_ATTEMPT = 10\n\n# The maximum time in seconds with no communication\n# after which a ping is sent\nDT_PING_AFTER = 60\n\n# The maximum time in seconds with no communication\n# after which the connection is considered lost\nDT_MAX_INACTIVE = DT_PING_AFTER * 2\n\n\nclass PeerStats(object):\n def __init__(self, peer):\n self.peer = peer\n self.connection_attempts = 0\n self.last_update = datetime.now()\n self.last_reconnect = None\n self.error_since = None\n\n self.bytes_sent = 0\n self.bytes_sent_rate = 0\n self.bytes_received = 0\n self.bytes_received_rate = 0\n\n\n def update(self):\n now = datetime.now()\n interval = (now - self.last_update).total_seconds()\n self.last_update = now\n\n if not self.peer.is_connected and self.peer.connected_on is not None:\n if not self.error_since:\n logger.info('%r disconnected', self.peer)\n self.error_since = self.error_since or now\n self.bytes_sent_rate = 0\n self.bytes_received_rate = 0\n return\n\n # calculate tx and rx rates\n if self.peer.is_connected:\n self.bytes_sent_rate = (self.peer.conn.bytes_sent - self.bytes_sent) / interval\n self.bytes_sent = self.peer.conn.bytes_sent\n self.bytes_received_rate = (self.peer.conn.bytes_received - self.bytes_received) / interval\n self.bytes_received = self.peer.conn.bytes_received\n\n if self.peer.last_rx and (now - self.peer.last_rx).total_seconds() > DT_MAX_INACTIVE:\n if not self.error_since:\n logger.info('%r is inactive for more than %s seconds (%s)', self.peer,\n DT_MAX_INACTIVE, now - self.peer.last_rx)\n self.error_since = self.error_since or now\n else:\n if self.error_since:\n logger.info('%s recovered', self.peer)\n # clear error stats\n self.connection_attempts = 0\n self.error_since = None\n\n\n def __str__(self):\n if self.error_since:\n fmt = '{peer.name} error since {error_since}'\n else:\n fmt = '{peer.name} communicating at {bytes_received_rate:.2f} kbps rx, {bytes_sent_rate} kbps tx'\n\n return fmt.format_map(self.__dict__)\n\n\n\n\nclass Watchdog(object):\n def __init__(self, node):\n self.node = node\n self._peer_stats = {}\n self.monitor_task = None\n\n atexit.register(self.stop)\n\n\n def start(self):\n self.monitor_task = self.node.loop.create_task(self._monitor())\n\n\n def stop(self):\n self.monitor_task = None\n\n\n def peer_stats(self, peer):\n stats = self._peer_stats.get(peer)\n if not stats:\n self._peer_stats[peer] = stats = PeerStats(peer)\n return stats\n\n\n @asyncio.coroutine\n def _monitor(self):\n try:\n while self.monitor_task and self.node.running:\n yield from self._check()\n yield from asyncio.sleep(WATCHDOG_INTERVAL, loop=self.node.loop) # @UndefinedVariable\n except CancelledError:\n pass\n\n\n @asyncio.coroutine\n def _ping(self, peer):\n try:\n yield from peer.send(Ping())\n except Exception:\n self.peer_stats(peer).update()\n logger.warning('Unable to send ping to peer %r', peer, exc_info=True)\n\n\n @asyncio.coroutine\n def _check(self):\n for name in list(self.node.peers.keys()):\n try:\n # check a connection with a peer\n yield from self._check_peer(name)\n except CancelledError:\n raise\n except Exception:\n logger.exception('unable to check peer %s of %s', self.node.name, name)\n\n # if no nodes are connected, attempt to connect with the seeds\n if not any(peer.is_connected for peer in self.node.peers.values()):\n yield from self.node._connect_seeds()\n\n\n @asyncio.coroutine\n def _check_peer(self, name):\n try:\n peer = self.node.peers[name]\n except KeyError:\n return\n\n if peer.name != name:\n logger.info('Peer %s of node %s registered under %s, updating registration',\n peer.name, self.node.name, name)\n peer = self.node.peers.pop(name)\n self.node.peers[name] = peer\n\n stats = self.peer_stats(peer)\n stats.update()\n\n if stats.connection_attempts > MAX_CONNECTION_ATTEMPT:\n popped = self.node.peers.pop(name)\n if popped != peer:\n self.node.peers[name] = popped\n yield from peer.disconnect('disconnected by watchdog after %s failed connection attempts',\n stats.connection_attempts)\n elif stats.error_since:\n # max reconnect interval is:\n # - twice the watch_dog interval (maybe something was missed)\n # - exponentially to the connection attempts (exponentially back off)\n # - with a random factor between 1 +/- .25\n now = datetime.now()\n connect_wait = WATCHDOG_INTERVAL * 2 ** stats.connection_attempts * (.75 + random() / 2)\n if (now - stats.error_since).total_seconds() > WATCHDOG_INTERVAL * 2 and \\\n (not stats.last_reconnect or (now - stats.last_reconnect).total_seconds() > connect_wait):\n stats.connection_attempts += 1\n stats.last_reconnect = now\n yield from peer.connect()\n elif peer.is_connected and \\\n peer.last_rx and \\\n (datetime.now() - peer.last_rx).total_seconds() > DT_PING_AFTER:\n yield from self._ping(peer)\n\n\n def rxtx_stats(self):\n stats = dict(\n bytes_sent=0,\n bytes_sent_rate=0,\n bytes_received=0,\n bytes_received_rate=0\n )\n for peer_stats in self._peer_stats.values():\n for k in stats.keys():\n stats[k] += getattr(peer_stats, k, 0)\n return stats\n","repo_name":"bndl/bndl","sub_path":"bndl/net/watchdog.py","file_name":"watchdog.py","file_ext":"py","file_size_in_byte":7044,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"29387350939","text":"class Taxon:\n def __init__(self, categoria, nombre):\n self.categoria = categoria\n self.nombre = nombre\n self.subcategorias = []\n\n# Ejemplo de uso\naves = Taxon(\"Clase\", \"Aves\")\nfalconiformes = Taxon(\"Orden\", \"Falconiformes\")\naves.subcategorias.append(falconiformes)\n\nprint(aves.subcategorias[0].nombre) # Imprime \"Falconiformes\"\n\n ","repo_name":"pabloschwarzenberg/grader","sub_path":"hito3_ej2/hito3_ej2_6f3a15500d032e4f21047a41229cdcc9.py","file_name":"hito3_ej2_6f3a15500d032e4f21047a41229cdcc9.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"70922845048","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport pickle\nimport gzip\n\nnp.set_printoptions(threshold=np.inf)\n\nf = open('data/ACML_Movies.csv', 'r')\nmovie_strngs = f.read()\nmovie_strngs = movie_strngs.split('\\n')\nmovie_strngs = movie_strngs[1:]\nmovie_strngs = movie_strngs[:-1]\nratings = []\nfor strng in movie_strngs:\n split_strng = strng.split(',')\n rate = np.array([int(d) for d in split_strng])\n ratings.append(rate)\n\nratings = np.array(ratings)\nratings = ratings[:, 1:]\n\ntest_ratings = np.copy(ratings[-11:])\nratings = ratings[:-11]\n\nweights = np.random.uniform(-0.3, 0.3, (20,35*5))\n\nlearn_rate = 0.01\nepochs = 400\n\ndef sigmoid(x):\n\tout = np.zeros(x.shape)\n\tfor i in range(out.shape[0]):\n\t\tif x[i] >= 0:\n\t\t\tout[i] = 1/(1+np.exp(-x[i]))\n\t\telse:\n\t\t\tout[i] = np.exp(x[i])/(1+np.exp(x[i]))\n\treturn out\n\t#return np.where(x >= 0, 1/(1+np.exp(-x)), np.exp(x)/(1+np.exp(x)))\n\ndef softmax(x):\n\treturn np.exp(x-np.max(x))/np.sum(np.exp(x-np.max(x)), axis=0)\t\t#NOTE If we using batches we will need axis=1\n\n\nfor k in range(epochs):\n print(\"Starting epoch: \", k)\n for v in ratings:\n rate_matrix = np.zeros((v.shape[0], 5))\n for i in range(v.shape[0]):\n if v[i] != -1:\n rate_matrix[i, v[i]-1] = 1\n v_in = rate_matrix.reshape(35*5,)\n h = np.random.binomial(1,sigmoid(np.dot(weights, v_in)))\n pos_grad = np.dot(h.reshape(20,1), v_in.reshape(1,175))\n v_prime = np.zeros((v.shape[0], 5))\n vis_active = np.dot(h, weights)\n vis_active_matrix = vis_active.reshape(v.shape[0], 5)\n for movie_index in range(len(vis_active_matrix)):\n v_prime[movie_index] = np.random.binomial(1, softmax(vis_active_matrix[movie_index]))\n #v_prime = np.random.binomial(1, sigmoid(np.dot(h, weights)))\n for i in range(len(v)):\n if v[i] == -1:\n v_prime[i] = np.zeros(5)\n h_prime = np.random.binomial(1, sigmoid(np.dot(weights, v_prime.reshape(35*5,))))\n neg_grad = np.dot(h_prime.reshape(20,1), v_prime.reshape(1, 175))\n delta_w = pos_grad - neg_grad\n weights = weights + (learn_rate * delta_w)\n\nnp.savetxt(\"RBM_movies_weights.txt\", weights)\n\nfor i in range(20):\n\th_set = np.zeros(20)\n\th_set[i] = 1\n\tvis_active = np.dot(h_set, weights)\n\tvis_active_matrix = vis_active.reshape(v.shape[0], 5)\n\tplt.figure()\n\tplt.imshow(vis_active_matrix)\n\tplt.axis('off')\n\tplt.savefig(\"RBM_movie_pc_out_ims/component_\" + str(i+1) + \".png\")\n\tnp.savetxt(\"RBM_movie_pc_out_ims/component_\" + str(i+1) + \".txt\", vis_active_matrix)\n","repo_name":"JarvisDevon/Restricted_Boltzmann_Machine","sub_path":"RBM_movie.py","file_name":"RBM_movie.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"43359014566","text":"from datetime import date\r\n\r\n\r\ndef diasEntreFechas():\r\n f_day = int(input(\"Dia inicial: \"))\r\n f_month = int(input(\"Mes inicial: \"))\r\n f_year = int(input(\"Año inicial: \\n\"))\r\n first_date = date(f_year, f_month, f_day)\r\n\r\n l_day = int(input(\"Dia final: \"))\r\n l_month = int(input(\"Mes final: \"))\r\n l_year = int(input(\"Año final: \"))\r\n last_date = date(l_year, l_month, l_day)\r\n delta = last_date - first_date\r\n\r\n print(f\"\\nHay {delta.days} dias entre las 2 fechas\\n\")\r\n\r\n\r\n\r\ndef diasPara():\r\n\r\n today = date(date.today().year, \r\n date.today().month, \r\n date.today().day)\r\n\r\n day = int(input(\"Dia final: \"))\r\n month = int(input(\"Mes final: \"))\r\n year = int(input(\"Año final: \"))\r\n\r\n desired_date = date(year, month, day)\r\n \r\n delta = desired_date - today\r\n\r\n print(f\"\\nFaltan {delta.days} dias para la fecha!\\n\")\r\n\r\nwhile True:\r\n print(\"Bienvenido\")\r\n print(\"¿Que opción deseas?\")\r\n print(\"Dias entre fechas ---- 1\")\r\n print(\"Dias para ------------ 2\")\r\n print(\"Salir ---------------- 3\")\r\n\r\n op = int(input(\"Opcion: \"))\r\n if op == 1:\r\n diasEntreFechas()\r\n elif op == 2:\r\n diasPara()\r\n else:\r\n exit()\r\n\r\n","repo_name":"KaysenGamiz/DiasEntreFechas","sub_path":"diasEntreFechas.py","file_name":"diasEntreFechas.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"7889774727","text":"import symbolicAnalysis\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport lowLevelFeatures as ll\nfrom sklearn import preprocessing\nimport plots\nimport json\nimport recordingAttributes\n\ndef showTop2GramsForFileList(annotationFileList, top=100):\n symStatistics, topTwoGrams, topNGrams, matrix =\\\n symbolicAnalysis.estimateStatistics(annotationFileList,\n top=top, maxNGram=20)\n twoGramsFrame = pd.DataFrame({'Bigrams': [x[0] for x in topTwoGrams], 'Qty': [x[1] for x in topTwoGrams]})\n height = max(28.0 * int(len(topTwoGrams) / 100), 3)\n fig = plt.figure(figsize=(18, height), dpi=90, facecolor='w', edgecolor='k')\n sns.set_color_codes(\"pastel\")\n ax = sns.barplot(\"Qty\", y=\"Bigrams\", data=twoGramsFrame, color=\"b\")\n ax.axes.set_xlabel(\"Quantity\")\n ax.xaxis.set_label_position('top')\n ax.xaxis.tick_top()\n plt.tight_layout()\n plt.show()\n\ndef showTopNGramsForFileList(annotationFileList, top=100):\n symStatistics, topTwoGrams, topNGrams, matrix =\\\n symbolicAnalysis.estimateStatistics(annotationFileList,\n top=top, maxNGram=20)\n nGramsFrame = pd.DataFrame({'N-grams': [x[0] for x in topNGrams], 'Qty': [x[1] for x in topNGrams]})\n fig = plt.figure(figsize=(20, int(25.0 * len(topNGrams) / 100)), dpi=90, facecolor='w', edgecolor='k')\n sns.set_color_codes(\"pastel\")\n ax = sns.barplot(\"Qty\", y=\"N-grams\", data=nGramsFrame, color=\"b\")\n ax.axes.set_xlabel(\"Quantity\")\n ax.xaxis.set_label_position('top')\n ax.xaxis.tick_top()\n plt.tight_layout()\n plt.show()\n\ndef show5HexagramsForFileList(annotationFileList):\n cep = ll.ChromaEvaluationParameters(stepSize=2048, smoothingTime=1.2)\n chromaEvaluator = ll.AnnotatedChromaEvaluator(cep)\n chromas = chromaEvaluator.loadChromasForAnnotationFileList(annotationFileList)\n fig, ax = plt.subplots(nrows=1,ncols=5,figsize=(12,2.6), dpi= 90, facecolor='w', edgecolor='k')\n for axx in ax:\n axx.axes.get_xaxis().set_visible(False)\n axx.axes.get_yaxis().set_visible(False)\n ax[0].set_title(\"Maj\")\n if (any(chromas.kinds == 'maj') > 0):\n maj = preprocessing.normalize(chromas.chromas[chromas.kinds == 'maj'], norm='l1')\n #sns.violinplot(data=pd.DataFrame(maj, columns=degrees), inner=\"point\", ax=ax[0][0])\n plots.plotMajHexagram(ax[0], maj)\n ax[1].set_title(\"Min\")\n if (any(chromas.kinds == 'min') > 0):\n min = preprocessing.normalize(chromas.chromas[chromas.kinds == 'min'], norm='l1')\n #sns.violinplot(data=pd.DataFrame(min, columns=degrees), inner=\"point\", ax=ax[0][1])\n plots.plotMinHexagram(ax[1], min)\n ax[2].set_title(\"Dom\")\n if (any(chromas.kinds == 'dom') > 0):\n dom = preprocessing.normalize(chromas.chromas[chromas.kinds == 'dom'], norm='l1')\n #sns.violinplot(data=pd.DataFrame(dom, columns=degrees), inner=\"point\", ax=ax[0][2])\n plots.plotDomHexagram(ax[2], dom)\n ax[3].set_title(\"Hdim7\")\n if (any(chromas.kinds == 'hdim7') > 0):\n hdim7 = preprocessing.normalize(chromas.chromas[chromas.kinds == 'hdim7'], norm='l1')\n #sns.violinplot(data=pd.DataFrame(hdim7, columns=degrees), inner=\"point\", ax=ax[0][3])\n plots.plotHdim7Hexagram(ax[3], hdim7)\n ax[4].set_title(\"Dim\")\n if (any(chromas.kinds == 'dim') > 0):\n dim = preprocessing.normalize(chromas.chromas[chromas.kinds == 'dim'], norm='l1')\n #sns.violinplot(data=pd.DataFrame(dim, columns=degrees), inner=\"point\", ax=ax[0][4])\n plots.plotDimHexagram(ax[4], dim)\n plt.tight_layout()\n plt.show()\n\ndef showYearHistogramForFileList(annotationFileList):\n years = []\n for file in annotationFileList:\n with open(file, 'r') as df:\n annotation = json.load(df)\n print(file, annotation['mbid'])\n recording = recordingAttributes.loadRecordingAttributesFromMusicBrainz(\n annotation['mbid'])\n if (recording.started != None):\n years.append(int(recording.started[:4]))\n fig = plt.figure(figsize=(6, 4), dpi=90, facecolor='w', edgecolor='k')\n plt.hist(years)\n plt.xlabel('Year')\n plt.ylabel('Number of recordings')\n plt.show()\n","repo_name":"seffka/jazz-harmony-analysis","sub_path":"utils/siteUtils.py","file_name":"siteUtils.py","file_ext":"py","file_size_in_byte":4266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"5385188357","text":"\"\"\"\r\nProblem: The Unix tool wc counts the numbers of characters, words and lines in a file.\r\nWrite your own version of wc that prompts for the name of the file to read, then prints the counts.\r\nAssume a word may contain letters, digits, symbols and their mixture, but not space. Hyphenated words,\r\ne.g. large-scale, shall be considered as one word.\r\nOutput:\r\nFile name: python.txt\r\nCharacters: 1227\r\nWords: 176\r\nLines: 10\r\n\"\"\"\r\n\r\nf = open(input(\"File name:\"), \"r\")\r\nnum_chars = num_words = num_lines = 0\r\nfor line in f:\r\n num_lines += 1\r\n num_chars += len(line)\r\n line = line.strip() #remove whitespaces\r\n words = line.split() #split into list using whitespace\r\n num_words += len(words)\r\nprint(\"Characters:\", num_chars)\r\nprint(\"Words:\", num_words)\r\nprint(\"Lines:\", num_lines)\r\nf.close()","repo_name":"vinaya07/Python","sub_path":"File_Pgms/word_Lines_Char_Count.py","file_name":"word_Lines_Char_Count.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"23570494935","text":"# Based on source from http://stackoverflow.com/questions/38263313/radial-grids-must-be-strictly-positive-error-on-radar-chart\nimport numpy as np\n\nAX_MIN_VALUE = 0.1\nAX_MAX_VALUE = 0.8\n\n\ndef _invert(x, limits):\n \"\"\"inverts a value x on a scale from\n limits[0] to limits[1]\"\"\"\n return limits[1] - (x - limits[0])\n\ndef _scale_data(data, ranges):\n result = []\n for d, (y1, y2) in zip(data, ranges):\n assert (y1 <= d <= y2) or (y2 <= d <= y1)\n result.append((d-y1)/(y2-y1)*(AX_MAX_VALUE-AX_MIN_VALUE) + AX_MIN_VALUE) # This is the formula to convert between 2 scales\n return result\n\nclass ComplexRadar():\n def __init__(self, fig, variables, ranges,\n n_ordinate_levels=6, precision=2, textsize=\"smaller\", numberssize=\"smaller\", textposrate=1.11, textposrotation=60):\n angles = np.arange(0, 360, 360./len(variables))\n\n axes = [fig.add_axes([AX_MIN_VALUE,AX_MIN_VALUE,AX_MAX_VALUE,AX_MAX_VALUE],polar=True,\n label = \"axes{}\".format(i))\n for i in range(len(variables))]\n l, text = axes[0].set_thetagrids(angles,\n labels=variables,\n frac=textposrate, size=textsize)\n [txt.set_rotation(angle-textposrotation) for txt, angle\n in zip(text, angles)]\n for ax in axes[1:]:\n ax.patch.set_visible(False)\n ax.grid(\"off\")\n ax.xaxis.set_visible(False)\n for i, ax in enumerate(axes):\n grid = np.linspace(*ranges[i],\n num=n_ordinate_levels)\n adjusted_range = [(AX_MIN_VALUE,AX_MAX_VALUE) for i in range(len(ranges))] # radial grids must be strictly positive in matplotlib\n adjusted_grid = np.linspace(*adjusted_range[i],\n num=n_ordinate_levels)\n gridlabel = [\"{}\".format(round(x,precision))\n for x in grid]\n if ranges[i][0] > ranges[i][1]:\n grid = grid[::-1] # hack to invert grid\n # gridlabels aren't reversed\n gridlabel[0] = \"\" # clean up origin\n ax.set_rgrids(adjusted_grid, labels=gridlabel,\n angle=angles[i], size=numberssize)\n #ax.spines[\"polar\"].set_visible(False)\n ax.set_ylim(*adjusted_range[i])\n # variables for plotting\n self.angle = np.deg2rad(np.r_[angles, angles[0]])\n self.ranges = ranges\n self.ax = axes[0]\n def plot(self, data, *args, **kw):\n sdata = _scale_data(data, self.ranges)\n self.ax.plot(self.angle, np.r_[sdata, sdata[0]], *args, **kw)\n def fill(self, data, *args, **kw):\n sdata = _scale_data(data, self.ranges)\n self.ax.fill(self.angle, np.r_[sdata, sdata[0]], *args, **kw)","repo_name":"christiaangoossens/srccheck","sub_path":"utilities/complex_radar.py","file_name":"complex_radar.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"77"}
+{"seq_id":"31179969623","text":"import logging\nfrom datetime import datetime\n\nfrom dremio_toolkit.utils import Utils\n\n\nclass Logger:\n # Configuration\n _LEVELS = {'ERROR': 40, 'WARN': 30, 'WARNING': 30, 'INFO': 20, 'DEBUG': 10}\n\n def __init__(self, context, level=logging.ERROR, verbose=False, log_file: str = None):\n # Status print\n self._process_prefix_text = ''\n self._process_last_complete = 0\n self._process_total = 0\n self._process_start_time = None\n # Message collections\n self._errors = []\n # Other initialization\n self._context = context\n self._uuid = context.get_uuid()\n if type(level) == str:\n level = Logger._LEVELS[level]\n self._root_logger = logging.getLogger('root')\n self._root_logger.setLevel(level)\n self._error_count = 0\n self._verbose = verbose\n self._process_start_time = datetime.now()\n self._last_error_message = ''\n print('Running command ' + self._context.get_command() + '. Run ID: ' + self._uuid)\n if log_file:\n print('Logger will write to file: ' + log_file)\n logging.basicConfig(handlers=[logging.FileHandler(filename=log_file, encoding='utf-8', mode='a+')])\n\n def set_uuid(self, uuid: str):\n self._uuid = uuid\n\n def fatal(self, message: str, catalog: str = None) -> None:\n self._root_logger.critical(self._enrich_message(message, catalog))\n raise RuntimeError(\"Critical message: \" + str(message))\n\n def get_last_error_message(self):\n return self._last_error_message\n\n def get_all_errors(self):\n return self._errors\n\n def error(self, message: str, catalog: str = None, object_list: list = None) -> None:\n self._last_error_message = message\n self._error_count += 1\n if object_list:\n enriched_message = self._enrich_message(message)\n if self._verbose:\n self.error(enriched_message + ' ' + str(object_list))\n else:\n self.error(enriched_message + ', total: ' + str(len(object_list)) + ' items.')\n else:\n enriched_message = self._enrich_message(message, catalog)\n self._root_logger.error(self._enrich_message(message, catalog))\n self._errors.append({'message': message, 'enriched_message': enriched_message, 'catalog': catalog,\n 'object_list': str(object_list)})\n\n def warn(self, message: str, catalog: str = None) -> None:\n self._root_logger.warning(self._enrich_message(message, catalog))\n\n def info(self, message: str, catalog: str = None) -> None:\n self._root_logger.info(self._enrich_message(message, catalog))\n\n def debug(self, message: str, catalog: str = None) -> None:\n self._root_logger.debug(self._enrich_message(message, catalog))\n\n def new_process_status(self, total: int, prefix_text='') -> None:\n self._process_prefix_text = prefix_text\n self._process_total = total\n self._process_last_complete = 0\n self._process_start_time = datetime.now()\n print()\n print(self._process_prefix_text, end='\\r')\n\n def print_process_status(self, complete: int = None, increment: int = None) -> None:\n # Validate parameters\n if complete is None and increment is None:\n self.warn('Error reporting process status')\n return\n elif complete is not None:\n self._process_last_complete = complete\n else: # increment is not None\n complete = self._process_last_complete + increment\n self._process_last_complete = complete\n if complete != 0:\n pct_complete = complete / self._process_total * 100\n ttn = (datetime.now() - self._process_start_time) // 1000000 * 1000000 # round to seconds\n etl = (ttn * (self._process_total / complete - 1)) // 1000000 * 1000000 # round to seconds\n if complete < self._process_total:\n print(self._process_prefix_text +\n 'Processed: ' + str(round(pct_complete)) + '% in ' + str(ttn) +\n ' with ' + str(self._error_count) + ' errors.' +\n ' Estimated time left: ' + str(etl) + '.', end='\\r')\n else:\n print(self._process_prefix_text +\n 'Processed: ' + str(round(pct_complete)) + '% in ' + str(ttn) +\n ' with ' + str(self._error_count) + ' errors.', end='\\r')\n\n def finish_process_status_reporting(self) -> None:\n print()\n if self._error_count > 0:\n print(\"Process finished with \" + str(self._error_count) +\n \" errors. Please review the log file for more information.\")\n\n def get_error_count(self) -> int:\n return self._error_count\n\n # Enrich message with either catalog ID or entire catalog JSON depending on verbose setting\n def _enrich_message(self, message: str, catalog: dict = None) -> str:\n message = 'Run:' + self._uuid + ': ' + message\n if catalog is None or type(catalog) != dict:\n return message\n if self._verbose:\n return message + \" \" + str(catalog)\n if 'path' in catalog:\n if 'entityType' in catalog:\n return message + \" \" + str(catalog['entityType']) + \":\" + Utils.get_str_path(catalog['path'])\n else:\n return message + \" \" + Utils.get_str_path(catalog['path'])\n if 'entityType' in catalog:\n if 'name' in catalog:\n return message + \" \" + str(catalog['entityType']) + \":\" + str(catalog['name'])\n else:\n return message + \" \" + str(catalog['entityType']) + \":\" + str(catalog['id'])\n return message + \" \" + str(catalog)\n","repo_name":"ucesys/dremio-toolkit","sub_path":"dremio_toolkit/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":5794,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"27339618023","text":"import json, time\nfrom re import L\n\n# stringOfJsonData = '{\"name\": \"Zophie\", \"isCat\": true, \"miceCaught\": 0, \"felineIQ\": null}'\n# pythonValue = { 'isCat': True, 'miceCaught': 0, 'name': 'Zophie', 'felineIQ': None }\n\n# airportFile = open('IATA_Airports.json')\nwith open('IATA_Airports.json') as airportFile:\n airportData = airportFile.read() # don't use readlines() with JSON\n print(f\"File opened. Contains {len(airportData)} characters.\")\n convertedJson = json.loads(airportData) #loads is short for 'load string'\n\ncountries = {}\nfor item in convertedJson:\n if item['country_code'] in countries.keys():\n countries[item['country_code']] += 1\n else:\n countries.update({item['country_code']:1})\n\ncountriesSorted = sorted(countries.items(), key=lambda i: i[1], reverse=True)\nfor country in countriesSorted:\n print('Country code:',country[0],'Num airports:',country[1])\n\nwhile True:\n countryChoice = input('Which country would you like to view >> ')\n if countryChoice in countries.keys():\n break\n else:\n print(\"Invalid country code. Try again\")\n\nairports = []\nfor item in convertedJson:\n if item['country_code'] == countryChoice:\n airports.append({ \n 'name' : item['name_translations']['en'],\n 'code' : item['code'],\n 'lat': item['coordinates']['lat'],\n 'lon': item['coordinates']['lon']\n })\n # print(item['name_translations']['en'])\n\nprint(\"Total airports with matching country_code >> \", len(airports))\nprint(\"Information captured. Preparing to sort.\")\nchoice = input(\"Enter sort [code] [name] [lat] [lon] or '' >> \")\nif choice == '':\n choice = 'code'\nairportsSorted = sorted(airports, key=lambda i: i[choice]) \n# sorted is a built in function that allows for a key\nprint(\"Information sorted. Preparing to print.\")\n\nfor item in airportsSorted:\n print(item['code'], item['name'], item['lat'], item['lon'])\n time.sleep(0.10)\n\nprint(\"Exporting filtered results to JSON\")\n\nwith open(countryChoice+'airportData.json', 'w') as exportFile:\n exportJson = json.dumps(airportsSorted)\n exportFile.write(exportJson)\n\n\n","repo_name":"edwardough/vce-software-development","sub_path":"JSONfiles/jsonFileHandling.py","file_name":"jsonFileHandling.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"23828430851","text":"#!/usr/bin/env python3\nimport requests\nimport random\nfrom bs4 import BeautifulSoup as bs\nimport random\n\nproxies = []\nall_proxies = {}\n\ndef get_free_proxies():\n url = \"https://free-proxy-list.net/\"\n # get the HTTP response and construct soup object\n soup = bs(requests.get(url).content, \"html.parser\")\n for row in soup.find(\"table\", attrs={\"id\": \"proxylisttable\"}).find_all(\"tr\")[1:]:\n tds = row.find_all(\"td\")\n try:\n ip = tds[0].text.strip()\n port = tds[1].text.strip()\n host = f\"{ip}:{port}\"\n proxies.append(host)\n except IndexError:\n continue\n return proxies\n\ndef get_session(proxies):\n get_free_proxies()\n proxy = random.choice(proxies) \n all_proxies['http'] = proxy\n return print(\"Proxy | \" + proxy)","repo_name":"DevKylian/Skrap-it.com","sub_path":"scraping/configs/proxies.py","file_name":"proxies.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"71924687608","text":"import threading\nimport time\nimport RPi.GPIO as GPIO\n\nclass ToggleGlowbar(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n def run(self):\n GPIO.output(22, True) # glow bar\n time.sleep(10)\n GPIO.output(23, True)\n time.sleep(2)\n GPIO.output(22, False) ","repo_name":"Zuul86/breware2","sub_path":"ToggleGlowbar.py","file_name":"ToggleGlowbar.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"31177750373","text":"import binascii\nimport hashlib\nimport logging\nimport os\nimport unittest\nfrom uuid import UUID\n\nimport ed25519\nimport ecdsa\n\nimport ubirch\nfrom ubirch.ubirch_protocol import SIGNED, CHAINED\n\nlogger = logging.getLogger(__name__)\n\n# test fixtures\nTEST_UUID = UUID(hex=\"6eac4d0b-16e6-4508-8c46-22e7451ea5a1\")\nTEST_PRIV = bytes.fromhex(\"a6abdc5466e0ab864285ba925452d02866638a8acb5ebdc065d2506661301417\")\nTEST_PUBL = bytes.fromhex(\"b12a906051f102881bbb487ee8264aa05d8d0fcc51218f2a47f562ceb9b0d068\")\n\n# expected simple signed message\nEXPECTED_SIGNED = bytearray(bytes.fromhex(\n \"9522c4106eac4d0b16e645088c4622e7451ea5a1ccef01\"\n \"c440c8f1c19fb64ca6ecd68a336bbffb39e8f4e6ee686de725ce9e23f76945fc2d\"\n \"734b4e77f9f02cb0bb2d4f8f8e361efc5ea10033bdc741a24cff4d7eb08db6340b\"))\n\nEXPECTED_SIGNED_HASH = bytearray(bytes.fromhex(\n \"9522c4106eac4d0b16e645088c4622e7451ea5a1ccefc4404dff4ea340f0a823f1\"\n \"5d3f4f01ab62eae0e5da579ccb851f8db9dfe84c58b2b37b89903a740e1ee172da\"\n \"793a6e79d560e5f7f9bd058a12a280433ed6fa46510ac440c79663647d486d6c4c\"\n \"577d12cb34b825988c9eb4a8d322dbd2ceb8b17c99ce3dd34295cf641ea312ee77\"\n \"c15a2c9b404a32d67abb414061b7639e1ea5a20ce90b\"\n))\n\nEXPECTED_SIGNED_UNPACKED = [\n 34, b'n\\xacM\\x0b\\x16\\xe6E\\x08\\x8cF\"\\xe7E\\x1e\\xa5\\xa1', 239, 1, b'\\xc8\\xf1\\xc1\\x9f\\xb6L\\xa6\\xec\\xd6\\x8a3k\\xbf\\xfb9\\xe8\\xf4\\xe6\\xeehm\\xe7%\\xce\\x9e#\\xf7iE\\xfc-sKNw\\xf9\\xf0,\\xb0\\xbb-O\\x8f\\x8e6\\x1e\\xfc^\\xa1\\x003\\xbd\\xc7A\\xa2L\\xffM~\\xb0\\x8d\\xb64\\x0b'\n]\n\n\n# expected sequence of chained messages\nEXPECTED_CHAINED = [\n bytearray(bytes.fromhex(\n \"9623c4106eac4d0b16e645088c4622e7451ea5a1c44000000000000000000000\"\n \"0000000000000000000000000000000000000000000000000000000000000000\"\n \"00000000000000000000000000000000000000000000ccee01c440296544cbaf\"\n \"aae7646422c7f5cf8c7e8d0767df257b6d66e237f0f98ca8375eb44dc1564607\"\n \"85984b570196ea6834e210dcf991fbbb6cd986a50ae2e2b5268f09\")),\n bytearray(bytes.fromhex(\n \"9623c4106eac4d0b16e645088c4622e7451ea5a1c440296544cbafaae7646422\"\n \"c7f5cf8c7e8d0767df257b6d66e237f0f98ca8375eb44dc156460785984b5701\"\n \"96ea6834e210dcf991fbbb6cd986a50ae2e2b5268f09ccee02c44033c137b6ca\"\n \"f084a5c480a0f129650507f0236be63da60c1cdc89ae4576c5e8b4dd26945ad5\"\n \"84c2c76ba130e1d46f9ae65e59e99f4f16c379329ab6aaf04ab107\")),\n bytearray(bytes.fromhex(\n \"9623c4106eac4d0b16e645088c4622e7451ea5a1c44033c137b6caf084a5c480\"\n \"a0f129650507f0236be63da60c1cdc89ae4576c5e8b4dd26945ad584c2c76ba1\"\n \"30e1d46f9ae65e59e99f4f16c379329ab6aaf04ab107ccee03c440a0a6247a71\"\n \"e31626831d00ba06e0a5bf1a608da1ab8cbdc92664d1675b95a9d92c444ffe2a\"\n \"9ead4e39b187ed4b95c1ad32e06b9795897cdc568c84230fc8c90c\"))\n]\n\nEXPECTED_CHAINED_HASH = bytearray(bytes.fromhex(\n \"9623c4106eac4d0b16e645088c4622e7451ea5a1c440000000000000000000000000\"\n \"00000000000000000000000000000000000000000000000000000000000000000000\"\n \"000000000000000000000000000000000000ccefc4404dff4ea340f0a823f15d3f4f\"\n \"01ab62eae0e5da579ccb851f8db9dfe84c58b2b37b89903a740e1ee172da793a6e79\"\n \"d560e5f7f9bd058a12a280433ed6fa46510ac440dde50cad0db567dee187513e2d11\"\n \"bb2d9ba24a85fe6dddc4a0dc0b28fa2cd28bca72a60aa15dda962ae46488c80ae67a\"\n \"67445d257c56febf4f3c5221d95c2309\"\n))\n\n\n# a simple implementation of the ubirch protocol, having a fixed single key (from fixtures)\nclass Protocol(ubirch.Protocol):\n sk = ed25519.SigningKey(TEST_PRIV)\n vk = ed25519.VerifyingKey(TEST_PUBL)\n\n def _sign(self, uuid: UUID, message: bytes) -> bytes:\n if isinstance(self.sk, ecdsa.SigningKey):\n # no hashing required here\n final_message = message\n elif isinstance(self.sk, ed25519.SigningKey):\n final_message = hashlib.sha512(message).digest() \n else: \n raise(ValueError(\"Signing Key is neither ed25519, nor ecdsa!\")) \n \n return self.sk.sign(final_message)\n\n def _verify(self, uuid: UUID, message: bytes, signature: bytes):\n if isinstance(self.vk, ecdsa.VerifyingKey):\n # no hashing required here\n final_message = message\n elif isinstance(self.vk, ed25519.VerifyingKey):\n final_message = hashlib.sha512(message).digest() \n else: \n raise(ValueError(\"Verifying Key is neither ed25519, nor ecdsa!\")) \n \n return self.vk.verify(signature, final_message)\n\n\nclass TestUbirchProtocol(unittest.TestCase):\n def test_sign_not_implemented(self):\n p = ubirch.Protocol()\n try:\n p.message_signed(TEST_UUID, 0xEF, 1)\n except NotImplementedError as e:\n self.assertEqual(e.args[0], 'signing not implemented')\n\n def test_verify_not_implemented(self):\n p = ubirch.Protocol()\n try:\n p.verfiy_signature(None, EXPECTED_SIGNED)\n except NotImplementedError as e:\n self.assertEqual(e.args[0], 'verification not implemented')\n\n def test_get_unpacked_index(self):\n p = Protocol()\n\n # test indexes of signatures for unsigned messages\n self.assertEqual(p.get_unpacked_index(0b0001, ubirch.ubirch_protocol.UNPACKED_UPP_FIELD_SIG), -1)\n self.assertEqual(p.get_unpacked_index(0b0001, ubirch.ubirch_protocol.UNPACKED_UPP_FIELD_PREV_SIG), -1)\n \n # test indexes of signatures for signed messages\n self.assertEqual(p.get_unpacked_index(0b0010, ubirch.ubirch_protocol.UNPACKED_UPP_FIELD_SIG), 4)\n self.assertEqual(p.get_unpacked_index(0b0010, ubirch.ubirch_protocol.UNPACKED_UPP_FIELD_PREV_SIG), -1)\n\n # test indexes of signatures for chained messages\n self.assertEqual(p.get_unpacked_index(0b0011, ubirch.ubirch_protocol.UNPACKED_UPP_FIELD_SIG), 5)\n self.assertEqual(p.get_unpacked_index(0b0011, ubirch.ubirch_protocol.UNPACKED_UPP_FIELD_PREV_SIG), 2)\n\n def test_unpack_upp(self):\n p = Protocol()\n\n self.assertEqual(p.unpack_upp(EXPECTED_SIGNED), EXPECTED_SIGNED_UNPACKED)\n\n BROKEN_EXPECTED_SIGNED = EXPECTED_SIGNED.copy()\n BROKEN_EXPECTED_SIGNED[1] = 0\n\n self.assertRaises(ValueError, p.unpack_upp, BROKEN_EXPECTED_SIGNED)\n\n return\n\n def test_create_signed_message(self):\n p = Protocol()\n message = p.message_signed(TEST_UUID, 0xEF, 1)\n logger.debug(\"MESSAGE: %s\", binascii.hexlify(message))\n self.assertEqual(EXPECTED_SIGNED, message)\n\n def test_create_signed_message_with_hash(self):\n p = Protocol()\n message = p.message_signed(TEST_UUID, 0xEF, hashlib.sha512(b'1').digest())\n logger.debug(\"MESSAGE: %s\", binascii.hexlify(message))\n self.assertEqual(EXPECTED_SIGNED_HASH, message)\n\n def test_create_chained_messages(self):\n p = Protocol()\n for i in range(0, 3):\n message = p.message_chained(TEST_UUID, 0xEE, i + 1)\n logger.debug(\"MESSAGE: %s\", binascii.hexlify(message))\n self.assertEqual(EXPECTED_CHAINED[i], message, \"message #{} failed\".format(i + 1))\n\n def test_create_chained_message_with_hash(self):\n p = Protocol()\n message = p.message_chained(TEST_UUID, 0xEF, hashlib.sha512(b'1').digest())\n logger.debug(\"MESSAGE: %s\", binascii.hexlify(message))\n self.assertEqual(EXPECTED_CHAINED_HASH, message)\n\n def test_verify_signed_message(self):\n p = Protocol()\n unpacked = p.unpack_upp(EXPECTED_SIGNED)\n self.assertEqual(p.verfiy_signature(UUID(bytes=unpacked[1]), bytes(EXPECTED_SIGNED)), True)\n self.assertEqual(SIGNED, unpacked[0])\n self.assertEqual(TEST_UUID.bytes, unpacked[1])\n self.assertEqual(0xEF, unpacked[2])\n self.assertEqual(1, unpacked[3])\n\n def test_verify_chained_messages(self):\n p = Protocol()\n last_signature = b'\\0' * 64\n for i in range(0, 3):\n unpacked = p.unpack_upp(EXPECTED_CHAINED[i])\n self.assertEqual(p.verfiy_signature(UUID(bytes=unpacked[1]), bytes(EXPECTED_CHAINED[i])), True)\n self.assertEqual(CHAINED, unpacked[0])\n self.assertEqual(TEST_UUID.bytes, unpacked[1])\n self.assertEqual(last_signature, unpacked[2])\n self.assertEqual(0xEE, unpacked[3])\n self.assertEqual(i + 1, unpacked[4])\n # update the last signature we expect in the next message\n last_signature = unpacked[5]\n\n # TODO add randomized message generation and verification\n\n def test_set_saved_signatures(self):\n p = Protocol()\n p.set_saved_signatures({TEST_UUID: \"1234567890\"})\n\n self.assertEqual({TEST_UUID: \"1234567890\"}, p.get_saved_signatures())\n\n def test_set_saved_signatures_changed(self):\n p = Protocol()\n p.set_saved_signatures({TEST_UUID: \"1234567890\"})\n self.assertEqual({TEST_UUID: \"1234567890\"}, p.get_saved_signatures())\n\n # sign a message and expect the last signature for this UUID to change\n p.message_signed(TEST_UUID, 0xEF, 1, True)\n self.assertEqual({TEST_UUID: EXPECTED_SIGNED[-64:]}, p.get_saved_signatures())\n\n def test_set_saved_signatures_unchanged(self):\n p = Protocol()\n p.set_saved_signatures({TEST_UUID: \"1234567890\"})\n self.assertEqual({TEST_UUID: \"1234567890\"}, p.get_saved_signatures())\n\n # sign a message and do not save the last signature\n p.message_signed(TEST_UUID, 0xEF, 1, False)\n self.assertEqual({TEST_UUID: \"1234567890\"}, p.get_saved_signatures())\n\n def test_reset_saved_signatures(self):\n p = Protocol()\n p.set_saved_signatures({TEST_UUID: \"1234567890\"})\n self.assertEqual({TEST_UUID: \"1234567890\"}, p.get_saved_signatures())\n\n # sign a message and expect the last signature for this UUID to change\n p.message_signed(TEST_UUID, 0xEF, 1, True)\n p.reset_signature(TEST_UUID)\n self.assertEqual({}, p.get_saved_signatures())\n\n #disable the legacy trackle message test\n \"\"\"\n def test_unpack_legacy_trackle_message(self):\n loc = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n\n with open(os.path.join(loc, \"v0.4-trackle-production.mpack\"), \"rb\") as f:\n message = f.read()\n\n class ProtocolNoVerify(ubirch.Protocol):\n def _verify(self, uuid: UUID, message: bytes, signature: bytes) -> bytes:\n pass\n \n p = ProtocolNoVerify()\n \n unpacked = p.unpack_upp(message)\n \n self.assertEqual(p.verfiy_signature(UUID(bytes=unpacked[1]), bytes(EXPECTED_CHAINED[i])), True)\n self.assertEqual(CHAINED & 0x0f, unpacked[0] & 0x0f)\n self.assertEqual(UUID(bytes=bytes.fromhex(\"af931b05acca758bc2aaeb98d6f93329\")), UUID(bytes=unpacked[1]))\n self.assertEqual(0x54, unpacked[3])\n\n payload = unpacked[4]\n self.assertEqual(\"v1.0.2-PROD-20180326103205 (v5.6.6)\", bytes.decode(payload[0]))\n self.assertEqual(2766, payload[1])\n self.assertEqual(3, payload[2])\n self.assertEqual(736, len(payload[3]))\n self.assertEqual(3519, payload[3].get(1533846771))\n self.assertEqual(3914, payload[3].get(1537214378))\"\"\"\n\n def test_unpack_register_v1(self):\n loc = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n\n with open(os.path.join(loc, \"v1.0-register.mpack\"), \"rb\") as f:\n message = f.read()\n\n class ProtocolNoVerify(ubirch.Protocol):\n def _verify(self, uuid: UUID, message: bytes, signature: bytes) -> bytes:\n pass\n\n p = ProtocolNoVerify()\n\n unpacked = p.unpack_upp(message)\n\n self.assertEqual(SIGNED & 0x0f, unpacked[0] & 0x0f)\n self.assertEqual(1, unpacked[0] >> 4)\n self.assertEqual(UUID(bytes=bytes.fromhex(\"00000000000000000000000000000000\")), UUID(bytes=unpacked[1]))\n self.assertEqual(0x01, unpacked[2])\n\n payload = unpacked[3]\n expectedPubKey = binascii.unhexlify(\"2c37eee25b08490a9936e0c4d1f8f2091bebdbc3b08e29164e833a33742df91a\")\n\n self.assertEqual(b'ECC_ED25519', payload[b'algorithm'])\n self.assertEqual( 1542793437, payload[b'created'])\n self.assertEqual(b'\\0'*16, payload[b'hwDeviceId'])\n self.assertEqual(expectedPubKey, payload[b'pubKey'])\n self.assertEqual(expectedPubKey, payload[b'pubKeyId'])\n self.assertEqual( 1574329437, payload[b'validNotAfter'])\n self.assertEqual( 1542793437, payload[b'validNotBefore'])","repo_name":"ubirch/ubirch-template-repository","sub_path":"tests/test_ubirch_protocol.py","file_name":"test_ubirch_protocol.py","file_ext":"py","file_size_in_byte":12397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"3824560584","text":"from django.urls import path\nfrom . import views\n\nfrom .views import IdeaListView, IdeaDetailView, IdeaCreateView, IdeaUpdateView, IdeaDeleteView\n\napp_name='ideabin'\n\nurlpatterns = [\n path('',IdeaListView.as_view(), name='index'),\n path('',IdeaDetailView.as_view(), name='detail'),\n path('add/',IdeaCreateView.as_view(), name='add'),\n path('edit/',IdeaUpdateView.as_view(), name='edit'),\n path('delete/',IdeaDeleteView.as_view(), name='delete'),\n]","repo_name":"rohan-krishna/wealthy-web","sub_path":"ideabin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"17465674433","text":"from copy import deepcopy\n\nimport plotly.graph_objects as go\nfrom ax.core.data import Data\nfrom ax.modelbridge.registry import Models\nfrom ax.plot.base import AxPlotConfig\nfrom ax.plot.scatter import interact_fitted, interact_fitted_plotly\nfrom ax.utils.common.testutils import TestCase\nfrom ax.utils.testing.core_stubs import get_branin_experiment\nfrom ax.utils.testing.mock import fast_botorch_optimize\n\n\nclass FittedScatterTest(TestCase):\n @fast_botorch_optimize\n def test_fitted_scatter(self) -> None:\n exp = get_branin_experiment(with_str_choice_param=True, with_batch=True)\n exp.trials[0].run()\n # dup branin\n data = exp.fetch_data()\n df = deepcopy(data.df)\n df[\"metric_name\"] = \"branin_dup\"\n\n model = Models.BOTORCH_MODULAR(\n # Model bridge kwargs\n experiment=exp,\n data=Data.from_multiple_data([data, Data(df)]),\n )\n # Assert that each type of plot can be constructed successfully\n scalarized_metric_config = [\n {\"name\": \"branin:agg\", \"weight\": {\"branin\": 0.5, \"branin_dup\": 0.5}}\n ]\n plot = interact_fitted_plotly(\n model=model, rel=False, scalarized_metric_config=scalarized_metric_config\n )\n self.assertIsInstance(plot, go.Figure)\n plot = interact_fitted(\n model=model, rel=False, scalarized_metric_config=scalarized_metric_config\n )\n self.assertIsInstance(plot, AxPlotConfig)\n\n # Make sure all parameters and metrics are displayed in tooltips\n tooltips = list(exp.parameters.keys()) + list(exp.metrics.keys())\n for d in plot.data[\"data\"]:\n # Only check scatter plots hoverovers\n if d[\"type\"] != \"scatter\":\n continue\n for text in d[\"text\"]:\n for tt in tooltips:\n self.assertTrue(tt in text)\n","repo_name":"facebook/Ax","sub_path":"ax/plot/tests/test_fitted_scatter.py","file_name":"test_fitted_scatter.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","stars":2182,"dataset":"github-code","pt":"77"}
+{"seq_id":"19476333767","text":"class ICSParser():\n '''\n Takes in ics file and outputs it into dictionary format\n \n {\n AssignmentName : \n {\n Date: MMDDYYYY,\n Class : class,\n }\n ...\n }\n\n '''\n def parse(self, text):\n text = text.split(\"BEGIN:VEVENT\")\n event = {}\n for item in text:\n if 'SUMMARY:' in item:\n assignmentName = item.split(\"SUMMARY:\")[1].split('URL:')[0]\n className, assignmentName = self.getSplitString(assignmentName, \"[\", \" (\")\n date = self.cleanString(str(item.split(\"VALUE=DATE:\")[1].split(\"CLASS:\")[0]), \"\\r\", \"\\n\")\n event[assignmentName] = {\n \"Date\" : date,\n \"Class\" : className\n }\n return event\n\n def cleanString(self, string, *args):\n for str in args:\n splitstring = string.split(str)\n splitstring = [x.lstrip() for x in splitstring]\n string = ''.join(splitstring)\n return string\n\n def getSplitString(self, string, str1, str2):\n idx1 = string.find(str1)\n idx2 = string.find(str2)\n\n splitStr1 = self.cleanString(string[idx1 + len(str1): idx2], \"\\r\", \"\\n\")\n splitStr2 = self.cleanString(string[0:idx1-1], \" [\", \"(\")\n\n return splitStr1, splitStr2\n\n \n \n","repo_name":"colinpannikkat/canvas_to_reminders","sub_path":"icsparser.py","file_name":"icsparser.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"37632155088","text":"\n\ndata = \"\"\nwith open('day6.txt', 'r') as f:\n data = f.readlines()\n\ndef checkIfDuplicates_1(listOfElems):\n ''' Check if given list contains any duplicates '''\n if len(listOfElems) == len(set(listOfElems)):\n return False\n else:\n return True\n\nfor item in data:\n numChar = 4\n tempArr = []\n for letter in item:\n tempArr.append(letter)\n if len(tempArr) == 4:\n result = checkIfDuplicates_1(tempArr)\n if result:\n numChar += 1\n tempArr.pop(0)\n print(numChar)\n\nfor item in data:\n numChar = 14\n tempArr = []\n for letter in item:\n tempArr.append(letter)\n if len(tempArr) == 14:\n result = checkIfDuplicates_1(tempArr)\n if result:\n numChar += 1\n tempArr.pop(0)\n print(numChar)","repo_name":"sburgholzer/Advent-of-Code-2022","sub_path":"day6.py","file_name":"day6.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"18331265323","text":"#!/usr/bin/env python3\n##\n## EPITECH PROJECT, 2020\n## main.py\n## File description:\n## blabla\n##\n\nimport math\nimport sys\nimport string\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\n\ndef horner(poly, n, x): \n result = poly[0]\n for i in range(1, n):\n result = result*x + poly[i]\n return result\n\ndef make_expression(yolo):\n number_string = yolo.split('*')\n number_string = [int(i) for i in number_string]\n P = number_string[::-1]\n return P\n\n\ndef check(yolo):\n a = len(yolo) - 1\n b = 0\n while (b < a):\n try:\n val = float(yolo[b])\n except ValueError:\n sys.exit(84)\n b = b + 2\n\ndef main(argv):\n px = []\n py = []\n #fig = plt.figure()\n #ax = fig.add_subplot(111, projection='3d')\n if (len(sys.argv) == 3):\n check(argv[0])\n check(argv[1])\n poly = make_expression(argv[0])\n poly2 = make_expression(argv[1])\n x = 0\n r1 = round(horner(poly, len(poly), x), 5)\n r2 = round(horner(poly2, len(poly2), x), 5)\n if (r2 == 0):\n print(\"Division by 0\")\n return 84\n while (x < 1.001):\n r1 = round(horner(poly, len(poly), x), 5)\n r2 = round(horner(poly2, len(poly2), x), 5)\n print(\"%.3f ->\" % x, end= ' ')\n print(\"%.5f\" % (r1 / r2))\n x = x + 0.001\n px.append(x)\n py.append(r1/r2)\n x = round(x, 3)\n #plt.plot(px, py)\n plt.scatter(px, py, color='b')\n plt.title('Courbe transfer')\n plt.xlabel('x')\n plt.ylabel('r1 / R2')\n plt.show()\n else:\n return 84","repo_name":"Paul-Czaplinski/Epitech-Maths","sub_path":"107transfer_2019/bonus/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"74476982009","text":"from django.core.mail import EmailMessage\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.template.loader import render_to_string\nfrom django.utils.html import strip_tags\n\nclass Util:\n @staticmethod\n def send_email(data):\n # Renderiza el template del email\n html_message = render_to_string(\n 'email_template.html', {'user': data['user'], 'absurl': data['absurl']})\n\n # Remueve las etiquetas HTML para obtener el texto plano\n plain_message = strip_tags(html_message)\n\n email = EmailMultiAlternatives(\n subject=data['subject'],\n body=plain_message,\n to=[data['email']]\n )\n\n # Adjunta el contenido HTML\n email.attach_alternative(html_message, 'text/html')\n email.send()\n","repo_name":"IvanDLPG-EDU/rolgm-project","sub_path":"backend/authentication_core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"14549195147","text":"# Proszę zaimplementować jeden ze standardowych algorytmów sortowania tablicy działający w\n# czasie O(n^2) (np. sortowanie bąbelkowe, sortowanie przez wstawianie, sortowanie przez wybieranie).\n\ndef bubbleSort(arr):\n n = len(arr)\n for i in range(n - 1):\n for j in range(0, n - i - 1):\n if arr[j] > arr[j + 1]:\n arr[j], arr[j + 1] = arr[j + 1], arr[j]\n return arr\n\n\ndef swap(array, right, left): # zamiaaaaaaaaaana\n temporary_value = array[left]\n array[left] = array[right]\n array[right] = temporary_value","repo_name":"pvtrov/algorithms-and-data-structures","sub_path":"exercises_from_course/labs/lab01_sorting/zad1.py","file_name":"zad1.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"pl","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"24330000177","text":"\"\"\" \nPlus One\n\nTopics: arrays\n\nInput:\n1. array representing integer digits, where each element is the th digit of the integer\neg [1,2,3,4] represents integer 1,234\n\nThe digits are ordered from most significant to least significant in left-to-right order. \nThe large integer does not contain any leading 0's.\n\nIncrement the large integer by one and return the resulting array of digits.\n\nOutput:\n1. resulting array\n\nConstraints:\n1. 1 <= digits.length <= 100\n2. 0 <= digits[i] <= 9\n3. digits does not contain any leading 0's.\n\"\"\"\nclass Solution:\n def plusOne(self, nums):\n nums.reverse()\n for index in range(0, len(nums)):\n nums[index]=nums[index]+1\n if nums[index]>9:\n nums[index]=0\n if index+1 >= len(nums):\n nums.append(1)\n break\n else:\n nums[index+1]=nums[index+1]\n else:\n break\n nums.reverse()\n return nums\n\nnums1 = [3,6,1,0]\nnums2 = [9,9,9,9]\nnums3 = [4,3,2,1] \nnums4 = [0] \nnums5 = [8,9,9,9]\n\nTest = Solution()\n\nprint(Test.plusOne(nums1))\nprint(Test.plusOne(nums2))\nprint(Test.plusOne(nums3))\nprint(Test.plusOne(nums4))\nprint(Test.plusOne(nums5))","repo_name":"pgtval13/pgtval13","sub_path":"Learn/Python/Data Structures/Array and String/01_plusOne.py","file_name":"01_plusOne.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"29328135969","text":"#Aprobación de créditos\ningreso=int(input('ingrese su ingreso mensual: '))\nnac=int(input('ingrese su año de nacimiento: '))\nhijos=int(input('cantidad de hijos: '))\npert=int(input('ingrese sus años de pertenencia al banco: '))\nestado=input('ingrese su estado civil (S= soltero),(C= casado): ')\nlugar=input('ingrese U si vive en ciudad o R si vive en el campo: ')\nedad= 2020-nac\n\nif pert > 10 and hijos>=2:\n print('APROBADO')\nelif estado == 'S' and hijos > 3 and 55>edad>45:\n print('APROBADO')\nelif ingreso > 2500000 and estado == 'S' and lugar == 'U':\n print('APROBADO')\nelif ingreso > 3500000 and pert > 5:\n print('APROBADO')\nelif lugar == 'R' and estado == 'C' and hijos < 2:\n print('APROBADO')\n\nelse:\n print('RECHAZADO')\n\n\n\n\n\n\n\n\n","repo_name":"pabloschwarzenberg/grader","sub_path":"hito1_ej3/hito1_ej3_61324ac4c37f9c26e2c04712bb93b4e3.py","file_name":"hito1_ej3_61324ac4c37f9c26e2c04712bb93b4e3.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"35973988049","text":"'''\nThis is a supporting library with the code of the model.\n\nPaper: Predicting Dynamic Embedding Trajectory in Temporal Interaction Networks. S. Kumar, X. Zhang, J. Leskovec. ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (KDD), 2019. \n'''\n\nfrom __future__ import division\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nfrom torch.autograd import Variable\nfrom torch import optim\nimport numpy as np\nimport math, random\nimport sys\nfrom collections import defaultdict\nimport os\nimport sys\nimport pickle\n#import gpustat\nfrom itertools import chain\nfrom tqdm import tqdm, trange, tqdm_notebook, tnrange\nimport csv\nimport sklearn\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler()\nepsilon = 1e-6\nPATH = \"./\"\n\ntry:\n get_ipython\n trange = tnrange\n tqdm = tqdm_notebook\nexcept NameError:\n pass\n\ntotal_reinitialization_count = 0\n\n# A NORMALIZATION LAYER\nclass NormalLinear(nn.Linear):\n def reset_parameters(self):\n stdv = 1. / math.sqrt(self.weight.size(1))\n self.weight.data.normal_(0, stdv)\n if self.bias is not None:\n self.bias.data.normal_(0, stdv)\n\n\n# THE JODIE MODULE\nclass JODIE(nn.Module):\n def __init__(self, args, num_features, num_users, num_items):\n super(JODIE,self).__init__()\n\n print(\"*** Initializing the JODIE model ***\")\n self.modelname = args.model\n self.embedding_dim = args.embedding_dim\n self.num_users = num_users\n self.num_items = num_items\n self.user_static_embedding_size = num_users\n self.item_static_embedding_size = num_items\n\n print(\"Initializing user and item embeddings\")\n self.initial_user_embedding = nn.Parameter(torch.Tensor(2*args.embedding_dim))\n self.initial_item_embedding = nn.Parameter(torch.Tensor(args.embedding_dim))\n\n rnn_input_size_items = rnn_input_size_users = self.embedding_dim + 1 + num_features\n\n print( \"Initializing user and item RNNs\")\n self.item_rnn = nn.RNNCell(rnn_input_size_users, self.embedding_dim)\n self.user_rnn = nn.RNNCell(rnn_input_size_items, self.embedding_dim*2)\n self.decay_rate = nn.RNNCell(2*self.embedding_dim, 1)\n\n print (\"Initializing linear layers\")\n self.linear_layer1 = nn.Linear(self.embedding_dim, 50)\n self.linear_layer2 = nn.Linear(50, 2)\n self.linear_layer3 = nn.Linear(self.embedding_dim, 1)\n self.linear_layer4 = nn.Linear(self.embedding_dim, self.embedding_dim)\n # self.linear_layer5 = nn.Linear(self.embedding_dim, args.k)\n self.prediction_layer = nn.Linear(self.user_static_embedding_size + self.item_static_embedding_size + self.embedding_dim * 2, self.item_static_embedding_size + self.embedding_dim)\n self.embedding_layer = NormalLinear( 1, self.embedding_dim)\n\n print( \"*** JODIE initialization complete ***\\n\\n\")\n \n def forward(self,args, user_embeddings, item_embeddings, timediffs=None, features=None, select=None):\n if select == 'item_update':\n user_embeddings_input = user_embeddings[:,:args.embedding_dim]\n input1 = torch.cat([user_embeddings_input, timediffs, features], dim=1)\n item_embedding_output = self.item_rnn(input1, item_embeddings)\n return F.normalize(item_embedding_output)\n\n elif select == 'user_update':\n\n input2 = torch.cat([item_embeddings, timediffs, features], dim=1)\n user_embedding_output = self.user_rnn(input2, user_embeddings)\n return F.normalize(user_embedding_output)\n\n def compute_local_embeddings(self, args, embeddings, local_embeddings):\n user_embedding = embeddings[:, :args.embedding_dim]\n\n user_embedding = F.normalize(self.linear_layer4(user_embedding))\n user_embedding = user_embedding.unsqueeze(1).repeat(1, args.k, 1)\n local_embeddings_temp = local_embeddings.unsqueeze(0).repeat(len(user_embedding), 1, 1)\n user_embeddings_local = torch.norm(user_embedding - local_embeddings_temp, p=2, dim=-1)\n\n user_embeddings_local = user_embeddings_local / (torch.max(user_embeddings_local, dim=1).unsqueeze(1))\n user_embeddings_local = torch.nn.functional.threshold_(user_embeddings_local, 1, 0)\n return user_embeddings_local\n\n\n\n def project_user2(self, args, embeddings, local_embeddings, userids, gu, timediffs, timestamps, user_timestamp, user_embeddings, alpha, delta):\n\n\n new_embeddings = embeddings[:,:args.embedding_dim]* (1 + self.embedding_layer(timediffs))\n return new_embeddings\n # def compute_weight(self,args, embeddings, local_embeddings):\n # user_embedding = embeddings[:, :args.embedding_dim]\n #\n # user_embedding = F.normalize(self.linear_layer4(user_embedding))\n # user_embedding = user_embedding.unsqueeze(1).repeat(1, args.k, 1)\n # local_embeddings_temp = local_embeddings.unsqueeze(0).repeat(len(embeddings), 1, 1)\n # user_embeddings_local = torch.norm(user_embedding.clone() - local_embeddings_temp.clone(), p=2, dim=-1)\n # user_embeddings_coeff = nn.Softmax(dim=1)(-user_embeddings_local)\n #\n # return user_embeddings_coeff\n #\n\n\n def project_user3(self, args, embeddings,local_embeddings, userids, gu, timediffs, timestamps, user_timestamp, user_embeddings, alpha, delta):\n user_embedding = embeddings[:, :args.embedding_dim]\n\n user_embedding = F.normalize(self.linear_layer4(user_embedding))\n user_embedding = user_embedding.unsqueeze(1).repeat(1, args.k, 1)\n local_embeddings_temp = local_embeddings.unsqueeze(0).repeat(len(userids), 1, 1)\n user_embeddings_local = torch.norm(user_embedding - local_embeddings_temp, p=2, dim=-1)\n\n user_embeddings_local = user_embeddings_local / (torch.sum(user_embeddings_local, dim=1).unsqueeze(1))\n user_embeddings_local = torch.nn.functional.threshold_(user_embeddings_local, 1, 0)\n # user_embeddings_local = nn.Softmax(dim=1)(-user_embeddings_local)\n\n user_embeddings_local = torch.mm(user_embeddings_local.clone(), local_embeddings.clone())\n\n user_embeddings_key = embeddings[:, args.embedding_dim:]\n\n new_embeddings = gu.unsqueeze(1) * user_embeddings_key + (1 - gu).unsqueeze(1) * user_embeddings_local\n\n return new_embeddings\n\n\n\n def project_user(self, args, embeddings,local_embeddings, userids, timediffs, timestamps, user_timestamp, user_embeddings, alpha, delta):\n # user_embedding = embeddings[:,args.embedding_dim:]\n # #delta_u = self.linear_layer3(user_embedding)\n # user_embeddings_key = self.linear_layer4(user_embedding)\n #\n # user_timestamp_tensor = torch.t(user_timestamp.repeat(1,timestamps.shape[0]))\n #\n #\n # timestamps_tensor = timestamps.expand_as(user_timestamp_tensor)\n #\n # user_timestamp_tensor = timestamps_tensor-user_timestamp_tensor\n #\n # #print(user_timestamp_tensor)\n # #print('here')\n #\n # user_timestamp= scaler.fit_transform(np.transpose(user_timestamp_tensor.data.cpu().numpy()))\n # #print(user_timestamp)\n # user_timestamp_tensor= torch.t(torch.from_numpy(user_timestamp).cuda())\n # #mask = torch.where(user_timestamp_tensor > 0, torch.ones(user_timestamp_tensor.shape).cuda(), torch.zeros(user_timestamp_tensor.shape).cuda())\n # #print(user_timestamp_tensor)\n # delta_key = delta[userids,:]\n # alpha_key = alpha[userids,:]\n #\n # exp_timediffs = torch.exp(-delta_key* user_timestamp_tensor)\n # static_user_embeddings_coeff = alpha_key*exp_timediffs\n # #static_user_embeddings_coeff_softmax =nn.LogSoftmax( dim=1)(static_user_embeddings_coeff)\n #\n # user_embeddings_query = user_embeddings[:,:args.embedding_dim]\n #\n # static_user_embeddings = torch.matmul(static_user_embeddings_coeff.clone(), user_embeddings_query.clone())\n #\n # new_embeddings = gu*user_embeddings_key+(1-gu)*static_user_embeddings\n #\n # if torch.isnan(new_embeddings).any():\n # #print(user_timestamp_tensor)\n # idx = (torch.nonzero(torch.isnan(new_embeddings)))\n #\n # print(user_embeddings_key[idx[0]])\n # print(user_embeddings[idx[0]])\n # print(static_user_embeddings[idx[0]])\n # print(user_timestamp_tensor)\n # print(alpha_key)\n # print(delta_key)\n # print(new_embeddings)\n # sys.exit()\n #\n #\n # return new_embeddings\n user_embedding = embeddings[:, args.embedding_dim:]\n delta_u = self.linear_layer3(user_embedding)\n user_embeddings_key = self.linear_layer4(user_embedding)\n\n user_timestamp_tensor = torch.t(user_timestamp.repeat(1, timestamps.shape[0]))\n\n timestamps_tensor = timestamps.expand_as(user_timestamp_tensor)\n\n user_timestamp_tensor = timestamps_tensor - user_timestamp_tensor\n mask = torch.where(user_timestamp_tensor>0, torch.ones(user_timestamp_tensor.shape).cuda(), torch.zeros(user_timestamp_tensor.shape).cuda())\n\n user_timestamp = scaler.fit_transform(np.transpose(user_timestamp_tensor.data.cpu().numpy()))\n\n user_timestamp_tensor = torch.t(torch.from_numpy(user_timestamp).cuda())\n # print(user_timestamp_tensor)\n delta_key = delta[userids, :]\n alpha_key = alpha[userids, :]\n\n exp_timediffs = torch.exp(-delta_key * user_timestamp_tensor)\n static_user_embeddings_coeff = mask * local_embeddings[userids]*alpha_key * exp_timediffs\n # static_user_embeddings_coeff_softmax =nn.LogSoftmax( dim=1)(static_user_embeddings_coeff)\n\n user_embeddings_query = user_embeddings[:, :args.embedding_dim]\n\n static_user_embeddings = torch.matmul(static_user_embeddings_coeff.clone(), user_embeddings_query.clone())\n\n new_embeddings = user_embeddings_key + static_user_embeddings\n\n if torch.isnan(new_embeddings).any():\n # print(user_timestamp_tensor)\n idx = (torch.nonzero(torch.isnan(new_embeddings)))\n\n sys.exit()\n\n return new_embeddings\n\n # def project_user(self, args, embeddings, userids, timediffs, timestamps, user_timestamp, user_embeddings, alpha, delta):\n # user_embeddings = embeddings[:,:args.embedding_dim]\n # new_embeddings = user_embeddings * (1 + self.embedding_layer(timediffs))\n # return new_embeddings\n\n def compute_NN(self,num_tbatch_users, user_embedding, num_users, user_embeddings):\n user_embedding_temp = user_embedding.unsqueeze(1).repeat(1, num_users, 1)\n user_embeddings_temp = user_embeddings.unsqueeze(0).repeat(num_tbatch_users, 1, 1)\n user_embeddings_local = torch.norm(user_embedding_temp - user_embeddings_temp, p=2, dim=-1)\n user_embeddings_mean =torch.mean(user_embeddings_local, 1, True, None)\n user_embeddings_local = user_embeddings_local - user_embeddings_mean\n user_embeddings_local = nn.Sigmoid()(user_embeddings_local)\n user_embeddings_local = torch.where(user_embeddings_local>0.8, torch.ones(user_embeddings_local.shape).cuda(),torch.zeros(user_embeddings_local.shape).cuda())\n return user_embeddings_local\n\n # def project_user4(self,user_embedding, local_embeddings, embeddings):\n # user_embedding =\n\n\n def predict_label(self, user_embeddings):\n X_out = nn.ReLU()(self.linear_layer1(user_embeddings))\n X_out = self.linear_layer2(X_out)\n return X_out\n\n def predict_item_embedding(self, user_embeddings):\n X_out = self.prediction_layer(user_embeddings)\n if torch.isnan(X_out).any():\n print(user_embeddings)\n print(torch.isnan(self.prediction_layer.weight).any())\n print(torch.isnan(self.prediction_layer.weight).any())\n print(torch.isnan(user_embeddings).any())\n sys.exit()\n return X_out\n\n\n\n\n# INITIALIZE T-BATCH VARIABLES\ndef reinitialize_tbatches():\n global current_tbatches_interactionids, current_tbatches_user, current_tbatches_item, current_tbatches_timestamp, current_tbatches_feature, current_tbatches_label, current_tbatches_previous_item\n global tbatchid_user, tbatchid_item, current_tbatches_user_timediffs, current_tbatches_item_timediffs, current_tbatches_user_timediffs_next, current_tbatches_timestamps, current_tbatches_negative_items\n\n # list of users of each tbatch up to now\n current_tbatches_interactionids = defaultdict(list)\n current_tbatches_user = defaultdict(list)\n current_tbatches_item = defaultdict(list)\n current_tbatches_timestamp = defaultdict(list)\n current_tbatches_feature = defaultdict(list)\n current_tbatches_label = defaultdict(list)\n current_tbatches_previous_item = defaultdict(list)\n current_tbatches_user_timediffs = defaultdict(list)\n current_tbatches_item_timediffs = defaultdict(list)\n current_tbatches_user_timediffs_next = defaultdict(list)\n current_tbatches_user_timediffs_next= defaultdict(list)\n current_tbatches_timestamps = defaultdict(list)\n current_tbatches_negative_items= defaultdict(list)\n\n # the latest tbatch a user is in\n tbatchid_user = defaultdict(lambda: -1)\n\n # the latest tbatch a item is in\n tbatchid_item = defaultdict(lambda: -1)\n\n global total_reinitialization_count\n total_reinitialization_count +=1\n\n\n# CALCULATE LOSS FOR THE PREDICTED USER STATE \ndef calculate_state_prediction_loss(model, tbatch_interactionids, user_embeddings_time_series, y_true, loss_function):\n # PREDCIT THE LABEL FROM THE USER DYNAMIC EMBEDDINGS\n prob = model.predict_label(user_embeddings_time_series[tbatch_interactionids,:])\n y = Variable(torch.LongTensor(y_true).cuda()[tbatch_interactionids])\n \n loss = loss_function(prob, y)\n\n return loss\n\n\n# SAVE TRAINED MODEL TO DISK\ndef save_model(model, optimizer, args, epoch, user_embeddings, item_embeddings, train_end_idx, alpha, delta, local_embeddings, user_current_timestamp, user_embeddings_time_series=None, item_embeddings_time_series=None, path=PATH):\n print (\"*** Saving embeddings and model ***\")\n state = {\n 'user_embeddings': user_embeddings.data.cpu().numpy(),\n 'item_embeddings': item_embeddings.data.cpu().numpy(),\n 'local_embeddings' : local_embeddings.data.cpu().numpy(),\n 'epoch': epoch,\n 'state_dict': model.state_dict(),\n 'optimizer' : optimizer.state_dict(),\n 'train_end_idx': train_end_idx,\n 'alpha' : alpha.cpu().detach().numpy(),\n 'delta' : delta.cpu().detach().numpy(),\n # 'delta_u' : delta_u.cpu().detach().numpy(),\n # 'gu' : gu.cpu().detach().numpy(),\n 'user_current_timestamp' : user_current_timestamp.cpu().numpy()\n }\n\n if user_embeddings_time_series is not None and item_embeddings_time_series is not None:\n state['user_embeddings_time_series'] = user_embeddings_time_series.data.cpu().numpy()\n state['item_embeddings_time_series'] = item_embeddings_time_series.data.cpu().numpy()\n\n directory = os.path.join(path, 'saved_models/%s' % args.network)\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n filename = os.path.join(directory, \"checkpoint.%s.ep%d.tp%.1f.pth.tar\" % (args.model, epoch, args.train_proportion))\n torch.save(state, filename)\n print( \"*** Saved embeddings and model to file: %s ***\\n\\n\" % filename)\n\n\n# LOAD PREVIOUSLY TRAINED AND SAVED MODEL\ndef load_model(model, optimizer, args, epoch):\n modelname = args.model\n #print(sum(p.numel() for p in model.parameters() if p.requires_grad))\n filename = PATH + \"saved_models/%s/checkpoint.%s.ep%d.tp%.1f.pth.tar\" % (args.network, modelname, epoch, args.train_proportion)\n checkpoint = torch.load(filename)\n print (\"Loading saved embeddings and model: %s\" % filename)\n args.start_epoch = checkpoint['epoch']\n user_embeddings = Variable(torch.from_numpy(checkpoint['user_embeddings']).cuda())\n item_embeddings = Variable(torch.from_numpy(checkpoint['item_embeddings']).cuda())\n local_embeddings = Variable(torch.from_numpy(checkpoint['local_embeddings']).cuda())\n alpha = Variable(torch.from_numpy(checkpoint['alpha']).cuda())\n delta = Variable(torch.from_numpy(checkpoint['delta']).cuda())\n # delta_u = Variable(torch.from_numpy(checkpoint['delta_u']).cuda())\n # gu = Variable(torch.from_numpy(checkpoint['gu']).cuda())\n user_current_timestamp = Variable(torch.from_numpy(checkpoint['user_current_timestamp']).cuda())\n try:\n train_end_idx = checkpoint['train_end_idx'] \n except KeyError:\n train_end_idx = None\n\n try:\n user_embeddings_time_series = Variable(torch.from_numpy(checkpoint['user_embeddings_time_series']).cuda())\n item_embeddings_time_series = Variable(torch.from_numpy(checkpoint['item_embeddings_time_series']).cuda())\n except:\n user_embeddings_time_series = None\n item_embeddings_time_series = None\n\n model.load_state_dict(checkpoint['state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n\n return [model, optimizer, user_embeddings, item_embeddings, user_embeddings_time_series, item_embeddings_time_series,train_end_idx, alpha, delta, local_embeddings,user_current_timestamp]\n\n\n# SET USER AND ITEM EMBEDDINGS TO THE END OF THE TRAINING PERIOD \ndef set_embeddings_training_end(user_embeddings, item_embeddings, user_embeddings_time_series, item_embeddings_time_series, user_data_id, item_data_id, train_end_idx):\n userid2lastidx = {}\n for cnt, userid in enumerate(user_data_id[:train_end_idx]):\n userid2lastidx[userid] = cnt\n itemid2lastidx = {}\n for cnt, itemid in enumerate(item_data_id[:train_end_idx]):\n itemid2lastidx[itemid] = cnt\n\n try:\n embedding_dim = user_embeddings_time_series.size(1)\n except:\n embedding_dim = user_embeddings_time_series.shape[1]\n for userid in userid2lastidx:\n user_embeddings[userid, :embedding_dim] = user_embeddings_time_series[userid2lastidx[userid]]\n for itemid in itemid2lastidx:\n item_embeddings[itemid, :embedding_dim] = item_embeddings_time_series[itemid2lastidx[itemid]]\n\n user_embeddings.detach_()\n item_embeddings.detach_()\n\n\n\n## SELECT THE GPU WITH MOST FREE MEMORY TO SCHEDULE JOB \n#def select_free_gpu():\n# mem = []\n# gpus = list(set([0,1]))\n# for i in gpus:\n# gpu_stats = gpustat.GPUStatCollection.new_query()\n# mem.append(gpu_stats.jsonify()[\"gpus\"][i][\"memory.used\"])\n # return str(gpus[np.argmin(mem)])\n\n","repo_name":"shalini1194/IACN","sub_path":"library_models.py","file_name":"library_models.py","file_ext":"py","file_size_in_byte":18690,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"1985604015","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n### Author: Edward Huang\n\nfrom collections import Counter\nimport file_operations\nimport math\nimport operator\n\n### This script reads the time series data and find the most frequent herbs,\n### and the symptoms that correspond the most to these herbs.\n\ndef get_frequent_herbs(patient_dct):\n # One dictionary counting the herbs, one for the symptoms for each herb.\n herb_count_dct = {}\n herb_symptom_dct = {}\n symptom_count_dct = {}\n\n for key in patient_dct:\n patient_visit_list = patient_dct[key]\n for patient_visit in patient_visit_list:\n diseases, diagnosis_date, symptoms, herbs = patient_visit\n for herb in herbs:\n # Track the herb count for each herb.\n if herb not in herb_count_dct:\n herb_count_dct[herb] = 1\n herb_symptom_dct[herb] = symptoms[:]\n else:\n herb_count_dct[herb] += 1\n herb_symptom_dct[herb] += symptoms[:]\n for symptom in symptoms:\n if symptom not in symptom_count_dct:\n symptom_count_dct[symptom] = 1\n else:\n symptom_count_dct[symptom] += 1\n\n n = sum(symptom_count_dct.values()) + sum(herb_count_dct.values())\n # Get the most frequent herbs.\n frequent_herbs = sorted(herb_count_dct.items(), key=operator.itemgetter(1),\n reverse=True)[:100]\n # Get the top symptoms for each of the top herbs.\n out = open('./results/frequent_herbs_and_symptoms.txt', 'w')\n out.write('herb\\tsymptoms\\n')\n for herb, herb_count in frequent_herbs:\n # Keys are symptoms.\n co_occurrence_dct = Counter(herb_symptom_dct[herb])\n pmi_dct = {}\n for symptom in co_occurrence_dct:\n co_occurrence_count = co_occurrence_dct[symptom]\n symptom_count = symptom_count_dct[symptom]\n if symptom_count < 10:\n continue\n pmi_dct[symptom] = math.log(co_occurrence_count * n / \n float(herb_count * symptom_count), math.e)\n\n frequent_symptoms = sorted(pmi_dct.items(),\n key=operator.itemgetter(1), reverse=True)[:100]\n # out.write(herb + ',' + str(herb_count) + '\\t')\n out.write(herb + '\\t')\n for symptom, pmi in frequent_symptoms:\n # out.write(symptom + ',' + str(co_occurrence_dct[symptom]) + ',' + str(symptom_count_dct[symptom]) + ',' + str(pmi) + '\\t')\n out.write(symptom + ',' + str(pmi) + '\\t')\n out.write('\\n\\n')\n out.close()\n \ndef main():\n patient_dct = file_operations.get_patient_dct()\n frequent_herbs = get_frequent_herbs(patient_dct)\n\nif __name__ == '__main__':\n main()","repo_name":"ewhuang/parecat_bcb16","sub_path":"time_series/frequent_herbs_and_symptoms.py","file_name":"frequent_herbs_and_symptoms.py","file_ext":"py","file_size_in_byte":2761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"31458970999","text":"import subprocess\nimport sys\nimport re\nimport pygeoip\n\n# sys.argv[1] get value in terminal\nTR = ['traceroute', sys.argv[1]] # make traceroute command\nprint('[Destination] ', TR[1])\n\n# universal_newlines=True 'out' convert byte to string\nproc = subprocess.Popen(TR, stdout=subprocess.PIPE, universal_newlines=True)\nout, err = proc.communicate()\n\np = re.compile('\\([^()]*\\)') # get ip in () in 'out'\nIPList = p.findall(out)\ngi = pygeoip.GeoIP('GeoLiteCity.dat')\n\nlatitude = list() # make list to save latitude and lognitude\nlongitude = []\n\nfor i in range(0,len(IPList)):\n IPList[i] = IPList[i].replace('(', '') # remove (, ) form IPList\n IPList[i] = IPList[i].replace(')', '')\n\n if gi.record_by_addr(IPList[i]) == None: # if no geolocation information in databases\n print('[IP] ', IPList[i], ' No Geolocation Information')\n latitude.append('No Geolocation Information')\n longitude.append('No Geolocation Information')\n\n else: # have a geoloction info in databases\n latitude.append(gi.record_by_addr(IPList[i])['latitude'])\n longitude.append(gi.record_by_addr(IPList[i])['longitude'])\n print('[IP] ', IPList[i], ' - Lat : ', latitude[i], ' Lon : ', longitude[i])\n","repo_name":"jms0923/CNU_computerNetworking","sub_path":"tracerouteUsingSubprocess.py","file_name":"tracerouteUsingSubprocess.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"28441495779","text":"from PIL import Image, ImageFont, ImageDraw\n\n\ndef render(text: str, stroke_width=5):\n font = ImageFont.truetype(font=\"malgunbd.ttf\", size=70)\n offset = font.getoffset(text)\n print(offset)\n width, height = font.getsize(text, stroke_width=stroke_width)\n im = Image.new('RGBA', (width, height), (255, 255, 255, 0))\n drawer = ImageDraw.Draw(im)\n\n r, g, b = [6, 193, 193]\n fill_color = (int(r+0.7*(255-r)), int(g+0.7*(255-g)), int(b+0.7*(255-b)))\n stroke_color = (6, 193, 193)\n\n drawer.text((-offset[0]+stroke_width, 0), text, font=font, fill=fill_color, stroke_width=stroke_width,\n stroke_fill=stroke_color)\n\n im.show(\"text-image\")\n im.save(\"OH MY GIRL - STEP BY STEP (Line 1 - Jiho - pre).png\")\n\n im = Image.new('RGBA', (width, height), (255, 255, 255, 0))\n drawer = ImageDraw.Draw(im)\n\n fill_color = (int(0.6*r), int(0.6*g), int(0.6*b))\n\n drawer.text((-offset[0]+stroke_width, 0), text, font=font, fill=fill_color, stroke_width=stroke_width,\n stroke_fill=stroke_color)\n\n im.show(\"text-image\")\n im.save(\"OH MY GIRL - STEP BY STEP (Line 1 - Jiho - post).png\")\n\n\nif __name__ == \"__main__\":\n # render(\"한\")\n render(\"그댄 어디쯤 걷고 있나요\", stroke_width=5)\n # render(\"j\")\n","repo_name":"PlaylistsTrance/lrc2osb","sub_path":"util/pil_render.py","file_name":"pil_render.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"69895048570","text":"import pandas as pd\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import recall_score, precision_score, accuracy_score\n\nif __name__ == \"__main__\":\n data = pd.read_csv('../data/data_clean.csv', delimiter='\\t', dtype={'email': 'string', 'label': 'int'})\n # print(data.shape)\n X_train, X_test, y_train, y_test = train_test_split(data['email'], data['label'], test_size=0.1, random_state=88)\n vectorizer = TfidfVectorizer(binary=True)\n X_train = vectorizer.fit_transform(X_train)\n X_test = vectorizer.transform(X_test)\n classifier = LogisticRegression(max_iter=1500, solver='liblinear', penalty='l1', random_state=0, C=6, verbose=1)\n classifier.fit(X_train, y_train)\n y_predicted = classifier.predict(X_test)\n precission = precision_score(y_test, y_predicted)\n recall = recall_score(y_test, y_predicted)\n accuracy = accuracy_score(y_test, y_predicted)\n print(f\"preccision score: {precission}\")\n print(f\"recall score: {recall}\")\n print(f\"accuracy score: {accuracy}\")\n","repo_name":"AdamOsiowy/klasyfikator_spamu","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"9757963589","text":"# 평행이동, 대칭이동- input: 방향별로 얼마나. output: 평행이동(방향별로 얼마나 이동-> (x,y)), 대칭이동(x축, y축, 원점, y=x 대한 대칭이동 각각 (x,y))\r\nTOF=False\r\na=False\r\n\r\ndef parallel():\r\n x_move, y_move=input(\"\\nx방향으로 이동한 정도와 y방향으로 이동할 정도를 띄어쓰기로 구분해 입력하세요.\\n----> \").split()\r\n x_move, y_move=int(x_move),int(y_move)\r\n print(\"\\n\\nx축으로\",x_move,\"만큼, y축으로\",y_move,\"만큼 평행이동한 결과:\\n(\",x+x_move,\",\",y+y_move,\")\")\r\n\r\n\r\ndef symmetric():\r\n print(\"\\n\\nx축에 대해 평행이동한 결과: (\",x,\",\",y*-1,\")\")\r\n print(\"\\ny축에 대해 평행이동한 결과: (\",x*-1,\",\",y,\")\")\r\n print(\"\\n원점에 대해 평행이동한 결과: (\",x*-1,\",\",y*-1,\")\")\r\n print(\"\\ny=x에 대해 평행이동한 결과: (\",y,\",\",x,\")\")\r\n\r\ndef run():\r\n global TOF\r\n while TOF==False:\r\n try:\r\n global x, y\r\n x,y = input(\"\\n점의 x좌표와 y좌표를 띄어쓰기로 구분해 입력하세요. 종료하려면 exit를 2번 입력해 주세요.\\n----> \").split()\r\n if x==\"exit\" and y==\"exit\":\r\n TOF=True\r\n else:\r\n x,y=int(x),int(y)\r\n\r\n choice=int(input(\"\\n대칭이동은 1, 평행이동은 2를, 종료하려면 9를 입력하세요.\\n----> \"))\r\n if choice==1:\r\n parallel()\r\n elif choice==2:\r\n symmetric()\r\n elif choice==9:\r\n TOF=True\r\n else:\r\n print(\"\\n잘못된 입력입니다.\")\r\n except :\r\n print(\"\\n잘못된 입력입니다.\")\r\n TOF=False\r\n","repo_name":"2ssunny/Py_Calculator","sub_path":"Calculator/move.py","file_name":"move.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"24220797053","text":"# -*- coding:utf-8 -*-\r\nfrom tkinter import *\r\nimport tkinter.messagebox\r\nfrom PIL import Image,ImageTk\r\nimport requests\r\nimport re\r\nimport os\r\n\r\ndef get_img():\r\n name = nameent.get()\r\n if not name:\r\n tkinter.messagebox.showinfo('警告','请输入名字再继续')\r\n return\r\n data = {\r\n 'word': name,\r\n 'sizes': '60',\r\n 'fonts': 'jfcs.ttf',\r\n 'fontcolor': '#000000'\r\n }\r\n url= 'http://www.uustv.com/'\r\n result = requests.post(url, data=data)\r\n result.encoding = 'utf-8'\r\n pattern = re.compile('
')\r\n imgurl =url + (re.findall(pattern,result.text)[0])\r\n response = requests.get(imgurl).content\r\n Root = \"F://QianPic//\"\r\n path = Root +'{}.gif'.format(name)\r\n if not os.path.exists(Root):\r\n os.mkdir(Root)\r\n if not os.path.exists(path):\r\n with open(path, 'wb') as f:\r\n f.write(response)\r\n f.close()\r\n print(\"文件保存成功\")\r\n else:\r\n print(\"文件已存在\")\r\n # with open('{}.gif'.format(name),'wb') as f:\r\n # f.write(response)\r\n # try:\r\n # im = Image.open('{}.gif'.format(name))\r\n # im.show()\r\n # im.close()\r\n # except:\r\n # print('请自己打开!')\r\n bm = ImageTk.PhotoImage(file='F://QianPic//{}.gif'.format(name))\r\n label2 = Label(root,image =bm)\r\n label2.bm = bm\r\n label2.grid(row=2,columnspan=3)\r\nroot = Tk()\r\nroot.title('python签名设计')\r\nroot.geometry('600x300')# 坐标,大小\r\nLabel(root,text=\"姓名:\",font=('微软雅黑',15)).grid()\r\nnameent = Entry(root,font=('微软雅黑',15))\r\nnameent.grid(row=0, column=1)\r\nbutton = Button(root,text='一键设计签名',font=('微软雅黑',15),width ='15',height='1',command=get_img) # 按钮控件\r\nbutton.grid(row=0,column=2)\r\nmainloop()","repo_name":"javicode-hu/PythonDemo","sub_path":"python爬虫/spider demo/qianmi.py","file_name":"qianmi.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"34470479734","text":"from django.urls import path\n\nfrom scrums.views import ScrumAPIView,MainScrumAPIView, ScrumDetailUpdateAPIView,CommentCreateAPIView,CommentUpdateDeleteAPIView\n\napp_name = 'scrums'\n\nurlpatterns = [\n path('',ScrumAPIView.as_view(),name='scrum'),\n path('main/',MainScrumAPIView.as_view(),name='main_scrum'),\n path('/',ScrumDetailUpdateAPIView.as_view(),name='detail'),\n path('comment//',CommentCreateAPIView.as_view(),name='comment'),\n path('/comment/',CommentUpdateDeleteAPIView.as_view(),name='comment_ud'),\n]\n","repo_name":"FAMILYZOA/ZOA","sub_path":"backend/scrums/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"242443715","text":"'''\nWe are trying to interact with the links and mainly simply we can get them using the By function\n\nLet's getting the No of the links, all link text, partial link text so we get hands on find_elements function too.\n\n\nanother ways to find \n(i) By.LINK_TEXT --> complete text for single element\n(ii) By.PARTIAL_LINK_TEXT --> partial text is enough for finding individual work\n'''\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport time\n\ndriver =webdriver.Chrome(executable_path=\"chromeDriver.exe\")\ndriver.get(\"https://mohitpeshwani.github.io/crazyprogrammer/\")\ntime.sleep(5)\nno_of_links = driver.find_elements(By.TAG_NAME,'a')\ntime.sleep(2)\nprint(\"No of the links available in the web page:\", len(no_of_links))\n\n#we link to go on the link no 2\nno_of_links[2].click()\n\n#printing the assosicate text with the link\nfor i in no_of_links:\n print(i.text)\n\n#element using LINK_TEXT\nprint(driver.find_element(By.LINK_TEXT,'mohitpesh23@gmail.com').is_displayed())\n\n#element using LINK_TEXT\nprint(driver.find_element(By.PARTIAL_LINK_TEXT,'mohitpesh23').is_displayed())\n\ntime.sleep(5)\ndriver.quit()\n\n","repo_name":"Logan1x/Python-Scripts","sub_path":"bin/Selenium basics with python/basics_selenium8.py","file_name":"basics_selenium8.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","stars":294,"dataset":"github-code","pt":"77"}
+{"seq_id":"10088260668","text":"from typing import cast\n\nfrom marshmallow import Schema, fields, post_load\nfrom redis import Redis\n\nfrom app import app\nfrom app.services.imdb import Movie\n\n\nclass MovieSchema(Schema):\n id = fields.Str()\n title = fields.Str()\n year = fields.Int()\n runtime = fields.Str()\n genre = fields.Str()\n rating = fields.Int()\n date_rated = fields.Date(data_key=\"dateRated\")\n\n @post_load\n def make_movie(self, data, **_kwargs):\n return Movie(**data)\n\n\nredis = Redis(\n host=app.config[\"REDIS_HOST\"],\n port=app.config[\"REDIS_PORT\"],\n db=app.config[\"REDIS_DB\"],\n)\n\n\ndef store_ratings(user_id: str, movies: set[Movie]) -> None:\n key = f\"user:{user_id}:ratings\"\n redis.delete(key)\n for movie in movies:\n movie = MovieSchema().dumps(movie)\n redis.sadd(key, cast(str, movie))\n\n\ndef retrieve_ratings(user_id: str) -> set[Movie]:\n key = f\"user:{user_id}:ratings\"\n if not redis.exists(key):\n raise KeyError(\"No ratings exist for that user.\")\n movies = redis.smembers(key)\n movies = {MovieSchema().loads(cast(str, m)) for m in movies}\n return cast(set[Movie], movies)\n","repo_name":"deMenschRutger/IMDbPy","sub_path":"app/services/redis.py","file_name":"redis.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"7013380797","text":"from django.urls import path\n\nfrom . import views\n\napp_name = 'users'\n\nurlpatterns = [\n path('register/', views.RegistrationView.as_view(), name='register'),\n path('login/', views.LoginView.as_view(), name='login'),\n path('logout/', views.LogoutView.as_view(), name='logout'),\n path('search/', views.SearchUsersView.as_view(), name='search'),\n path('profile//', views.UserProfileView.as_view(), name='profile')\n]\n","repo_name":"badgersky/social-media-app","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"24137084208","text":"lister = []\ncount_elements = int(input(\"Введите количество элементов в списке >> \"))\n\nfor i in range(0, count_elements):\n elem = int(input(f\"Введите {i + 1}-й элемент >> \"))\n lister.append(elem)\n\nprint(\"list before \" + str(lister))\nfor i in range(0, len(lister) - 1, 2):\n if i + 1 <= len(lister) - 1:\n lister[i], lister[i + 1] = lister[i + 1], lister[i]\nprint(\"list after \" + str(lister))\n","repo_name":"MisterHat-89/geekBrainsPython","sub_path":"lesson_2/exam_2.py","file_name":"exam_2.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"37179869316","text":"import os\nimport win32com.client\n# pip install pywin32\n\nclass DesignFile():\n def __init__(self, name):\n self.name = name\n self.wdApp = win32com.client.gencache.EnsureDispatch('Word.Application')\n self.doc = self.wdApp.Documents.Open(os.path.join(os.getcwd(), \"模板.docx\"))\n self.wdApp.Selection.Find.ClearFormatting()\n self.wdApp.Selection.Find.Replacement.ClearFormatting()\n\n def process_word(self):\n # 替换文字\n self.wdApp.Selection.Find.Execute(\n FindText=\"某某\", MatchCase=False, MatchWholeWord=False,MatchWildcards=False,MatchSoundsLike=False,\n MatchAllWordForms=False, Forward=True, Wrap=1,Format=True,ReplaceWith=self.name, Replace=2)\n\n # 插入拓扑图,需要在word相应位置插入标签“AddImage”\n RangeImage = self.wdApp.ActiveDocument.Bookmarks(\"AddImage\").Range\n self.wdApp.Selection.InlineShapes.AddPicture(FileName=os.path.join(os.getcwd(), \"模板.jpg\"), LinkToFile=False, SaveWithDocument=True, Range=RangeImage)\n\n # 替换页眉\n # self.wdApp.ActiveDocument.Sections(3).Headers(win32com.client.constants.wdHeaderFooterPrimary).Range.Find.ClearFormatting()\n # self.wdApp.ActiveDocument.Sections(3).Headers(win32com.client.constants.wdHeaderFooterPrimary).Range.Find.Replacement.ClearFormatting()\n # self.wdApp.ActiveDocument.Sections(3).Headers(win32com.client.constants.wdHeaderFooterPrimary).Range.Find.Execute(\"页眉\", 0, 0, 0, 0, 0, 1, 1, 1, \"\", 2)\n\n # 另存为doc和pdf\n print(self.name)\n self.doc.SaveAs(os.path.join(os.getcwd(), f\"{self.name}.docx\"))\n # self.doc.ExportAsFixedFormat(os.path.join(os.getcwd(), f\"{self.name}.pdf\"), win32com.client.constants.wdExportFormatPDF,\n # Item=win32com.client.constants.wdExportDocumentWithMarkup,\n # CreateBookmarks=win32com.client.constants.wdExportCreateHeadingBookmarks)\n self.wdApp.Quit()\n\n def start_func(self):\n self.process_word()\n\n\ndef process_excel():\n EachFileList = []\n xlApp = win32com.client.Dispatch('Excel.Application')\n # 选择excel文件,选中sheet\n xlBook = xlApp.Workbooks.Open(os.path.join(os.getcwd(), \"模板.xlsx\"))\n xlSheet = xlBook.Worksheets(\"模板\")\n # 获取当前sheet下有效的行数(-1是排除了第一行表头)\n Num = xlSheet.usedrange.rows.count - 1\n print(\"本次共有\", Num, \"个文件处理:\\n\")\n for i in range(Num):\n EachFileDict = {}\n EachFileDict[\"姓名\"] = xlSheet.Cells(i + 2, 1).Value\n # 若需要在表格赋值:\n # xlSheet.Cells(i + 2, 2).Value = \"处理\"\n EachFileList.append(EachFileDict)\n\n # 若需要保存及输出PDF\n # xlBook.SaveAs(f\"模板.xlsx\")\n # xlBook.Worksheets(['模板']).Select()\n # xlApp.ActiveSheet.ExportAsFixedFormat(0,f\"表格.pdf\")\n xlApp.Quit()\n return EachFileList\n\n\nif __name__ == '__main__':\n pe_res = process_excel()\n for each in pe_res:\n df = DesignFile(each[\"姓名\"])\n df.start_func()\n","repo_name":"MrYuGoui/letmepy","sub_path":"office/office_process.py","file_name":"office_process.py","file_ext":"py","file_size_in_byte":3095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"24442084525","text":"import discord\n\n# This is a dictionary of all the defcon settings. You can add more defcon levels (if premium)\nDEFCON_SETTINGS = {\n 1: {\n \"name\": \"DEFCON 1\",\n \"description\": \"Maximum readiness. Server lockdown. Includes all settings from DEFCON 2\",\n \"color\": discord.Color.red(),\n \"SETTINGS\": {\n \"ALLOW_INVITE_CREATE\": False,\n \"ALLOW_SERVER_JOIN\": False,\n \"HIDE_CHANNELS\": True,\n \"LOCK_VOICE_CHANNELS\": True,\n \"LOCK_TEXT_CHANNELS\": True,\n \"LOCK_ASSIGN_ROLES\": True,\n \"ALLOW_CREATE_ROLE\": False,\n },\n },\n 2: {\n \"name\": \"DEFCON 2\",\n \"description\": \"Lockdown. No one can join server. All channels will remain visible, no moderator can assign roles, no one can create roles\",\n \"color\": discord.Color.orange(),\n \"SETTINGS\": {\n \"ALLOW_INVITE_CREATE\": False,\n \"ALLOW_SERVER_JOIN\": False,\n \"HIDE_CHANNELS\": False,\n \"LOCK_VOICE_CHANNELS\": True,\n \"LOCK_TEXT_CHANNELS\": True,\n \"LOCK_ASSIGN_ROLES\": True,\n \"ALLOW_CREATE_ROLE\": False,\n },\n },\n 3: {\n \"name\": \"DEFCON 3\",\n \"description\": \"Strict slowmode. Not allowing sending discord invites, images, gif(s), excess emotes. All channels will remain visible, but lock voice channels\",\n \"color\": discord.Color.gold(),\n \"SETTINGS\": {\n \"ALLOW_INVITE_CREATE\": True,\n \"ALLOW_SERVER_JOIN\": True,\n \"HIDE_CHANNELS\": False,\n \"LOCK_VOICE_CHANNELS\": True,\n \"LOCK_TEXT_CHANNELS\": False,\n \"LOCK_ASSIGN_ROLES\": False,\n \"SLOWMODE\": True,\n \"SLOWMODE_TIME\": 10,\n },\n },\n 4: {\n \"name\": \"DEFCON 4\",\n \"description\": \"Moderate slowmode. No one can join server, not allowing sending discord invites. All channels will remain visible\",\n \"color\": discord.Color.green(),\n \"SETTINGS\": {\n \"ALLOW_INVITE_CREATE\": True,\n \"ALLOW_SERVER_JOIN\": True,\n \"HIDE_CHANNELS\": False,\n \"LOCK_VOICE_CHANNELS\": False,\n \"LOCK_TEXT_CHANNELS\": False,\n \"LOCK_ASSIGN_ROLES\": False,\n \"SLOWMODE\": True,\n \"SLOWMODE_TIME\": 3,\n },\n },\n 5: {\n \"name\": \"DEFCON 5\",\n \"description\": \"No slowmode. No one can join server, not allowing sending discord invites. All channels will remain visible. Peaceful mode\",\n \"color\": discord.Color.blue(),\n \"SETTINGS\": {\n \"ALLOW_INVITE_CREATE\": True,\n \"ALLOW_SERVER_JOIN\": True,\n \"HIDE_CHANNELS\": False,\n \"LOCK_VOICE_CHANNELS\": False,\n \"LOCK_TEXT_CHANNELS\": False,\n \"LOCK_ASSIGN_ROLES\": False,\n \"SLOWMODE\": False,\n \"SLOWMODE_TIME\": 0,\n },\n },\n}\n\n\n# Actions\n\nACTION_SETTINGS = {\n \"ALLOW_INVITE_CREATE\": {\n \"name\": \"Allow Invite Creation\",\n \"description\": \"Allow users to create discord invites\",\n \"default\": True,\n },\n \"ALLOW_CREATE_ROLE\": {\n \"name\": \"Allow Create Role\",\n \"description\": \"Allow users to create roles\",\n \"default\": True,\n },\n \"ALLOW_SERVER_JOIN\": {\n \"name\": \"Allow Server Join\",\n \"description\": \"Allow users to join the server\",\n \"default\": True,\n },\n \"HIDE_CHANNELS\": {\n \"name\": \"Hide Channels\",\n \"description\": \"Hide all channels from users\",\n \"default\": False,\n },\n \"LOCK_VOICE_CHANNELS\": {\n \"name\": \"Lock Voice Channels\",\n \"description\": \"Lock all voice channels from users\",\n \"default\": False,\n },\n \"LOCK_TEXT_CHANNELS\": {\n \"name\": \"Lock Text Channels\",\n \"description\": \"Lock all text channels from users\",\n \"default\": False,\n },\n \"LOCK_ASSIGN_ROLES\": {\n \"name\": \"Lock Assign Roles\",\n \"description\": \"Lock all roles from users\",\n \"default\": False,\n },\n \"SLOWMODE\": {\n \"name\": \"Slowmode\",\n \"description\": \"Enable slowmode\",\n \"default\": False,\n },\n \"SLOWMODE_TIME\": {\n \"name\": \"Slowmode Time\",\n \"description\": \"Slowmode time in seconds\",\n \"default\": 0,\n },\n}\n\nDEFAULT_TRUSTABLES = {\n \"roles\": [],\n \"members\": [],\n \"members_with_admin\": True,\n \"members_above_bot_role\": False,\n}\n","repo_name":"rtk-rnjn/Parrot","sub_path":"cogs/defcon/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4386,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"77"}
+{"seq_id":"31976260735","text":"from openerp import models, api\n\n\nclass StockPickingAssignMulti(models.TransientModel):\n _name = 'stock.picking.assign.multi'\n\n @api.multi\n def assign(self):\n self.ensure_one()\n picking_ids = self._context.get('active_ids', False)\n pickings = self.env['stock.picking'].browse(picking_ids)\n pickings = pickings.filtered(\n lambda r: r.state in ['partially_available', 'confirmed'])\n pickings.action_assign()\n return {'type': 'ir.actions.act_window_close'}\n","repo_name":"Comunitea/CMNT_00040_2016_ELN_addons","sub_path":"eln_stock/wizard/stock_picking_assign_multi.py","file_name":"stock_picking_assign_multi.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"40422785369","text":"# coding=utf-8\nfrom PyQt4 import QtCore\nfrom PyQt4 import QtGui\nfrom PyQt4 import QtSvg\nfrom DentalFormula import TOOTH_SIZE, ToothSchemaDelegate\n\n\ndef gen_tooth_svg(tooth, size=TOOTH_SIZE):\n r = QtCore.QRect(0, 0, size, size)\n out = QtCore.QByteArray()\n buf = QtCore.QBuffer(out)\n\n gen = QtSvg.QSvgGenerator()\n gen.setSize(QtCore.QSize(size, size))\n gen.setViewBox(QtCore.QRect(-1, -1, size + 2, size + 2))\n gen.setOutputDevice(buf)\n painter = QtGui.QPainter()\n painter.begin(gen)\n painter.setBrush(QtGui.QBrush(QtCore.Qt.white))\n\n sections = tooth.sections\n painter.setRenderHint(QtGui.QPainter.Antialiasing)\n painter.setPen(QtGui.QPen(QtCore.Qt.black))\n painter.setFont(ToothSchemaDelegate.get_font(float(size) / TOOTH_SIZE))\n\n x, y, w, h = r.x(), r.y(), r.width(), r.height()\n\n if sections.FULL:\n painter.setFont(ToothSchemaDelegate.get_large_font(float(size) / TOOTH_SIZE))\n painter.drawEllipse(r)\n painter.drawText(r, QtCore.Qt.AlignCenter, '\\n'.join((state.code for state in sections.FULL)))\n painter.end()\n return unicode(out)\n\n painter.drawPie(r, 45 * 16, 90 * 16) # U\n painter.drawPie(r, 135 * 16, 90 * 16) # L\n painter.drawPie(r, 225 * 16, 90 * 16) # D\n painter.drawPie(r, 315 * 16, 90 * 16) # R\n\n if not tooth.is_simplified():\n r = QtCore.QRect(x + w / 4, y + h / 4, w / 2, h / 2)\n painter.drawPie(r, 90 * 16, 180 * 16) # CL\n painter.drawPie(r, 270 * 16, 180 * 16) # CR\n\n painter.drawText(\n QtCore.QRect(x, y, w / 4, h),\n QtCore.Qt.AlignCenter,\n '\\n'.join((state.code for state in sections.L))\n )\n painter.drawText(\n QtCore.QRect(x, y, w, h / 4),\n QtCore.Qt.AlignCenter,\n ' '.join((state.code for state in sections.U))\n )\n painter.drawText(\n QtCore.QRect(x + w * 3 / 4, y, w / 4, h),\n QtCore.Qt.AlignCenter,\n '\\n'.join((state.code for state in sections.R))\n )\n painter.drawText(\n QtCore.QRect(x, y + h * 3 / 4, w, h / 4),\n QtCore.Qt.AlignCenter,\n ' '.join((state.code for state in sections.D))\n )\n painter.drawText(\n QtCore.QRect(x + w / 4, y, w / 4, h),\n QtCore.Qt.AlignCenter,\n '\\n'.join((state.code for state in sections.CL))\n )\n painter.drawText(\n QtCore.QRect(x + w * 2 / 4, y, w / 4, h),\n QtCore.Qt.AlignCenter,\n '\\n'.join((state.code for state in sections.CR))\n )\n else:\n painter.drawText(\n QtCore.QRect(x, y, w / 2, h),\n QtCore.Qt.AlignCenter,\n '\\n'.join((state.code for state in sections.L))\n )\n painter.drawText(\n QtCore.QRect(x, y, w, h / 2),\n QtCore.Qt.AlignCenter,\n ' '.join((state.code for state in sections.U))\n )\n painter.drawText(\n QtCore.QRect(x + w / 2, y, w / 2, h),\n QtCore.Qt.AlignCenter,\n '\\n'.join((state.code for state in sections.R))\n )\n painter.drawText(\n QtCore.QRect(x, y + h / 2, w, h / 2),\n QtCore.Qt.AlignCenter,\n ' '.join((state.code for state in sections.D))\n )\n painter.end()\n return unicode(out)\n\n\ndef gen_tooth_col(tooth, model, size=TOOTH_SIZE):\n svg = gen_tooth_svg(tooth, size)\n status_obj = model.statuses[tooth.status] if tooth.status else None\n\n return [\n u'''%s ''' % (status_obj.color if status_obj else '#fff',\n status_obj.name if status_obj else '---'),\n u'''%s ''' % tooth.mobility or u'---',\n u''' ''' % svg,\n u'''%s ''' % tooth.get_number()\n ]\n\n\ndef formula_printer(model):\n def print_formula(size):\n \"\"\" :type model: DentalFormulaModel \"\"\"\n tbl = [\n [u'Статус '],\n [u'Подвижность '],\n [u'Состояние '],\n [u'Номер '],\n [u'Номер '],\n [u'Состояние '],\n [u'Подвижность '],\n [u'Статус ']\n ]\n max_number = 5 if model.is_deciduous else 8\n for number in xrange(10+max_number, 10, -1):\n tooth = model.items[number]\n tooth_col = gen_tooth_col(tooth, model, size)\n tbl[0] += [tooth_col[0]]\n tbl[1] += [tooth_col[1]]\n tbl[2] += [tooth_col[2]]\n tbl[3] += [tooth_col[3]]\n for number in xrange(21, 21+max_number):\n tooth = model.items[number]\n tooth_col = gen_tooth_col(tooth, model, size)\n tbl[0] += [tooth_col[0]]\n tbl[1] += [tooth_col[1]]\n tbl[2] += [tooth_col[2]]\n tbl[3] += [tooth_col[3]]\n for number in xrange(30+max_number, 30, -1):\n tooth = model.items[number]\n tooth_col = gen_tooth_col(tooth, model, size)\n tbl[4] += [tooth_col[3]]\n tbl[5] += [tooth_col[2]]\n tbl[6] += [tooth_col[1]]\n tbl[7] += [tooth_col[0]]\n for number in xrange(41, 41+max_number):\n tooth = model.items[number]\n tooth_col = gen_tooth_col(tooth, model, size)\n tbl[4] += [tooth_col[3]]\n tbl[5] += [tooth_col[2]]\n tbl[6] += [tooth_col[1]]\n tbl[7] += [tooth_col[0]]\n return (u'' %\n u'\\n'.join([u'%s ' % u'\\n'.join(row) for row in tbl]))\n return print_formula\n","repo_name":"dio4/vista_1","sub_path":"Forms/F043v2/DentalFormulaPrint.py","file_name":"DentalFormulaPrint.py","file_ext":"py","file_size_in_byte":5836,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"18224364613","text":"# Meduim\n# https://leetcode.com/problems/utf-8-validation/\n\nfrom typing import List\nfrom re import compile\n\n'''\nRuntime: 227 ms, faster than 29.97% of Python3 online submissions for UTF-8 Validation.\nMemory Usage: 14.9 MB, less than 15.94% of Python3 online submissions for UTF-8 Validation.\n'''\nclass Solution:\n def validUtf8(self, data: List[int]) -> bool:\n stringifiedBytes = [bin(byte)[2:].zfill(8) for byte in data]\n byteSize = len(data)\n idx = 0\n\n bytePatterns = [compile('0[0-1]{7}'), compile('110[0-1]{4}'), compile('1110[0-1]{3}'), compile('11110[0-1]{2}')]\n followingBytePattern = compile('10[0-1]{6}')\n\n while idx < byteSize:\n matched = False\n for patternNo, pattern in enumerate(bytePatterns):\n if pattern.match(stringifiedBytes[idx]) is None: continue\n\n if patternNo == 0:\n matched = True\n break\n\n if idx + patternNo >= byteSize: return False\n\n for j in range(1, patternNo + 1):\n nextByte = stringifiedBytes[idx + j]\n if followingBytePattern.match(nextByte) is None:\n return False\n\n matched = True\n idx += patternNo\n\n if not matched: return False\n idx += 1\n\n return True\n\n\nsolution = Solution()\nprint(solution.validUtf8([197,130,1])) # True\nprint(solution.validUtf8([235,140,4])) # False\nprint(solution.validUtf8([240,162,138,147])) # True\nprint(solution.validUtf8([39,89,227,83,132,95,10,0])) # False\nprint(solution.validUtf8([10])) # True\n","repo_name":"okyungjin/ALGORITHM","sub_path":"LeetCode/393_UTF-8_Validation.py","file_name":"393_UTF-8_Validation.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"13131766899","text":"import httplib2\n\nfrom apiclient.discovery import build\nfrom oauth2client.client import SignedJwtAssertionCredentials\n\nfrom drivesite.config import config\n\nclass DriveAgent(object):\n\n @staticmethod\n def get_build():\n f = file(config['drive_key_path'], 'rb')\n key = f.read()\n f.close()\n credentials = SignedJwtAssertionCredentials(config['drive_email'], key,\n scope='https://www.googleapis.com/auth/drive')\n http = httplib2.Http()\n http = credentials.authorize(http)\n return build('drive', 'v2', http=http)\n\n\n\n","repo_name":"linuxlewis/drivesite","sub_path":"drivesite/drive.py","file_name":"drive.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"33322578718","text":"def show_menu():\n\n #This function prints the menu at the starting of the program, just as it is executed.\n #This enables the customer to go through the item codes and costs, to make a decision as to what to buy.\n #No calculations and no return value in this function.\n \n print(\"\"\"=================================================\n MY BAZAAR\n=================================================\nHello! Welcome to my grocery store!\nFollowing are the products available in the shop:\n\n-------------------------------------------------\nCODE | DESCRIPTION | CATEGORY | COST (Rs)\n-------------------------------------------------\n 0 | Tshirt | Apparels | 500\n 1 | Trousers | Apparels | 600\n 2 | Scarf | Apparels | 250\n 3 | Smartphone | Electronics | 20,000\n 4 | iPad | Electronics | 30,000\n 5 | Laptop | Electronics | 50,000\n 6 | Eggs | Eatables | 5\n 7 | Chocolate | Eatables | 10\n 8 | Juice | Eatables | 100\n 9 | Milk | Eatables | 45\n------------------------------------------------\n\"\"\")\n\n\n\n\n\n\n \ndef get_regular_input():\n\n #This function obtains the regular input as entered by the customer.\n #A list of length 10, and respective quantity values is returned.\n \n print(\"\"\"\n\n-------------------------------------------------\nENTER ITEMS YOU WISH TO BUY\n-------------------------------------------------\"\"\")\n\n regular_items = input(\"Enter the item codes (space-seperated): \") #The input is obtained as a string, with space seperated entries.\n l = regular_items.split()\n \n #The .split() method seperates all the items of the .\n #It does this by deleting all the entries of the and stores rests of the substrings in the form of an ordered list.\n #The entries in the string are of the type .\n \n quant = [0]*10\n\n #A list of length 10 and values <0> is created.\n #This is the list that will be returned by the function.\n \n for i in range(len(l)):\n\n #Runs the loop as many times as the length of the list .\n \n if int(l[i]) not in range(10):\n print(\"\\n\",l[i], \" is not a valid entry in this list. It will not be considered.\", sep = \"\")\n\n #Checks for invalid inputs.\n #Only accepts input if it is an integer entry between 0 and 9 (inclusive).\n \n else:\n quant[int(l[i])] += 1\n\n #Increment of 's index by 1 with respect to its index as entered by the customer.\n \n return quant\n\n\n\n\n\n\n\ndef get_bulk_input():\n\n #This function obtains bulk input from the customer.\n #A list of length 10, and respective quantity values is returned.\n \n print(\"\"\"\n-------------------------------------------------\nENTER ITEM AND QUANTITIES\n-------------------------------------------------\"\"\")\n \n l = [\"Tshirt\",\"Trousers\",\"Scarf\",\"Smartphone\",\"iPad\",\"Laptop\",\"Eggs\",\"Chocolate\",\"Juice\",\"Milk\"]\n\n #A list of item descriptions sorted on the basis of code indexes.\n \n quant = [0]*10\n\n #A list of length 10 and values <0> is created.\n #This is the list that will be returned by the function.\n \n while True:\n\n #Will run the loop till the command is used to exit it.\n \n inp = input(\"Enter code and quantity (leave blank to stop): \")\n\n #Inputs the code and quantity from the customer.\n\n if inp == \"\":\n\n #Breaks from the loop if the string entered is empty.\n \n print(\"Your order has been finalized.\")\n \n break\n \n \n \n inp = inp.split(\" \")\n\n #Splits the string on the basis of and stores it in a list.\n #The indexing of the string is done sequentially as done in the original string.\n #The values of the list are of type .\n \n\n if len(inp) != 2:\n \n print(\"Invalid input. Try again.\\n\")\n\n #Can only have 2 entries in the list.\n\n elif inp[0] == \"\" and inp[1] == \"\":\n \n print(\"Invalid input. Try again.\\n\")\n\n #Negates a corner case when a single space is entered as input.\n\n elif int(inp[0]) in range(10) and int(inp[1]) >= 0:\n \n quant[int(inp[0])] += int(inp[1])\n print(\"You added\",int(inp[1]),l[int(inp[0])],\"\\n\")\n\n #If the entered code and quantity are errorless, they are entered (with the particular index) to the list .\n #A conformational line is printed alongside.\n\n elif int(inp[0]) not in range(10) and int(inp[1]) < 0:\n\n print(\"Invalid code and quantity. Try again.\\n\")\n\n #Invalid code and quantity.\n\n elif int(inp[1]) < 0:\n\n print(\"Invalid quantity. Try again.\\n\")\n\n #Invalid quantity.\n\n elif int(inp[0]) not in range(10):\n\n print(\"Invalid code. Try again.\\n\")\n\n #Invalid code.\n \n\n return quant\n \n\n \n\n\n\n\ndef print_order_details(quantities):\n\n #This function prints the order details.\n #No value is returned in this function.\n \n print(\"\"\"\n\n-------------------------------------------------\nORDER DETAILS\n-------------------------------------------------\"\"\")\n \n c = 0\n l = [\"Tshirt\",\"Trousers\",\"Scarf\",\"Smartphone\",\"iPad\",\"Laptop\",\"Eggs\",\"Chocolate\",\"Juice\",\"Milk\"]\n\n #A counter for the serial number is used.\n #A list corresponding to item descriptions and item code is entered.\n #l[- ] =
- \n \n costs = [500,600,250,20000,30000,50000,5,10,100,45]\n\n #Costs of the items, ordered by the item codes.\n #costs[
- ] =
- \n \n for i in range(10):\n\n #A loop runs 10 times (the number of items).\n \n if quantities[i] != 0:\n\n #Checks for each entry of the list, whether it is <0> or not.\n \n c += 1\n\n #Increments the counter by 1.\n \n print(\"[\",c,\"] \",l[i],\" x \",quantities[i],\" = Rs \",costs[i],\" * \",quantities[i],\" = Rs \",quantities[i]*costs[i],sep = \"\")\n\n #Prints the required line for a particular order item.\n\n\n\n\n\n\n\ndef calculate_category_wise_cost(quantities):\n\n #This function calculates the cost of products segregated by category.\n #It returns a tuple, with costs of each category.\n #Its parameter is the list with all the order entries.\n \n print(\"\"\"\n\n-------------------------------------------------\nCATEGORY-WISE COST\n-------------------------------------------------\"\"\")\n \n costs = [500,600,250,20000,30000,50000,5,10,100,45]\n \n #List of costs of each item, based on index = item_code.\n \n apparels_cost = 0\n electronics_cost = 0\n eatables_cost = 0\n\n #Initializing variables with value <0>.\n \n for i in range(10):\n\n #Runs loop 10 times (The number of items).\n \n if i in [0,1,2]:\n \n apparels_cost += quantities[i]*costs[i]\n\n #Checks for apparels and adds cost to variable.\n \n if i == 2:\n \n print(\"Apparels = Rs\",apparels_cost)\n\n #Prints apparels cost only when last entry of apparels is running in the loop.\n \n elif i in [3,4,5]:\n \n electronics_cost += quantities[i]*costs[i]\n\n #Checks for electronics and adds cost to variable.\n \n if i == 5:\n \n print(\"Electronics = Rs\",electronics_cost)\n\n #Prints electronics cost only when last entry of electronics is running in the loop.\n \n else:\n \n eatables_cost += quantities[i]*costs[i]\n\n #Checks for eatables and adds cost to variable.\n \n if i == 9:\n \n print(\"Eatables = Rs\",eatables_cost)\n\n #Prints eatables cost only when last entry of eatables is running in the loop.\n\n \n return (apparels_cost,electronics_cost,eatables_cost)\n \n\n\n\n\n\ndef get_discount(cost, discount_rate):\n\n #This helper function returns the discount value, based on the parameters of cost and discount rate entered.\n \n return int(cost*discount_rate)\n\n\n\n\n\n\ndef calculate_discounted_prices(apparels_cost, electronics_cost, eatables_cost):\n\n #This function calculates the discounted prices based on the category of the item bought.\n #The parameters entered are the respective category-wise costs calculated earlier in the program.\n #The function returns a tuple of category-wise after discount prices.\n \n print(\"\"\"\n\n-------------------------------------------------\nDISCOUNTS\n-------------------------------------------------\"\"\")\n \n app = 0\n ele = 0\n eat = 0\n\n #Category-wise discounted amounts, initialized to <0>.\n \n if apparels_cost >= 2000 and apparels_cost != 0:\n\n #Checks for discount conditions.\n \n print(\"[APPAREL] Rs \",apparels_cost,\" - Rs \",sep = \"\",end = \"\")\n \n app = get_discount(apparels_cost,0.1)\n\n #Calculates the discounted amount for this category.\n \n apparels_cost -= app\n\n #Reduces the category cost by the discounted amount, by calling the helper function.\n \n print(app,\" = Rs \",apparels_cost,sep = \"\")\n \n \n \n if electronics_cost >= 25000 and electronics_cost != 0:\n\n #Checks for discount conditions.\n\n print(\"[ELECTRONICS] Rs \",electronics_cost,\" - Rs \",sep = \"\",end = \"\")\n \n ele = get_discount(electronics_cost,0.1)\n\n #Calculates the discounted amount for this category, by calling the helper function.\n \n electronics_cost -= ele\n\n #Reduces the category cost by the discounted amount, by calling the helper function.\n\n print(ele,\" = Rs \",electronics_cost,sep = \"\")\n\n \n \n if eatables_cost >= 500 and eatables_cost != 0:\n\n #Checks for discount conditions.\n\n print(\"[EATABLES] Rs \",eatables_cost,\" - Rs \",sep = \"\",end = \"\")\n \n eat = get_discount(eatables_cost,0.1)\n\n #Calculates the discounted amount for this category, by calling the helper function.\n \n eatables_cost -= eat\n\n #Reduces the category cost by the discounted amount, by calling the helper function.\n \n print(eat,\" = Rs \",eatables_cost,sep = \"\")\n\n \n\n print()\n\n #Prints an empty line.\n \n print(\"TOTAL DISCOUNT = Rs \",app+ele+eat,\"\\nTOTAL COST = Rs \", apparels_cost+electronics_cost+eatables_cost, sep = \"\")\n \n return (apparels_cost, electronics_cost, eatables_cost)\n \n \n\n\n \n\ndef get_tax(cost, tax):\n\n #This helper function returns the tax value, based on the parameters of cost and tax rate entered.\n \n return int(cost*tax)\n\n\n\n\n\ndef calculate_tax(apparels_cost, electronics_cost, eatables_cost):\n\n #This function calculates the tax based on which catergory the item belongs to.\n #The parameters are the category-wise costs, after discounts.\n #The function returns the values of total_cost_after_tax and total_taxed_amount.\n \n print(\"\"\"\n\n-------------------------------------------------\nTAX\n-------------------------------------------------\"\"\")\n \n app = 0\n ele = 0\n eat = 0\n\n #Initializing empty variables, for the tax amounts of each category.\n \n if apparels_cost != 0:\n\n #Checks if category cost is not <0>.\n \n print(\"[APPAREL] Rs \",apparels_cost,\" * 0.10 = Rs \",sep = \"\",end = \"\")\n \n app = get_tax(apparels_cost,0.1)\n\n #Calls helper function and calculates the taxed value based on category tax rate.\n \n apparels_cost += app\n\n #Adds taxed amount to the cost of category.\n \n print(app)\n\n \n \n if electronics_cost != 0:\n\n #Checks if category cost is not <0>.\n \n print(\"[ELECTRONICS] Rs \",electronics_cost,\" * 0.15 = Rs \",sep = \"\",end = \"\")\n \n ele = get_tax(electronics_cost,0.15)\n\n #Calls helper function and calculates the taxed value based on category tax rate.\n \n electronics_cost += ele\n\n #Adds taxed amount to the cost of category.\n\n print(ele)\n\n \n \n if eatables_cost != 0:\n\n #Checks if category cost is not <0>.\n\n print(\"[EATABLES] Rs \",eatables_cost,\" * 0.05 = Rs \",sep = \"\",end = \"\")\n \n eat = get_tax(eatables_cost,0.05)\n\n #Calls helper function and calculates the taxed value based on category tax rate.\n \n eatables_cost += eat\n\n #Adds taxed amount to the cost of category.\n \n print(eat)\n\n \n\n print()\n\n #Prints an empty line.\n \n print(\"TOTAL TAX = Rs \",app+ele+eat,\"\\nTOTAL COST = Rs \", apparels_cost+electronics_cost+eatables_cost, sep = \"\")\n \n return (apparels_cost+electronics_cost+eatables_cost, app+ele+eat)\n\n\n\n\n\ndef apply_coupon_code(total_cost):\n\n #This function checks if a coupon code can be applied.\n #The parameter is the total cost after tax and discount.\n #The fucntion returns cost_after_coupon_code_applied and the price_saved because of the coupon code.\n \n print(\"\"\"\n\n-------------------------------------------------\nCOUPON CODE\n-------------------------------------------------\"\"\")\n \n saved_price = 0\n\n #Initialize an empty variable.\n \n while True:\n\n #Runs the loop until the
command is used.\n \n code = input(\"Enter coupon code (else leave blank): \")\n\n #Inputs the coupon code (case sensitive).\n \n if code == \"\":\n\n #Checks if the entered string is empty.\n \n print(\"No coupon code applied.\\n\")\n \n break\n \n \n elif code == \"HELLE25\" and total_cost >= 25000:\n\n #Checks if code is entered correctly, and the conditions of the coupon code are met.\n \n print(\"[HELLE25] min(5000, Rs \",total_cost,\" * 0.25) = Rs \",min(5000,int(total_cost*0.25)),\"\\n\", sep = \"\")\n \n saved_price = min(5000,int(total_cost*0.25))\n\n #Calculates the saved_price, that is the minimum of both the conditions.\n \n total_cost -= saved_price\n\n #Reduces value from the saved price.\n \n break\n \n \n elif code == \"CHILL50\" and total_cost >= 50000:\n\n #Checks if code is entered correctly, and the conditions of the coupon code are met.\n \n print(\"[CHILL50] min(10000, Rs \",total_cost,\" * 0.50) = Rs \",min(10000,int(total_cost*0.50)),\"\\n\", sep = \"\")\n \n saved_price = min(10000,int(total_cost*0.50))\n\n #Calculates the saved_price, that is the minimum of both the conditions.\n \n total_cost -= saved_price\n\n #Reduces value from the saved price.\n \n break\n \n \n else:\n \n print(\"Invalid coupon code. Try again.\\n\")\n\n #If none of the conditions are satisfied, the input is taken again and again, from the customer.\n\n \n print(\"TOTAL COUPON DISCOUNT = Rs\", saved_price, \"\\nTOTAL COST = Rs\", total_cost)\n \n return (total_cost,saved_price) \n\n\n\n\ndef main():\n\n #This is the main function.\n #All the functions used in the program are called from this function.\n #The order and cohesion of the program is decided from this function.\n\n show_menu()\n \n while True:\n\n #Takes input for regular/bulk order.\n #Repeats loop till correct values entered by the customer.\n\n yesno = input(\"Would you like to buy in bulk? (y or Y / n or N): \")\n\n if yesno == \"y\" or yesno == \"Y\":\n\n #For a particular input, a particular function is called.\n #Thus, the flow of the program continues.\n \n get_input = get_bulk_input()\n \n break\n\n \n elif yesno == \"n\" or yesno == \"N\":\n\n #For a particular input, a particular function is called.\n #Thus, the flow of the program continues.\n \n get_input = get_regular_input()\n \n break\n\n \n else:\n \n print(\"Invalid input. Try again.\\n\")\n\n #If a correct input is not entered, the loop will keep running.\n\n print_order_details(get_input)\n \n apply_coupon_code(calculate_tax(*calculate_discounted_prices(*calculate_category_wise_cost(get_input)))[0])\n\n #Various functions are called depending on returned values of the functions.\n \n\n print(\"\\nThank you for visiting!\\n\")\n\n #The end of the program.\n\n\n\n \n\nif __name__ == '__main__':\n \n main()\n\n #The function is called in the primary iteration of the program\n","repo_name":"nin-ran-jan/IP-Assignments","sub_path":"IP_Assignment_1/a1.py","file_name":"a1.py","file_ext":"py","file_size_in_byte":17051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"34717031681","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n# Dependencies and Setup\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\n# Hide warning messages in notebook\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# File to Load (Remember to Change These)\nmouse_drug_data_to_load = \"02-Homework_05-Matplotlib_Instructions_Pymaceuticals_data_mouse_drug_data.csv\"\nclinical_trial_data_to_load = \"02-Homework_05-Matplotlib_Instructions_Pymaceuticals_data_clinicaltrial_data.csv\"\n\n# Read the Mouse and Drug Data and the Clinical Trial Data\ndrug_data = pd.read_csv(mouse_drug_data_to_load)\nclinical_data = pd.read_csv(clinical_trial_data_to_load)\n\n# Combine the data into a single dataset\ndata_combine = pd.merge(drug_data, clinical_data, on=\"Mouse ID\", how=\"outer\")\n\n\n# Display the data table for preview\ndata_combine.head()\n\n\n# In[3]:\n\n\n#Analysis of Tumor treatment results\n\n# Store the Mean Tumor Volume Data Grouped by Drug and Timepoint \ndrug_mean_tumor_vol = data_combine[[\"Drug\", \"Timepoint\",\"Tumor Volume (mm3)\"]]\ndrug_mean_tumor_vol_grouped = drug_mean_tumor_vol.groupby(['Drug', 'Timepoint'])\n\n# Convert to DataFrame\ntumorvol = pd.DataFrame(drug_mean_tumor_vol_grouped[\"Tumor Volume (mm3)\"].agg(np.mean))\n\n# Preview DataFrame\ntumorvol_indexed = tumorvol.reset_index()\ntumorvol_indexed.head(100)\n\n\n# In[4]:\n\n\n# Store the Standard Error of Tumor Volumes Grouped by Drug and Timepoint\ntumorvol = data_combine.groupby(['Drug', 'Timepoint']).sem()\n\n# Convert to DataFrame\ntumorvol_pd = pd.DataFrame(tumorvol[[\"Tumor Volume (mm3)\"]])\n\n# Preview DataFrame\ntumorvol_sem = tumorvol_pd.reset_index()\ntumorvol_sem.head()\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"RogerJAlbarran/matplotlib-challenge","sub_path":"Pymaceuticals Main py (1).py","file_name":"Pymaceuticals Main py (1).py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"19745608096","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import render\n\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\nfrom pruebaApp.models import Platillo\nfrom pruebaApp.serializers import PlatilloSerializer\n\nclass JSONResponse(HttpResponse):\n\n\tdef __init__(self, data, **kwargs):\n\t\tcontent = JSONRenderer().render(data)\n\t\tkwargs['content_type'] = 'application/json'\n\t\tsuper(JSONResponse, self).__init__(content, **kwargs)\n\t\n@csrf_exempt\ndef platillo_list(request):\n\tif request.method == 'GET':\n\t\tplatillos = Platillo.objects.all()\n\t\tserializer = PlatilloSerializer(platillos, many=True)\n\t\treturn JSONResponse(serializer.data)\n\telif request.method == 'POST':\n\t\tdata = JSONParser().parse(request)\n\t\tserializer = PlatilloSerializer(data=data)\n\t\tif serializer.is_valid():\n\t\t\tserializer.save()\n\t\t\treturn JSONResponse(serializer.data, status=201)\n\t\treturn JSONResponse(serializer.errors, status=400)\n\n@csrf_exempt\ndef platillo_detail(request, idP):\n \n\ttry:\n\t\tplatillo = Platillo.objects.get(idP=idP)\n\texcept Platillo.DoesNotExist:\n\t\treturn HttpResponse(status=404)\n\tif request.method == 'GET':\n\t\tserializer = PlatilloSerializer(platillo)\n\t\treturn JSONResponse(serializer.data)\n\n\telif request.method == 'PUT':\n\t\tdata = JSONParser().parse(request)\n\t\tserializer = PlatilloSerializer(platillo, data=data)\n\t\tif serializer.is_valid():\n\t\t\tserializer.save()\n\t\t\treturn JSONResponse(serializer.data)\n\t\treturn JSONResponse(serializer.errors, status=400)\n\n\telif request.method == 'DELETE':\n\t\tplatillo.delete()\n\t\treturn HttpResponse(status=204)\n","repo_name":"anrosant/angular2","sub_path":"pruebaRest/prueba/pruebaApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"23693723793","text":"import pygame, controls\nfrom tank import Tank\nfrom pygame.sprite import Group\nfrom stats import Stats\nfrom scores import Scores\n\ndef start():\n\n pygame.init()\n screen = pygame.display.set_mode((720, 720), 1, 1, 0, 1)\n pygame.display.set_caption('space game')\n bg_color = (30, 30, 30)\n tank = Tank(screen)\n bullets = Group()\n enemyes = Group()\n controls.create_squad(screen, enemyes)\n stats = Stats()\n score = Scores(screen, stats)\n\n while True:\n\n controls.events(screen, tank, bullets)\n if stats.start_game:\n tank.update_tank()\n controls.update_screen(bg_color, screen, stats, score, tank, bullets, enemyes)\n controls.update_bullets(screen, stats, score, bullets, enemyes)\n controls.update_enemyes(stats, screen, score, tank, enemyes, bullets)\n\nstart()","repo_name":"Antei/space_game","sub_path":"space_game.py","file_name":"space_game.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"41959243471","text":"import torch\nimport torch.nn as nn\nfrom torch.distributions import Categorical\nimport torch.nn.functional as f\nimport torch.optim as optim\n\nfrom ma_gym_workspace.util.basic_net import Actor, MACritic\nfrom ma_gym_workspace.util.experience_memory import ExperienceMemory, Dynamics\n\n\nclass MADDPG(object):\n def __init__(self, obs_dim, n_agents, n_actions, capacity=5000, batch_size=300,\n gamma=0.99, a_lr=0.0001, c_lr=0.0001, tau=0.02, lt=0.0001, ut=1.0, step_weight=0.9):\n self.n_agents = n_agents\n self.batch_size = batch_size\n self.gamma = gamma\n self.tau = tau\n self.lt = lt\n self.ut = ut\n self.step = 0\n self.step_weight = step_weight\n self.temperature = 1.0\n self.single_obs_dim = obs_dim\n self.single_n_actions = n_actions\n\n self.memory = ExperienceMemory(capacity)\n\n # cur 用于训练,tar 用于采样\n self.actors_cur = [] # type: list[Actor]\n self.critics_cur = [] # type: list[MACritic]\n self.actors_tar = [] # type: list[Actor]\n self.critics_tar = [] # type: list[MACritic]\n self.actors_optimizer = [] # type: list[optim.Adam]\n self.critics_optimizer = [] # type: list[optim.Adam]\n\n self.a_lr = a_lr\n self.c_lr = c_lr\n self.init_agents()\n\n def init_agents(self):\n for agent_i in range(self.n_agents):\n self.actors_cur.append(Actor(self.single_obs_dim, self.single_n_actions))\n self.critics_cur.append(MACritic(self.single_obs_dim * self.n_agents, self.n_agents))\n self.actors_tar.append(Actor(self.single_obs_dim, self.single_n_actions))\n self.critics_tar.append(MACritic(self.single_obs_dim * self.n_agents, self.n_agents))\n self.actors_optimizer.append(optim.Adam(self.actors_cur[agent_i].parameters(), lr=self.a_lr))\n self.critics_optimizer.append(optim.Adam(self.critics_cur[agent_i].parameters(), lr=self.c_lr))\n\n # 对tar网络采取软更新策略\n self.actors_tar = self.update_tar(self.actors_cur, self.actors_tar, self.tau)\n self.critics_tar = self.update_tar(self.critics_cur, self.critics_tar, self.tau)\n\n def infer_actions(self, joint_obs, add_noise=True):\n actions = []\n if add_noise:\n self.temperature = self.update_temperature(self.ut, self.lt, self.step_weight)\n print('temperature:', self.temperature)\n for agent_i, actor_tar in enumerate(self.actors_tar):\n state = torch.tensor(joint_obs[agent_i], dtype=torch.float)\n action_dis = actor_tar.forward(state, temperature=self.temperature).detach() # type: torch.Tensor\n # temperature应该随着训练进行从1逐渐变小,要慢慢减少噪声\n actions.append(action_dis.max(0)[1].item())\n else:\n for agent_i, actor_tar in enumerate(self.actors_tar):\n state = torch.tensor(joint_obs[agent_i], dtype=torch.float)\n action_dis = actor_tar.forward(state, temperature=0).detach() # type: torch.Tensor\n # temperature应该随着训练进行从1逐渐变小,要慢慢减少噪声\n actions.append(action_dis.max(0)[1].item())\n return actions\n\n def update_temperature(self, init_t, final_t, step_weight):\n temperature = pow(1.0 - (final_t / init_t), (self.step / step_weight))\n self.step += 1\n return max(temperature, final_t)\n\n def push_dynamics(self, joint_obs, joint_actions, n_rewards, next_joint_obs, n_done):\n self.memory.push(joint_obs, joint_actions, n_rewards, next_joint_obs, n_done)\n\n def learn(self):\n \"\"\"\n 先计算Critic loss,包含了每个agent的观测和动作作为输入\n 之后计算actor loss,仅包含每个agent自己的观测\n :return:\n \"\"\"\n if len(self.memory) < self.batch_size:\n print('Data is not enough')\n return\n\n batch = self.memory.sample(self.batch_size)\n data = Dynamics(*zip(*batch))\n joint_obs = torch.tensor(data.state, dtype=torch.float)\n joint_actions = torch.tensor(data.action, dtype=torch.float)\n n_rewards = torch.tensor(data.reward, dtype=torch.float)\n joint_next_obs = torch.tensor(data.next_state, dtype=torch.float)\n n_dones = torch.tensor(data.is_end, dtype=torch.float)\n\n for agent_i, (actor_tar, actor_cur, critic_tar, critic_cur, actor_o, critic_o) in \\\n enumerate(zip(self.actors_tar, self.actors_cur,\n self.critics_tar, self.critics_cur, self.actors_optimizer, self.critics_optimizer)):\n \"\"\"\n 计算Critic loss:\n target value: y = ri + gamma * Qi 注意,这里的Q采用target网络计算,动作也由target网络给出\n current value: Qi 这里的Q采用current网络计算,动作来自经验回放池采样,梯度更新的也是cur参数\n \"\"\"\n # print('single agent obs', joint_next_obs[:, agent_i:agent_i+1, :].squeeze(),\n # 'shape', joint_next_obs[:, agent_i: agent_i+1, :].squeeze().shape)\n # print('action', Categorical(self.actors_tar[0].forward(joint_next_obs[:, 0:1, :].squeeze(), softmax=1)).sample().shape)\n next_actions = torch.cat([tar.forward(joint_next_obs[:, idx:idx+1, :].squeeze(), gs_dim=1).max(1)[1].reshape(-1, 1) for idx, tar in enumerate(self.actors_tar)], dim=1).float()\n # print('next_actions', next_actions.shape)\n # print('single rewards', n_rewards[:, agent_i:agent_i+1].shape,\n # 'single done', n_dones[:, agent_i:agent_i+1].shape)\n # print('joint next obs shape', joint_next_obs.shape, 'joint next action shape', next_actions.shape)\n target_qs = n_rewards[:, agent_i:agent_i+1] + self.gamma * critic_tar(joint_next_obs.reshape(self.batch_size, -1), next_actions) * n_dones[:, agent_i:agent_i+1]\n # print('joint obs shape', joint_obs.reshape(300, -1).shape, 'joint actions', joint_actions.shape)\n current_qs = critic_cur(joint_obs.reshape(self.batch_size, -1), joint_actions)\n critic_loss = f.smooth_l1_loss(current_qs, target_qs.detach())\n critic_o.zero_grad()\n critic_loss.mean().backward()\n critic_o.step()\n\n \"\"\"\n 计算Actor loss:\n 目测好像目标函数就是Q值,aj是通过actor cur获得的,其他的a是经验回放中获得的\n \"\"\"\n # print('joint obs shape', joint_obs[:, agent_i:agent_i+1, :].squeeze().shape)\n action_i = actor_cur.forward(joint_obs[:, agent_i:agent_i+1, :].squeeze(), 1).max(1)[1].reshape(-1, 1)\n # print('joint action', action_i.shape)\n joint_actions[:, agent_i:agent_i+1] = action_i\n actor_loss = - critic_cur(joint_obs.reshape(self.batch_size, -1), joint_actions)\n actor_o.zero_grad()\n actor_loss.mean().backward()\n actor_o.step()\n\n self.actors_tar = self.update_tar(self.actors_cur, self.actors_tar, self.tau)\n self.critics_tar = self.update_tar(self.critics_cur, self.critics_tar, self.tau)\n\n @staticmethod\n def update_tar(agents_cur, agents_tar, tau):\n \"\"\"\n 软更新的方式,更新步长为tau\n :param agents_cur:\n :param agents_tar:\n :param tau:\n :return:\n \"\"\"\n for agent_cur, agent_tar in zip(agents_cur, agents_tar):\n key_list = list(agent_cur.state_dict().keys())\n state_dict_t = agent_tar.state_dict()\n state_dict_c = agent_cur.state_dict()\n for key in key_list:\n state_dict_t[key] = state_dict_c[key] * tau + state_dict_t[key] * (1 - tau)\n agent_tar.load_state_dict(state_dict_t)\n return agents_tar\n","repo_name":"znnby1997/ProjectForRL","sub_path":"ma_gym_workspace/model/maddpg.py","file_name":"maddpg.py","file_ext":"py","file_size_in_byte":7904,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"15533544277","text":"# pylint: disable=no-name-in-module\n\nimport csv\nimport os\nimport tempfile\nimport zipfile\n\nimport numpy as np\nfrom d3rlpy.dataset import MDPDataset\nfrom PIL import Image\nfrom tqdm import trange\n\n\ndef convert_ndarray_to_image(ndarray):\n # convert channel-fist to channel-last\n if ndarray.shape[0] == 1:\n array = ndarray[0]\n else:\n array = np.transpose(ndarray, [1, 2, 0])\n return Image.fromarray(array)\n\n\ndef convert_image_to_ndarray(image):\n array = np.asarray(image)\n # fix channel-first shape\n if image.mode == \"L\":\n array = array.reshape((1, *array.shape))\n else:\n array = array.transpose([2, 0, 1])\n return array\n\n\ndef export_mdp_dataset_as_csv(dataset, fname):\n if len(dataset.get_observation_shape()) > 1:\n # image observation\n export_image_observation_dataset_as_csv(dataset, fname)\n else:\n # vector observation\n export_vector_observation_dataset_as_csv(dataset, fname)\n\n\ndef _save_image_files(dataset, zip_path):\n with tempfile.TemporaryDirectory() as dname:\n with zipfile.ZipFile(zip_path, \"w\") as zip_fd:\n data_size = dataset.observations.shape[0]\n for i in trange(data_size, desc=\"saving images\"):\n image = convert_ndarray_to_image(dataset.observations[i])\n image_path = os.path.join(dname, \"observation_%d.png\" % i)\n image.save(image_path, quality=100)\n zip_fd.write(image_path, arcname=\"observation_%d.png\" % i)\n\n\ndef export_image_observation_dataset_as_csv(dataset, fname):\n action_size = dataset.get_action_size()\n\n # prepare image directory\n csv_file_name = os.path.basename(fname)\n\n # save image files as zip file\n zip_name = csv_file_name.split(\".\")[0] + \".zip\"\n zip_path = os.path.join(os.path.dirname(fname), zip_name)\n _save_image_files(dataset, zip_path)\n\n with open(fname, \"w\") as file:\n writer = csv.writer(file)\n\n # write header\n header = [\"episode\", \"observation:0\"]\n if dataset.is_action_discrete():\n header += [\"action:0\"]\n else:\n header += [\"action:%d\" % i for i in range(action_size)]\n header += [\"reward\"]\n writer.writerow(header)\n\n count = 0\n for i, episode in enumerate(dataset.episodes):\n # prepare data to write\n for j in range(episode.observations.shape[0]):\n row = []\n row.append(i)\n\n # add image path\n row.append(\"observation_%d.png\" % count)\n count += 1\n\n row += episode.actions[j].reshape(-1).tolist()\n row.append(episode.rewards[j])\n writer.writerow(row)\n\n\ndef export_vector_observation_dataset_as_csv(dataset, fname):\n observation_size = dataset.get_observation_shape()[0]\n action_size = dataset.get_action_size()\n\n with open(fname, \"w\") as file:\n writer = csv.writer(file)\n\n # write header\n header = [\"episode\"]\n header += [\"observation:%d\" % i for i in range(observation_size)]\n if dataset.is_action_discrete():\n header += [\"action:0\"]\n else:\n header += [\"action:%d\" % i for i in range(action_size)]\n header += [\"reward\"]\n writer.writerow(header)\n\n for i, episode in enumerate(dataset.episodes):\n # prepare data to write\n observations = np.asarray(episode.observations)\n episode_length = observations.shape[0]\n actions = np.asarray(episode.actions).reshape(episode_length, -1)\n rewards = episode.rewards.reshape(episode_length, 1)\n episode_ids = np.full([episode_length, 1], i)\n\n # write episode\n rows = np.hstack([episode_ids, observations, actions, rewards])\n writer.writerows(rows)\n\n\ndef import_csv_as_mdp_dataset(fname, image=False):\n if image:\n return import_csv_as_image_observation_dataset(fname)\n return import_csv_as_vector_observation_dataset(fname)\n\n\ndef _load_image(path):\n image = Image.open(path)\n\n # resize image to (84, 84)\n if image.size != (84, 84):\n image = image.resize((84, 84), Image.BICUBIC)\n\n return image\n\n\ndef import_csv_as_image_observation_dataset(fname):\n with open(fname, \"r\") as file:\n reader = csv.reader(file)\n rows = [row for row in reader]\n\n # check header\n header = rows[0]\n _validate_csv_header(header)\n\n # get action size\n action_size = _get_action_size_from_header(header)\n\n data_size = len(rows) - 1\n\n observations = []\n actions = []\n rewards = []\n terminals = []\n for i, row in enumerate(rows[1:]):\n episode_id = row[0]\n\n # load image\n image_path = os.path.join(os.path.dirname(fname), row[1])\n if not os.path.exists(image_path):\n raise ValueError(f\"{image_path} does not exist.\")\n image = _load_image(os.path.join(os.path.dirname(fname), row[1]))\n\n # convert PIL.Image to ndarray\n array = convert_image_to_ndarray(image)\n\n observations.append(array)\n\n # get action columns\n actions.append(list(map(float, row[2 : 2 + action_size])))\n\n # get reward column\n rewards.append(float(row[-1]))\n\n if i == data_size - 1 or episode_id != rows[i + 2][0]:\n terminals.append(1)\n else:\n terminals.append(0)\n\n # convert list to ndarray\n observations = np.array(observations, dtype=np.uint8)\n actions = np.array(actions)\n rewards = np.array(rewards, dtype=np.float32)\n terminals = np.array(terminals, dtype=np.float32)\n\n dataset = MDPDataset(\n observations=observations,\n actions=actions,\n rewards=rewards,\n terminals=terminals,\n )\n\n return dataset\n\n\ndef import_csv_as_vector_observation_dataset(fname):\n with open(fname, \"r\") as file:\n reader = csv.reader(file)\n rows = [row for row in reader]\n\n # get observation shape\n header = rows[0]\n _validate_csv_header(header)\n\n # retrieve data section\n csv_data = np.array(rows[1:], dtype=np.float32)\n\n # get observation columns\n observation_size = _get_observation_size_from_header(header)\n observation_last_index = observation_size + 1\n observations = csv_data[:, 1:observation_last_index]\n\n # get action columns\n action_size = _get_action_size_from_header(header)\n action_last_index = observation_last_index + action_size\n actions = csv_data[:, observation_last_index:action_last_index]\n\n # get reward column\n rewards = csv_data[:, -1]\n\n # make terminal flags\n episode_ids = csv_data[:, 0]\n terminals = np.zeros_like(episode_ids)\n for i, episode_id in enumerate(episode_ids):\n if i + 1 == len(episode_ids) or episode_id != episode_ids[i + 1]:\n terminals[i] = 1.0\n\n dataset = MDPDataset(\n observations=observations,\n actions=actions,\n rewards=rewards,\n terminals=terminals,\n )\n\n return dataset\n\n\ndef _validate_csv_header(header):\n assert header[0] == \"episode\", \"column=0 must be 'episode'\"\n\n # check observation section\n index = 1\n observation_index = 0\n while header[index].find(\"action\") == -1:\n ref_name = \"observation:%d\" % observation_index\n message = \"column=%d must be '%s'\" % (index, ref_name)\n assert header[index] == ref_name, message\n index += 1\n observation_index += 1\n\n # check action section\n action_index = 0\n while header[index] != \"reward\":\n ref_name = \"action:%d\" % action_index\n message = \"column=%d must be '%s'\" % (index, ref_name)\n assert header[index] == ref_name, message\n index += 1\n action_index += 1\n\n\ndef _get_observation_size_from_header(header):\n size = 0\n for column in header:\n if column.find(\"observation\") > -1:\n size += 1\n return size\n\n\ndef _get_action_size_from_header(header):\n size = 0\n for column in header:\n if column.find(\"action\") > -1:\n size += 1\n return size\n","repo_name":"takuseno/minerva","sub_path":"minerva/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":8349,"program_lang":"python","lang":"en","doc_type":"code","stars":89,"dataset":"github-code","pt":"77"}
+{"seq_id":"30051665147","text":"import os\nimport re\nimport mailbox\nimport numpy as np\nimport random\nfrom collections import Counter\nfrom sklearn.naive_bayes import MultinomialNB, GaussianNB, BernoulliNB\nfrom sklearn.svm import SVC, NuSVC, LinearSVC\nimport numpy as np\nfrom sklearn import metrics\nimport matplotlib.pyplot as plt\n\n# import data from mbox files\n# remove tabs, special characters and digits\n# social category is labled as ham and promotions are labeled as spam\n\ndata = []\nfor message in mailbox.mbox('./Mail/SocialLabel.mbox'):\n subject = str(message['subject'])\n if not (('utf-8' in subject) or ('UTF-8' in subject)):\n #remove tags\n subject=re.sub(\"?.*?>\",\" <> \", subject)\n\n # remove special characters and digits\n subject=re.sub(\"(\\\\d|\\\\W)+\",\" \", subject)\n \n data.append([subject, \"ham\", 0.0])\ndata = data[0:900]\nprint(len(data))\n\nfor message in mailbox.mbox('./Mail/PromotionsLabel.mbox'):\n subject = str(message['subject'])\n if not (('utf-8' in subject) or ('UTF-8' in subject)):\n #remove tags\n subject=re.sub(\"?.*?>\",\" <> \", subject)\n\n # remove special characters and digits\n subject=re.sub(\"(\\\\d|\\\\W)+\",\" \", subject)\n \n data.append([subject, \"spam\", 0.0])\n \ndata = data[0:1800]\n\n\n##KNN\n# split data into train and test data\nfor item in data:\n item.append(random.random())\ntrain_data = []\ntest_data = []\nfor item in data:\n if item[3] > 0.3:\n train_data.append(item[0:3])\n else:\n test_data.append(item[0:3])\n\n# start testing\ndef getSimilarity(record1, record2):\n len1 = len(record1[0].split())\n len2 = len(record2[0].split())\n num_common = 0\n d = dict()\n for word in record1[0].split():\n \tif word not in d:\n \t\td[word] = 1\n for word in record2[0].split():\n \tif word in d:\n \t\tnum_common += 1\n divided_by = (len1 * len2) ** 0.5\n if (divided_by != 0):\n similarity = num_common / divided_by\n else:\n similarity = 0\n return similarity\n\n\ndef findKNN(train_data, record, k):\n # get the distance between every train_data and the record\n for i in range(0,len(train_data)):\n \tsim = getSimilarity(train_data[i], record)\n \ttrain_data[i][-1] = sim\n\n res = []\n for i in range(k):\n \tmax_sim = 0\n \tmax_sim_index = 0\n \tfor i in range(0, len(train_data)):\n \t\tif train_data[i][-1] > max_sim:\n \t\t\tmax_sim = train_data[i][-1]\n \t\t\tmax_sim_index = i\n \ttrain_data[max_sim_index][-1] = 0\n \tres.append(train_data[max_sim_index])\n return res\n\ndef calc_auc(knn):\n num_ham = 0\n num_spam = 0\n for r in knn:\n if r[1] == 'ham':\n num_ham += 1\n else:\n num_spam += 1\n pred = num_spam/(num_ham + num_spam)\n return pred\n\n#calculate auc for k in range of 1 to 120\npreds = []\naucs = []\nfor k in range(1,120):\n preds=[]\n for d in test_data:\n knn = findKNN(train_data, d, k)\n preds.append(calc_auc(knn)) \n TPRs = []\n FPRs = []\n preds.sort()\n for threshold in preds:\n TN = 0\n TP = 0\n FP = 0\n FN = 0\n for p, d in zip(preds, test_data):\n if p >= threshold:\n result = \"spam\"\n else:\n result = \"ham\"\n\n #calculating metrics\n if result == d[1]:\n if result == 'spam':\n TP += 1\n if result == 'ham':\n TN += 1\n else:\n if result == 'spam':\n FP += 1\n if result == 'ham':\n FN += 1\n TPR = TP/(TP+FN)\n FPR = FP/(FP+TN)\n TPRs.append(TPR)\n FPRs.append(FPR)\n auc = metrics.auc(FPRs, TPRs)\n aucs.append(auc) \n\nplt.plot(range(1,120), aucs)\nplt.show()\n\ndef judge(knn):\n num_ham = 0\n num_spam = 0\n for r in knn:\n if r[1] == 'ham':\n num_ham += 1\n else:\n num_spam += 1\n p_spam = num_spam/(num_ham + num_spam)\n return \"spam\" if p_spam >= 0.36 else \"ham\"\n\n#final calculation for KNN after deciding k=11\nk=11\nTN = 0\nTP = 0\nFP = 0\nFN = 0\naucs = []\npreds=[]\nfor d in test_data:\n knn = findKNN(train_data, d, k)\n preds.append(calc_auc(knn))\n result = judge(knn)\n if result == d[1]:\n correct += 1\n if result == 'spam':\n TP += 1\n if result == 'ham':\n TN += 1\n else:\n wrong += 1\n if result == 'spam':\n FP += 1\n if result == 'ham':\n FN += 1\n\n## NAIVE BAYES\n# map tokens to number of occurences\nham_dict = dict()\nspam_dict = dict()\nfor d in train_data:\n\tif d[-1] == \"ham\":\n\t\tfor word in d[0].split():\n\t\t\tif word in ham_dict:\n\t\t\t\tham_dict[word] += 1\n\t\t\telse:\n\t\t\t\tham_dict[word] = 1\n\telif d[-1] == \"spam\":\n\t\tfor word in d[0].split():\n\t\t\tif word in spam_dict:\n\t\t\t\tspam_dict[word] += 1\n\t\t\telse:\n\t\t\t\tspam_dict[word] = 1\n\n# testing\nprior_ham = 0.5\nprior_spam = 0.5\nTN = 0\nTP = 0\nFP = 0\nFN = 0\npred = []\nfor d in test_data:\n\ttext = d[0]\n\tp_ham = 1\n\tp_spam = 1\n\tfor word in text.split():\n\t\tnum_ham = ham_dict[word] if word in ham_dict else 0.000001\n\t\tnum_spam = spam_dict[word] if word in spam_dict else 0.000001\n\t\tlikily_ham = num_ham / (num_ham + num_spam)\n\t\tlikily_spam = num_spam / (num_ham + num_spam)\n\t\tp_ham *= (likily_ham * prior_ham) / (likily_ham * prior_ham + likily_spam * prior_spam)\n\t\tp_spam *= (likily_spam * prior_spam) / (likily_ham * prior_ham + likily_spam * prior_spam)\n\tif p_spam > p_ham:\n\t\tresult = \"spam\"\n\telif p_spam < p_ham:\n\t\tresult = \"ham\"\n\tp_spam_roc = p_spam/(p_spam+p_ham)\n\tpred.append(p_spam_roc)\n\n#calculating metrics\n\tif result == d[1]:\n\t\tif result == 'spam':\n\t\t\tTP += 1\n\t\tif result == 'ham':\n\t\t\tTN += 1\n\telse:\n\t\tif result == 'spam':\n\t\t\tFP += 1\n\t\tif result == 'ham':\n\t\t\tFN += 1\nprecision=TP/(TP+FP)\nrecall=TP/(TP+FN)\nF1 = 2 * (precision * recall) / (precision + recall)\n\n\n#calculating AUC for Naive Bayes\nTPRs = []\nFPRs = []\npred.sort()\nfor threshold in pred:\n TN = 0\n TP = 0\n FP = 0\n FN = 0\n for p, d in zip(pred, test_data):\n if p > threshold:\n result = \"spam\"\n else:\n result = \"ham\"\n\n #calculating metrics\n if result == d[1]:\n if result == 'spam':\n TP += 1\n if result == 'ham':\n TN += 1\n else:\n if result == 'spam':\n FP += 1\n if result == 'ham':\n FN += 1\n\n TPR = TP/(TP+FN)\n FPR = FP/(FP+TN)\n TPRs.append(TPR)\n FPRs.append(FPR)","repo_name":"JessicaLiu21/Sample_Python_Code","sub_path":"ML Package/Spam_Filter.py","file_name":"Spam_Filter.py","file_ext":"py","file_size_in_byte":6511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"30741784650","text":"from pathlib import Path\nimport numpy as np\nfrom dolfin import *\n\ndef poisson_error(N, order=1, plot=False):\n # Create mesh and define function space\n mesh = UnitSquareMesh(N, N)\n V = FunctionSpace(mesh, \"P\", order)\n\n # Define boundary condition\n u_D = Expression(\"1 + x[0]*x[0] + 2*x[1]*x[1]\", degree=6)\n\n def boundary(x, on_boundary):\n return on_boundary\n\n bc = DirichletBC(V, u_D, boundary)\n\n # Define variational problem\n u = TrialFunction(V)\n v = TestFunction(V)\n f = Constant(-6.0)\n a = dot(grad(u), grad(v)) * dx\n L = f * v * dx\n\n # Compute solution\n u = Function(V)\n solve(a == L, u, bc)\n\n if plot:\n # Save solution to file in VTK format\n f = XDMFFile(str(Path(__file__).parent / \"poisson.xdmf\"))\n f.write(u,0.)\n\n # Compute error in L2 norm\n error_L2 = errornorm(u_D, u, \"L2\")\n return error_L2\n\n\nif __name__ == \"__main__\":\n Ns = [1, 2, 4, 8, 16, 32, 64, 128]\n errors = []\n for N in Ns:\n errors.append(poisson_error(N, plot=N == 128))\n\n np.save(Path(__file__).parent / \"poisson_convergence_Ns\", Ns)\n np.save(Path(__file__).parent / \"poisson_convergence_errors\", errors)\n","repo_name":"BAMresearch/Reproducible-Science","sub_path":"example/computation/poisson.py","file_name":"poisson.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"28895575779","text":"from __future__ import print_function\nfrom __future__ import absolute_import\nfrom builtins import object\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader\nimport os\nimport re\n\nimport set_pyreg_paths\nimport pyreg.fileio as FIO\nimport pyreg.module_parameters as pars\nimport pyreg.deep_smoothers as deep_smoothers\nimport pyreg.deep_networks as dn\n\nfrom pyreg.data_wrapper import MyTensor, AdaptVal, USE_CUDA\n\ndevice = torch.device(\"cuda:0\" if (torch.cuda.is_available() and USE_CUDA) else \"cpu\")\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\n\n# create a dataloader\n\nclass ImageAndWeightDataset(Dataset):\n \"\"\"keeps track of pairwise image as well as checkpoints for their parameters\"\"\"\n\n def __init__(self, image_filenames, rel_path, params):\n\n self.params = params\n\n self.image_filenames = image_filenames\n self.rel_path = rel_path\n\n self.params[('image_and_weight_data_loader', {}, 'data loader settings')]\n cparams = self.params['image_and_weight_data_loader']\n self.intensity_normalize = cparams[('intensity_normalize',False,'intensity normalize images when reading')]\n self.squeeze_image = cparams[('squeeze_image',True,'squeezes image first (e.g, from 1x128x128 to 128x128)')]\n self.normalize_spacing = cparams[('normalize_spacing',True,'normalizes the image spacing')]\n\n def __len__(self):\n return len(self.image_filenames)\n\n def _get_image_filename(self,idx):\n return os.path.join(rel_path,self.image_filenames[idx])\n\n def _get_file_idx_from_image_filename(self,image_filename):\n # this will be a number at the end. Filenames are expected to be of the format m20.nii\n file_idx = int(re.findall(r'\\d+',image_filename)[0])\n return file_idx\n\n def _get_weight_filename(self,idx):\n current_image_filename = self._get_image_filename(idx)\n file_idx = self._get_file_idx_from_image_filename(current_image_filename)\n # this will be one directory up, in the subdirectory misc and by name gt_weights_00001.pt\n pn, _ = os.path.split(current_image_filename)\n pn, _ = os.path.split(pn) # because we need to get one directory up\n weight_filename = os.path.join(pn,'misc','gt_weights_{:05d}.pt'.format(file_idx))\n return weight_filename\n\n def __getitem__(self,idx):\n\n # load the actual images\n current_source_filename = self._get_image_filename(idx)\n\n im_io = FIO.ImageIO()\n ISource,hdr,spacing,normalized_spacing = im_io.read_batch_to_nc_format([current_source_filename],\n intensity_normalize=self.intensity_normalize,\n squeeze_image=self.squeeze_image,\n normalize_spacing=self.normalize_spacing,\n silent_mode=True)\n\n current_weight_filename = self._get_weight_filename(idx)\n weights = torch.load(current_weight_filename)\n\n sample = dict()\n sample['idx'] = idx\n sample['ISource'] = ISource[0,...] # as we only loaded a batch-of-one we remove the first dimension\n sample['gt_weights'] = weights[0,...]\n sample['spacing'] = normalized_spacing\n\n return sample\n\ndef compute_variances(weights,stds):\n nr_s = len(stds)\n nr_w = weights.size()[1]\n assert(nr_s==nr_w)\n\n ret = torch.zeros_like(weights[:,0,...])\n for n in range(nr_w):\n ret += weights[:,n,...]*stds[n]**2\n\n return ret\n\nonly_evaluate = False\n\nrel_path = '../experiments'\n\nsave_network_state_dict_file = 'network_conf.pt'\n\nif only_evaluate:\n input_directory = 'test_nn_synthetic_example_out_kernel_weighting_type_sqrt_w_K_sqrt_w'\nelse:\n input_directory = 'synthetic_example_out_kernel_weighting_type_sqrt_w_K_sqrt_w'\n\nimage_input_directory = os.path.join(rel_path,input_directory,'brain_affine_icbm')\n\ndim = 2\nbatch_size = 20\nnr_of_epochs = 100\nvisualize_intermediate_results = True\nonly_display_epoch_results = True\nimage_offset = 1.0\n\nif only_evaluate:\n if nr_of_epochs!=1:\n print('INFO: Setting number of epochs to 1 for evaluation-only mode')\n nr_of_epochs = 1\n if batch_size!=1:\n print('INFO: Setting batch size to 1 for evaluation-only mode')\n batch_size = 1\n\n# todo: read this values from the configuration file\nnr_of_weights = 4\n#global_multi_gaussian_weights = torch.from_numpy(np.array([0.25,0.25,0.25,0.25],dtype='float32'))\nglobal_multi_gaussian_weights = torch.from_numpy(np.array([0.0,0.0,0.3,0.7],dtype='float32'))\ngaussian_stds = torch.from_numpy(np.array([0.01,0.05,0.1,0.2],dtype='float32'))\n\nnormalization_type = 'group' # '['batch', 'instance', 'layer', 'group', 'none']\nuse_noisy_convolution = False\nnoisy_convolution_std = 0.05\n\nuse_noise_layers = False\nnoise_layer_std = 0.025\nlast_noise_layer_std = 0.025\n\nuse_color_tv = True\nuse_omt_tv_weighting = False\nreconstruct_variances = False\nreconstruct_stds = True\n\ndisplay_colorbar = True\n\nim_sz = np.array([128,128])\nreconstruction_weight = 10000.0\ntotalvariation_weight = 0.001\nomt_weight = 0.0001\nomt_power=1.0\nomt_use_log_transformed_std=True\nlr = 0.05\nseed = 75\n\nif seed is not None:\n print('Setting the seed to: {}'.format(seed))\n random.seed(seed)\n torch.manual_seed(seed)\n\nused_image_pairs_file = os.path.join(rel_path,input_directory,'used_image_pairs.pt')\nused_image_pairs = torch.load(used_image_pairs_file)\n# only the source images have the weights\ninput_images = used_image_pairs['source_images']\n\n# todo: check if smoothing of input image is beneficial for edge detection\n# todo: if so, also implement it in the main code base\n\n# todo: think about where to inject the noise in the noisy convolution, before or after the normalization (likely after the normalization)\n# todo: weight the total variation term by the OMT cost. In this way it will be cheaper to introduce jumps for cheaper terms\n\n#network_type = dn.Unet_no_skip\n#network_type = dn.Unet\nnetwork_type = dn.Simple_consistent\n\nparams = pars.ParameterDict()\nparams['normalization_type'] = normalization_type\nparams['use_noisy_convolution'] = use_noisy_convolution\nparams['noisy_convolution_std'] = noisy_convolution_std\n\nparams['use_noise_layers'] = use_noise_layers\nparams['noise_layer_std'] = noise_layer_std\nparams['last_noise_layer_std'] = last_noise_layer_std\n\nparams['edge_penalty_gamma'] = 2. #10.\n\ndataset = ImageAndWeightDataset(image_filenames=input_images, rel_path=rel_path, params=params)\ntrainloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=1)\n\n# create the two network and the loss function\n\nreconstruction_criterion = nn.MSELoss().to(device) # nn.L1Loss().to(device)\ntotalvariation_criterion = None\nomt_criterion = None\n\nreconstruction_unet = network_type(dim=dim, n_in_channel=1, n_out_channel=nr_of_weights, im_sz=im_sz, params=params).to(device)\nreconstruction_unet.initialize_network_weights()\n\nif only_evaluate:\n print('INFO: Loading the network state from {}'.format(save_network_state_dict_file))\n reconstruction_unet.load_state_dict(torch.load(save_network_state_dict_file))\n\nall_optimization_parameters = reconstruction_unet.parameters()\n\nprint(reconstruction_unet)\n\n# create the optimizer\noptimizer = optim.SGD(all_optimization_parameters, lr=lr, momentum=0.9, nesterov=True)\n#optimizer = optim.SGD(all_optimization_parameters, lr=lr, momentum=0.9, nesterov=True, weight_decay=0.001)\n\nnr_of_datasets = len(dataset)\nnr_of_batches = len(trainloader)\n\n# pre-weights versus weights\ndeep_network_local_weight_smoothing = 0.02\ndeep_network_weight_smoother = None\n\n\nfor epoch in range(nr_of_epochs): # loop over the dataset multiple times\n\n running_loss = 0.0\n running_reconstruction_loss = 0.0\n running_totalvariation_loss = 0.0\n running_omt_loss = 0.0 # todo: add the OMT loss\n\n for i, data in enumerate(trainloader, 0):\n # get the inputs\n input_dict = data\n unscaled_images = input_dict['ISource'].to(device)\n gt_weights = input_dict['gt_weights'].to(device)\n inputs = input_dict['ISource'].to(device) - image_offset\n spacing = input_dict['spacing'][0].detach().cpu().numpy() # all of the spacings are the same, so just use one\n volumeElement = spacing.prod()\n\n if totalvariation_criterion is None:\n # now we have the spacing information and can instantiate it\n totalvariation_criterion = dn.TotalVariationLoss(dim=dim, im_sz=im_sz, spacing=spacing,\n use_omt_weighting=use_omt_tv_weighting,\n gaussian_stds=gaussian_stds,\n omt_power=omt_power,\n omt_use_log_transformed_std=omt_use_log_transformed_std,\n params=params).to(device)\n if omt_criterion is None:\n # now we have the spacing information and can instantiate it\n omt_criterion = dn.OMTLoss(spacing=spacing, desired_power=omt_power,\n use_log_transform=omt_use_log_transformed_std, params=params).to(device)\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n reconstruction_outputs = reconstruction_unet(inputs)\n #pre_weights = deep_smoothers.weighted_softmax(reconstruction_outputs, dim=1, weights=global_multi_gaussian_weights)\n pre_weights = deep_smoothers.weighted_linear_softmax(reconstruction_outputs, dim=1, weights=global_multi_gaussian_weights)\n #pre_weights = deep_smoothers.stable_softmax(reconstruction_outputs, dim=1)\n\n # enforce minimum weight for numerical reasons\n # todo: check if this is really needed, this was for the sqrt\n # todo, maybe make this conditional\n pre_weights = deep_smoothers._project_weights_to_min(pre_weights, 0.001, norm_type='sum')\n\n # instantiate the extra smoother if weight is larger than 0 and it has not been initialized yet\n if deep_network_local_weight_smoothing > 0 and deep_network_weight_smoother is None:\n import pyreg.smoother_factory as sf\n\n s_m_params = pars.ParameterDict()\n s_m_params['smoother']['type'] = 'gaussian'\n s_m_params['smoother']['gaussian_std'] = deep_network_local_weight_smoothing\n deep_network_weight_smoother = sf.SmootherFactory(inputs.size()[2::], spacing=spacing).create_smoother(s_m_params)\n\n if deep_network_local_weight_smoothing > 0:\n # now we smooth all the weights\n weights = deep_network_weight_smoother.smooth(pre_weights)\n # make sure they are all still positive (#todo: may not be necessary, since we set a minumum weight above now; but risky as we take the square root below)\n\n # todo: put back in?\n #weights = torch.clamp(weights, 0.0, 1.0)\n else:\n weights = pre_weights\n\n # compute resulting variances\n gt_variances = compute_variances(gt_weights, gaussian_stds)\n pred_variances = compute_variances(weights, gaussian_stds)\n\n # compute losses\n if reconstruct_variances:\n reconstruction_loss = reconstruction_weight * reconstruction_criterion(pred_variances, gt_variances)\n elif reconstruct_stds:\n reconstruction_loss = reconstruction_weight * reconstruction_criterion(torch.sqrt(pred_variances), torch.sqrt(gt_variances))\n else: # directly penalizing weights differences\n reconstruction_loss = reconstruction_weight * reconstruction_criterion(weights, gt_weights)\n\n totalvariation_loss = totalvariation_weight * totalvariation_criterion(input_images=unscaled_images,label_probabilities=pre_weights,use_color_tv=use_color_tv)\n\n omt_loss = omt_weight * omt_criterion(weights, gaussian_stds)\n\n # compute the overall loss\n loss = reconstruction_loss + totalvariation_loss + omt_loss\n\n if not only_evaluate:\n # compute the gradient\n loss.backward()\n optimizer.step()\n\n if only_display_epoch_results:\n running_reconstruction_loss += reconstruction_loss.item() / nr_of_datasets\n running_loss += loss.item() / nr_of_datasets\n running_totalvariation_loss += totalvariation_loss.item() / nr_of_datasets\n running_omt_loss += omt_loss.item() / nr_of_datasets\n\n if i == nr_of_batches - 1:\n # print statistics\n print(\n 'Epoch: {}; loss={:.3f}, r_loss={:.3f}, tv_loss={:.3f}, omt_loss={:.3f}'\n .format(epoch + 1, running_loss, running_reconstruction_loss, running_totalvariation_loss, running_omt_loss))\n else:\n # print statistics\n print(\n 'Epoch: {}; batch: {}; loss={:.3f}, r_loss={:.3f}, tv_loss={:.3f}, omt_loss={:.3f}'\n .format(epoch + 1, i + 1, loss.item(), reconstruction_loss.item(), totalvariation_loss.item(), omt_loss.item()))\n\n if i == 0 and (epoch % 10 == 0):\n\n nr_of_current_images = inputs.size()[0]\n currently_selected_image = np.random.randint(low=0, high=nr_of_current_images)\n\n plt.clf()\n # plot the input (source) image\n plt.subplot(4, nr_of_weights, 1)\n plt.imshow(inputs[currently_selected_image, 0, ...].detach().cpu().numpy())\n plt.axis('image')\n plt.axis('off')\n if display_colorbar:\n plt.colorbar()\n\n plt.subplot(4, nr_of_weights, 2)\n plt.imshow((gt_variances[currently_selected_image,...].detach().cpu().numpy())**0.5)\n plt.axis('image')\n plt.axis('off')\n if display_colorbar:\n plt.colorbar()\n\n plt.subplot(4, nr_of_weights, 3)\n plt.imshow((pred_variances[currently_selected_image, ...].detach().cpu().numpy())**0.5)\n plt.axis('image')\n plt.axis('off')\n if display_colorbar:\n plt.colorbar()\n\n plt.subplot(4, nr_of_weights, 4)\n plt.imshow((pred_variances[currently_selected_image, ...].detach().cpu().numpy())**0.5-(gt_variances[currently_selected_image,...].detach().cpu().numpy())**0.5)\n plt.axis('image')\n plt.axis('off')\n if display_colorbar:\n plt.colorbar()\n\n # plot the ground truth weights\n for nw in range(nr_of_weights):\n plt.subplot(4,nr_of_weights,nr_of_weights+1+nw)\n plt.imshow(gt_weights[currently_selected_image, nw, ...].detach().cpu().numpy(),clim=(0.0,1.0))\n plt.axis('image')\n plt.axis('off')\n if display_colorbar:\n plt.colorbar()\n\n # plot the computed weights\n for nw in range(nr_of_weights):\n plt.subplot(4, nr_of_weights, 2*nr_of_weights + 1 + nw)\n plt.imshow(weights[currently_selected_image, nw, ...].detach().cpu().numpy(),clim=(0.0,1.0))\n plt.axis('image')\n plt.axis('off')\n if display_colorbar:\n plt.colorbar()\n\n # plot the computed weights\n for nw in range(nr_of_weights):\n plt.subplot(4, nr_of_weights, 3 * nr_of_weights + 1 + nw)\n plt.imshow(weights[currently_selected_image, nw, ...].detach().cpu().numpy()-gt_weights[currently_selected_image, nw, ...].detach().cpu().numpy(), clim=(-1.0, 1.0))\n plt.axis('image')\n plt.axis('off')\n if display_colorbar:\n plt.colorbar()\n\n #plt.tight_layout(pad=0.0, w_pad=0.0, h_pad=0.0)\n plt.show()\n\nprint('Finished Training')\n\nif not only_evaluate:\n print('Saving network state dict to {}'.format(save_network_state_dict_file))\n torch.save(reconstruction_unet.state_dict(),save_network_state_dict_file)\n","repo_name":"uncbiag/pregis_net","sub_path":"mermaid/image_clustering/supervised_weight_learning.py","file_name":"supervised_weight_learning.py","file_ext":"py","file_size_in_byte":16226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"41634229561","text":"\"\"\"\r\nTest suite to check compilance with PEP 247, the standard API\r\nfor hashing algorithms\r\n\"\"\"\r\n\r\nimport warnings\r\nwarnings.filterwarnings('ignore', 'the md5 module is deprecated.*',\r\n DeprecationWarning)\r\nwarnings.filterwarnings('ignore', 'the sha module is deprecated.*',\r\n DeprecationWarning)\r\n\r\nimport hmac\r\nimport md5\r\nimport sha\r\n\r\nimport unittest\r\nfrom test import test_support\r\n\r\nclass Pep247Test(unittest.TestCase):\r\n\r\n def check_module(self, module, key=None):\r\n self.assertTrue(hasattr(module, 'digest_size'))\r\n self.assertTrue(module.digest_size is None or module.digest_size > 0)\r\n\r\n if not key is None:\r\n obj1 = module.new(key)\r\n obj2 = module.new(key, 'string')\r\n\r\n h1 = module.new(key, 'string').digest()\r\n obj3 = module.new(key)\r\n obj3.update('string')\r\n h2 = obj3.digest()\r\n else:\r\n obj1 = module.new()\r\n obj2 = module.new('string')\r\n\r\n h1 = module.new('string').digest()\r\n obj3 = module.new()\r\n obj3.update('string')\r\n h2 = obj3.digest()\r\n\r\n self.assertEqual(h1, h2)\r\n\r\n self.assertTrue(hasattr(obj1, 'digest_size'))\r\n\r\n if not module.digest_size is None:\r\n self.assertEqual(obj1.digest_size, module.digest_size)\r\n\r\n self.assertEqual(obj1.digest_size, len(h1))\r\n obj1.update('string')\r\n obj_copy = obj1.copy()\r\n self.assertEqual(obj1.digest(), obj_copy.digest())\r\n self.assertEqual(obj1.hexdigest(), obj_copy.hexdigest())\r\n\r\n digest, hexdigest = obj1.digest(), obj1.hexdigest()\r\n hd2 = \"\"\r\n for byte in digest:\r\n hd2 += '%02x' % ord(byte)\r\n self.assertEqual(hd2, hexdigest)\r\n\r\n def test_md5(self):\r\n self.check_module(md5)\r\n\r\n def test_sha(self):\r\n self.check_module(sha)\r\n\r\n def test_hmac(self):\r\n self.check_module(hmac, key='abc')\r\n\r\ndef test_main():\r\n test_support.run_unittest(Pep247Test)\r\n\r\nif __name__ == '__main__':\r\n test_main()\r\n","repo_name":"google/google-ctf","sub_path":"third_party/edk2/AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_pep247.py","file_name":"test_pep247.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","stars":4153,"dataset":"github-code","pt":"77"}
+{"seq_id":"19682452327","text":"# Implement integer exponentiation. That is, implement the pow(x, y) function, where x and y are integers and returns x^y.\n#\n# Do this faster than the naive method of repeated multiplication.\n#\n# For example, pow(2, 10) should return 1024.\ndef pow(base, exp):\n\t# Worst case scenario is where there's a very large number as the exponent.\n\t# We'll want to minimize this by reducing the size of the exponent until it's 1.\n\t# We know that halving the exponent will result in squaring the current base,\n\t# so it reduces down to O(N) time complexity.\n\t#\n\t# Ex.: 1^64 = 1, N = 64\n\t# Brute force = O(64) = O(1^N)\n\t# Optimal\t = O(6) = O(1(2^6))\n\t#\n\t# When we encounter an odd, we update the result with the current base. Otherwise,\n\t# we square the current base.\n\t# 2^5 => (res, base, exp) => (2, 4, 2) => (2, 16, 1) => (32, 16, 0)\n\n\t# If negative exponent, we simply just need to inverse the base.\n\tif exp < 0:\n\t\tbase = (1.0 / base)\n\t\texp *= -1\n\n\tres = 1.0\n\n\twhile exp:\n\t\tif exp & 1:\n\t\t\tres *= base\n\n\t\tbase *= base\n\t\texp >>= 1\n\n\treturn res\n\n\nprint(pow(2, 5))\nprint(pow(2, -5))\n","repo_name":"JulianDomingo/interviews","sub_path":"dcp/12_26_18_pow.py","file_name":"12_26_18_pow.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"5027407535","text":"import re\nimport pandas as pd\n\ndef preprocess(data):\n lines = data.strip().split('\\n')\n\n dates = []\n messages = []\n\n pattern = r\"(\\d{1,2}/\\d{1,2}/\\d{2}), (\\d{1,2}:\\d{1,2})\\s(AM|PM) - ([^:]+):\\s(.+)\"\n for line in lines:\n match = re.match(pattern, line)\n if match:\n dates.append(match.group(1) + ', ' + match.group(2) + ' ' + match.group(3))\n messages.append(match.group(4) + ': ' + match.group(5))\n\n df = pd.DataFrame({'user_message': messages, 'message_date': dates})\n df['message_date'] = pd.to_datetime(df['message_date'], format='%m/%d/%y, %I:%M %p')\n df.rename(columns={'message_date': 'date'}, inplace=True)\n users = []\n messages = []\n for message in df['user_message']:\n entry = re.split('([\\w\\W]+?):\\s', message)\n if entry[1:]: # user name\n users.append(entry[1])\n messages.append(\" \".join(entry[2:]))\n else:\n users.append('group_notification')\n messages.append(entry[0])\n df['only_date']=df['date'].dt.date\n df['user'] = users\n df['message'] = messages\n df=df.drop(\"user_message\",axis=1)\n df['date'] = pd.to_datetime(df['date'])\n df[\"year\"]=df[\"date\"].dt.year\n df['month_num']=df['date'].dt.month\n df[\"month_name\"]=df[\"date\"].dt.month_name()\n df[\"day\"]=df[\"date\"].dt.day\n df['day_name']=df['date'].dt.day_name()\n df[\"hour\"]=df[\"date\"].dt.hour\n df[\"minute\"]=df[\"date\"].dt.minute\n df['message'] = df['message'].str.replace('Media Omitted', '').str.replace('Omitted Media', '')\n\n period=[]\n for hour in df[[\"day_name\",'hour']]['hour']:\n if hour==23:\n period.append(str(hour) + \"_\" + str('00'))\n elif hour ==0:\n period.append(str('00') + \"_\" + str(hour+1))\n else:\n period.append(str(hour) + \"_\" + str(hour+1))\n df['period']=period\n\n \n \n\n \n return df\n","repo_name":"arzzahid66/whatsapp_chat_Analyzer","sub_path":"preprocesser.py","file_name":"preprocesser.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"15460010322","text":"import numpy as np\nimport cv2\nimport socket\n\nUDP_IP = \"127.0.0.1\"\nUDP_PORT = 8888\nBUF_LEN=65540\nPACK_SIZE=4096\n\n\nsock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\nsock.bind((UDP_IP,UDP_PORT))\nwhile True:\n\n data,client_address= sock.recvfrom(512)\n num = ord(data[0])\n tmp=\"\"\n for i in range(num):\n data,_ = sock.recvfrom(BUF_LEN)\n tmp+=data\n if(len(data)!=PACK_SIZE):\n print(\"Received unexpected size pack:\"+str(len(data)))\n continue\n file_bytes = np.asarray(bytearray(tmp), dtype=np.uint8)\n image = cv2.imdecode(file_bytes, 0)\n cv2.imshow(\"recv\",image)\n cv2.waitKey(10)\n r = 'Receieve'\n sock.sendto(r.encode(),client_address)","repo_name":"GuoxianSong/UDP_win_py","sub_path":"scrip.py","file_name":"scrip.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"42699380831","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals, absolute_import\n\nfrom django.db import models\n\nfrom ..core.api import VkApi\nfrom .helpers import DbCredentials, admincolumn\n\n\nclass Account(models.Model):\n updated = models.DateTimeField(auto_now=True)\n uid = models.BigIntegerField(primary_key=True)\n screen_name = models.CharField(blank=True, max_length=200, unique=True)\n first_name = models.CharField(blank=True, max_length=200)\n last_name = models.CharField(blank=True, max_length=200)\n groups = models.ManyToManyField('Group', blank=True, through='Subscription')\n\n def get_link(self):\n return VkApi.user_link(self.uid, self.screen_name) if self.uid else None\n\n def __unicode__(self):\n return self.name or self.get_link() or '(новый аккаунт)'\n\n class Meta:\n verbose_name = 'аккаунт'\n verbose_name_plural = 'аккаунты'\n\n\nclass ManageredAccount(Account):\n access_token = models.CharField(max_length=255)\n is_default = models.BooleanField('', default=False)\n\n def has_access_token(self):\n return bool(self.access_token)\n\n @classmethod\n def get_default(cls):\n return cls.objects.filter(is_default=True).first()\n\n def get_vk_api(self):\n return VkApi(DbCredentials(self))\n\n def update(self):\n api = self.get_vk_api()\n fields = (\n 'first_name',\n 'last_name',\n 'screen_name',\n )\n info = api.self_info(fields)\n for k in fields:\n setattr(self, k, info['k'])\n self.uid = info['id']\n for data in api.user_groups((\n 'name',\n 'screen_name'\n 'type',\n )):\n group, _created = Group.objects.update_or_create(\n gid=data['id'],\n defaults=dict(\n name=data['name'],\n screen_name=data['screen_name'],\n type=Group.from_vk_type(data['type']),\n )\n )\n Subscription.objects.update_or_create(\n account=self,\n group=group,\n defaults=dict(\n is_admin=data['is_admin'],\n is_member=data['is_member'],\n ),\n )\n\n def save(self, *args, **kwargs):\n if self.access_token:\n self.update()\n other_defaults = ManageredAccount.objects.filter(is_default=True)\n if not other_defaults.exists():\n self.is_default = True\n elif self.pk and self.is_default and other_defaults.exists():\n other_defaults.update(is_default=False)\n super(ManageredAccount, self).save(*args, **kwargs)\n\n class Meta:\n verbose_name = 'управляемый аккаунт'\n verbose_name_plural = 'управляемые аккаунты'\n\n\nclass Group(models.Model):\n updated = models.DateTimeField(auto_now=True)\n gid = models.BigIntegerField(primary_key=True)\n screen_name = models.CharField(blank=True, max_length=200, unique=True)\n name = models.CharField(u'название', blank=True, max_length=200)\n\n TYPE_GROUP = 1\n TYPE_PAGE = 2\n TYPE_EVENT = 3\n TYPE_CHOICES = (\n (TYPE_GROUP, 'группа'),\n (TYPE_PAGE, 'публичная страница'),\n (TYPE_EVENT, 'мероприятие'),\n )\n _vk_types = {\n 'group': TYPE_GROUP,\n 'page': TYPE_PAGE,\n 'event': TYPE_EVENT,\n }\n type = models.SmallIntegerField(choices=TYPE_CHOICES)\n\n def to_vk_type(self):\n return {v: k for k,v in self._vk_types.items()}\n\n @classmethod\n def from_vk_type(cls, k):\n return cls._vk_types[k]\n\n @admincolumn('тип')\n def type_description(self):\n return dict(self.TYPE_CHOICES)[self.type]\n\n def get_link(self):\n return VkApi.group_link(\n self.gid,\n self.to_vk_type(),\n self.screen_name,\n ) if self.gid else None\n\n @admincolumn('админ')\n def get_default_admin(self):\n return self.subscriptions.filter(is_admin=True).first().account\n\n def __unicode__(self):\n return self.name or self.get_link() or '(новая группа)'\n\n class Meta:\n verbose_name = 'группа'\n verbose_name_plural = 'группы'\n\n\nclass Subscription(models.Model):\n group = models.ForeignKey(Group, related_name='subscriptions')\n account = models.ForeignKey(Account)\n updated = models.DateTimeField(auto_now=True)\n is_admin = models.BooleanField(default=False)\n is_member = models.BooleanField(default=True)\n\n ADMIN_LEVEL_MODER = 1\n ADMIN_LEVEL_EDITOR = 2\n ADMIN_LEVEL_ADMIN = 3\n ADMIN_LEVEL_CHOICES = (\n (ADMIN_LEVEL_MODER, 'модератор'),\n (ADMIN_LEVEL_EDITOR, 'редактор'),\n (ADMIN_LEVEL_ADMIN, 'админ'),\n )\n admin_level = models.SmallIntegerField(null=True)\n\n @admincolumn('роль')\n def admin_level_description(self):\n return dict(self.ADMIN_LEVEL_CHOICES)[self.admin_level]\n\n class Meta:\n verbose_name = 'статус'\n verbose_name_plural = 'статусы'\n","repo_name":"shantilabs/vkscriptz","sub_path":"djvk/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5177,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"77"}
+{"seq_id":"26503366922","text":"# import l293d.driver as l293d\n# import time\n# import RPi.GPIO as GPIO\n# GPIO.setwarnings(False)\n# GPIO.setmode(GPIO.BOARD)\n\n# motor1 = l293d.DC(22,18,16)\n# try:\n # while True:\n # motor1.clockwise()\n # time.sleep(1)\n# except KeyboardInterrupt:\n # print(\"Crtl C\")\n # GPIO.cleanup()\n # l293d.cleanup()\n \n \n \nimport RPi.GPIO as GPIO\nimport time\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BOARD)\n\nGPIO.setup(22,GPIO.OUT)\nGPIO.setup(18,GPIO.OUT)\nGPIO.setup(16,GPIO.OUT)\npwm=GPIO.PWM(22,100)\npwm.start(0)\nGPIO.output(18,GPIO.LOW)\nGPIO.output(16,GPIO.HIGH)\nGPIO.output(22,True)\n\ntry:\n while True:\n #forward\n \n pwm.ChangeDutyCycle(75)\n time.sleep(5)\n pwm.ChangeDutyCycle(10)\n print('ok') \n time.sleep(5)\n GPIO.output(22,False)\n GPIO.output(16,GPIO.LOW)\n GPIO.output(18,GPIO.HIGH)\n GPIO.output(22,True)\n time.sleep(15)\n print('ok') \n # GPIO.output(channel[2],True)\n # GPIO.output(channel[1],False)\n # pwm.ChangeDutyCycle(75)\n # GPIO.output(channel[0],False)\n # time.sleep(1)\n \n\nexcept KeyboardInterrupt:\n print(\"Crtl C pressed\")\n GPIO.cleanup()\n pwm.stop()\n \n\n \n","repo_name":"acn55/LTA_Swarm","sub_path":"finalprogram/motor_testing/motordrive.py","file_name":"motordrive.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"17699459594","text":"\"\"\"\nDriver implementation of project. Trains and evaluates models.\n\nauthor: William Tong (wlt2115@columbia.edu)\ndate: February 12, 2019\n\"\"\"\n\nfrom pathlib import Path\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\n\nfrom deep_learning import model\nfrom deep_learning import util\n\nLOG_DIR = Path(r'/home/grandpaa/workspace/PyCharm/deep_learning/logs')\n\nRUN_NAME = 'test'\nTB_DIR = LOG_DIR / 'tensorboard' / RUN_NAME\nWL_DIR = LOG_DIR / 'wang_landau' / RUN_NAME\n\n\ndef _train_model(model: tf.keras.models.Model,\n data: np.ndarray,\n labels: np.ndarray,\n epochs: int = 100,\n val_data: np.ndarray = None,\n val_labels: np.ndarray = None) -> 'Model':\n kwargs = {}\n if val_data is not None and val_labels is not None:\n kwargs['validation_data'] = (val_data, val_labels)\n\n tensorboard = tf.keras.callbacks.TensorBoard(log_dir=TB_DIR,\n histogram_freq=2)\n kwargs['callbacks'] = [tensorboard]\n\n model.fit(data, labels,\n epochs=epochs, batch_size=32,\n **kwargs)\n return model\n\n\n# Data configuration and prep\n# domain = np.array([[0, 50],\n# [0, 50],\n# [0, 50]])\ndomain = (-10, 10)\n#data_range = (0, 10)\ndata_range = (-12, 0)\npeaks = [1, 5, 10]\nlocs = np.array([[-5],\n [0],\n [5]])\n\nshekel = util.shekel(peaks, locs, negate=True)\n\ndata = np.arange(*domain, 0.005)\nlabels = np.array([shekel(x) for x in data])\nplt.subplot(121)\nplt.plot(data, labels, 'ko')\nplt.subplot(122)\nplt.hist(labels, bins=120, orientation='horizontal')\nplt.show()\n\nval_data = _rand_sample(len(data), domain)\nval_labels = np.array([shekel(x) for x in val_data])\n\npred_data = _rand_sample(len(data), domain)\npred_labels = np.array([shekel(x) for x in pred_data])\n\n\nif __name__ == '__main__':\n # Model training\n simple_wl = model.simple_wl_model(1)\n simple_wl.compile(optimizer=tf.train.AdamOptimizer(0.001),\n loss='mse',\n metrics=['mae'])\n\n _train_model(simple_wl, epochs=80,\n data=data, labels=labels,\n val_data=val_data, val_labels=val_labels\n )\n inferred_labels = simple_wl.predict(pred_data)\n\n plt.plot(pred_data, pred_labels, 'ko')\n plt.plot(pred_data, inferred_labels, 'ro')\n plt.savefig(str(TB_DIR / 'final_comparison.png'))\n plt.show()\n\n # Wang-Landau magic\n # def energy_func(x: float) -> float:\n # pred = simple_wl.predict(np.array([x]))\n # return pred[0][0]\n\n energy_func = model.simple_classify\n\n freqs, hist = util.wang_landau(energy_func,\n domain=domain,\n energy_range=range(10),\n max_iterations=50000,\n check_every=200,\n save_every=2000,\n log_dir=WL_DIR,\n flatness=0.95,\n step_size=1)\n\n bins = list(freqs.keys())\n values = list(freqs.values())\n print(bins)\n print(values)\n\n # plt.subplot(141)\n # plt.title(\"Neural Net function\")\n # plt.plot(pred_data, pred_labels, 'ko')\n # # plt.plot(pred_data, inferred_labels, 'ro')\n # plt.ylim(data_range)\n\n plt.subplot(121)\n plt.title(\"ln of energy density\")\n print(bins)\n plt.hist(bins, weights=values, bins=len(bins), orientation='horizontal')\n plt.ylim(data_range)\n\n plt.subplot(122)\n max_val = max(values)\n norm_values = [np.e ** (value - max_val) for value in values]\n plt.title(\"Normalized energy densities\")\n plt.hist(bins, weights=norm_values, bins=len(bins), orientation='horizontal')\n plt.ylim(data_range)\n\n # plt.subplot(144)\n # hist_values = list(hist.values())\n # plt.title(\"visited states\")\n # plt.hist(bins, weights=hist_values, bins=len(bins), orientation='horizontal')\n # plt.ylim(data_range)\n\n # TODO: implement final save\n plt.show()\n","repo_name":"Columbia-CRIS/Intern","sub_path":"Understanding Deep Learning/william_stuff/deep_learning/deep_learning/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4141,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"34705230718","text":"#!/usr/bin/env python\n\nimport os\nfrom subprocess import *\nfrom time import sleep\nfrom shlex import split\nimport sys\n\nclass MutualAttestationTestCase():\n socat_process = None\n server_process = None\n client_process = None\n \n def setup(self):\n self.socat_process = Popen(\"exec socat -t10 TCP-LISTEN:1234,bind=127.0.0.1,reuseaddr,fork,range=127.0.0.0/8 UNIX-CLIENT:/var/run/aesmd/aesm.socket\", shell=True)\n sleep(1)\n assert self.socat_process.poll() == None\n \n def teardown(self):\n if self.socat_process:\n self.socat_process.terminate()\n self.socat_process = None\n if self.server_process:\n if self.server_process.poll() == None:\n self.server_process.terminate()\n self.server_process = None\n if self.client_process:\n if self.client_process.poll() == None:\n self.client_process.terminate()\n self.client_process = None\n \n def verify(self):\n pass\n def main(self):\n cmd = 'exec deps/graphene/Runtime/pal-Linux-SGX wolfssl-ssl-server-mutual'\n self.server_process = Popen(cmd, shell=True)\n sleep(10)\n\n cmd = 'exec deps/graphene/Runtime/pal-Linux-SGX wolfssl-client-mutual'\n self.client_process = Popen(cmd, shell=True)\n for _ in range(10):\n if self.client_process.poll() != None:\n break\n sleep(1)\n \n assert (self.client_process.poll() == 0)\n\nclass GrapheneSGXTestCase():\n socat_process = None\n server_process = None\n \n def setup(self):\n self.socat_process = Popen(\"exec socat -t10 TCP-LISTEN:1234,bind=127.0.0.1,reuseaddr,fork,range=127.0.0.0/8 UNIX-CLIENT:/var/run/aesmd/aesm.socket\", shell=True)\n sleep(1)\n assert self.socat_process.poll() == None\n \n def teardown(self):\n if self.socat_process:\n self.socat_process.terminate()\n if self.server_process:\n if self.server_process.poll() == None:\n self.server_process.terminate()\n self.server_process = None\n\n def main(self):\n for server in ['wolfssl-ssl-server', 'mbedtls-ssl-server'] :\n cmd = \"exec deps/graphene/Runtime/pal-Linux-SGX ./%s\" % (server)\n self.server_process = Popen(cmd, shell=True)\n sleep(10)\n assert self.server_process.poll() == None\n\n for client in ['mbedtls-client', 'wolfssl-client', 'openssl-client -p 11111'] :\n check_call(split('./' + client))\n\n self.server_process.terminate()\n for i in range(5):\n if self.server_process.poll():\n break\n sleep(1)\n sigterm = 15\n assert self.server_process.poll() == sigterm\n","repo_name":"cloud-security-research/sgx-ra-tls","sub_path":"tests/00_graphene_server_client.py","file_name":"00_graphene_server_client.py","file_ext":"py","file_size_in_byte":2832,"program_lang":"python","lang":"en","doc_type":"code","stars":111,"dataset":"github-code","pt":"77"}
+{"seq_id":"74450072247","text":"import os\nimport re\nimport sys\nimport zipfile\nimport tarfile\nimport platform\nimport subprocess\n\n\nthis_dir = os.path.abspath(os.path.dirname(__file__)) + \"/\"\ndist_dir = this_dir + \"dist/\"\n\n\nwith open(\n os.path.join(this_dir, \"..\", \"pyzo\", \"__init__.py\"), \"rt\", encoding=\"utf-8\"\n) as fh:\n __version__ = re.search(r\"__version__ = \\\"(.*?)\\\"\", fh.read()).group(1)\n\nbitness = \"32\" if sys.maxsize <= 2**32 else \"64\"\n\nosname = os.getenv(\"PYZO_OSNAME\", \"\")\nif osname:\n pass\nelif sys.platform.startswith(\"linux\"):\n osname = \"linux_\" + platform.machine()\nelif sys.platform.startswith(\"win\"):\n osname = f\"win{bitness}\"\nelif sys.platform.startswith(\"darwin\"):\n osname = \"macos_\" + platform.machine()\nelse:\n raise RuntimeError(\"Unknown platform\")\n\nbasename = f\"pyzo-{__version__}-{osname}\"\n\n\n## Utils\n\n\ndef package_tar_gz():\n print(\"Packing up into tar.gz ...\")\n\n oridir = os.getcwd()\n os.chdir(dist_dir)\n try:\n with tarfile.open(basename + \".tar.gz\", \"w|gz\") as tf:\n tf.add(\"pyzo\", arcname=\"pyzo\")\n finally:\n os.chdir(oridir)\n\n\ndef package_zip():\n print(\"Packing up into zip ...\")\n\n dirname1 = \"pyzo.app\" if sys.platform.startswith(\"darwin\") else \"pyzo\"\n dirname2 = dirname1\n\n zf = zipfile.ZipFile(\n os.path.join(dist_dir, basename + \".zip\"), \"w\", compression=zipfile.ZIP_DEFLATED\n )\n with zf:\n for root, dirs, files in os.walk(os.path.join(dist_dir, dirname1)):\n for fname in files:\n filename1 = os.path.join(root, fname)\n filename2 = os.path.relpath(filename1, os.path.join(dist_dir, dirname1))\n filename2 = os.path.join(dirname2, filename2)\n zf.write(filename1, filename2)\n\n\ndef package_inno_installer():\n print(\"Packing up into exe installer (via Inno Setup) ...\")\n\n exes = [\n r\"c:\\Program Files (x86)\\Inno Setup 5\\ISCC.exe\",\n r\"c:\\Program Files (x86)\\Inno Setup 6\\ISCC.exe\",\n ]\n for exe in exes:\n if os.path.isfile(exe):\n break\n else:\n raise RuntimeError(\"Could not find Inno Setup exe\")\n\n # Set inno file\n innoFile1 = os.path.join(this_dir, \"installerBuilderScript.iss\")\n innoFile2 = os.path.join(this_dir, \"installerBuilderScript2.iss\")\n with open(innoFile1, \"rb\") as f:\n text = f.read().decode()\n text = text.replace(\"X.Y.Z\", __version__).replace(\"64\", bitness)\n if bitness == \"32\":\n text = text.replace(\"ArchitecturesInstallIn64BitMode = x64\", \"\")\n with open(innoFile2, \"wb\") as f:\n f.write(text.encode())\n try:\n subprocess.check_call([exe, \"/Qp\", innoFile2], cwd=dist_dir)\n finally:\n os.remove(innoFile2)\n\n\ndef package_dmg():\n print(\"Packing up into DMG ...\")\n\n app_dir = \"pyzo.app\"\n dmg_file = basename + \".dmg\"\n\n cmd = [\"hdiutil\", \"create\"]\n cmd.extend([\"-srcfolder\", app_dir])\n cmd.extend([\"-volname\", \"pyzo\"])\n cmd.extend([\"-format\", \"UDZO\"])\n cmd.extend([\"-fs\", \"HFSX\"])\n # cmd.extend([\"-uid\", \"99\"]) # who ever is mounting\n # cmd.extend([\"-gid\", \"99\"]) # who ever is mounting\n cmd.extend([\"-mode\", \"555\"]) # readonly\n cmd.append(\"-noscrub\")\n cmd.append(dmg_file)\n\n subprocess.check_call(cmd, cwd=dist_dir)\n\n\n## Build\n\n\nif sys.platform.startswith(\"linux\"):\n package_zip()\n package_tar_gz()\n\nif sys.platform.startswith(\"win\"):\n package_zip()\n if bitness == \"64\":\n # Note: for some reason the 32bit installer is broken. Ah well, the zip works.\n package_inno_installer()\n\nif sys.platform.startswith(\"darwin\"):\n package_zip()\n package_dmg()\n","repo_name":"pyzo/pyzo","sub_path":"freeze/pyzo_package.py","file_name":"pyzo_package.py","file_ext":"py","file_size_in_byte":3596,"program_lang":"python","lang":"en","doc_type":"code","stars":265,"dataset":"github-code","pt":"77"}
+{"seq_id":"37446703870","text":"#Includes\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cmath\nimport csv\n\nfrom matplotlib import rc\nfrom pylab import *\nfrom scipy.optimize import fsolve\nfrom mpl_toolkits.axes_grid.axislines import SubplotZero\n\nimport matplotlib.cm as cm\nfrom matplotlib.colors import LogNorm\n\n\n\nimport sys\nsys.path.append('/home/preston/Desktop/Programming/p_lib/python_lib/misc/')\nsys.path.append('/home/preston/Desktop/Programming/p_lib/python_lib/plot/')\nsys.path.append('/home/preston/Desktop/Programming/p_lib/python_lib/data_transform/')\nsys.path.append('/home/preston/Desktop/Programming/p_lib/python_lib/dtw/')\n\nimport p_plot\nimport Maze_Solver as ms\nimport Character as ch\nimport Character_Functions as chf\nimport data_transform\nimport pDTW\n\ncharacter_file_directory = '/home/preston/Desktop/Programming/datasci/projects/digit_recognizer/data/'\ncharacter_train_file_name = 'short_train.csv'\ncharacter_test_file_name = 'test.csv'\n\ntrain_character_list = chf.load_characters_kaggle_format(character_file_directory +\\\n character_train_file_name, 'train')\n\n\nzero_list = []\none_list = []\ntwo_list = []\nthree_list = []\nfour_list = []\nfive_list = []\nsix_list = []\nseven_list = []\neight_list = []\nnine_list = []\n\nfives = 0\ni = 0\nwhile fives < 2:\n\t\n\tif train_character_list[i]._classification == 5:\n\t\t\n\t\t\n\n\t\tif fives == 0:\n\t\t\tfive_0 = train_character_list[i]\n\t\t\tfives = fives + 1\n\t\t\n\n\t\telif fives == 1:\n\t\t\tfive_1 = train_character_list[i]\n\t\t\tif ms.walk_around_ccw(five_1._data_bw).shape[0] == ms.walk_around_ccw(five_0._data_bw).shape[0]:\n\t\t\t\tfives = fives + 1\n\t\t\t\n\t\t\n\ti = i + 1\n\n\n\n\t\t\nfive_0._perimeter_path = ms.walk_around_ccw(five_0._data_bw)\nfive_0._xseries = ms.convert_path_to_xseries(five_0._perimeter_path)\n\nfive_1._perimeter_path = ms.walk_around_ccw(five_1._data_bw)\nfive_1._xseries = ms.convert_path_to_xseries(five_1._perimeter_path)\n\n\n\nfive_0_x = five_0._xseries\nfive_0_x = data_transform.stretch_data_x(five_0_x)\nfive_0_x = data_transform.normalize_data(five_0_x)\n\nfive_1_x = five_1._xseries\nfive_1_x = data_transform.stretch_data_x(five_1_x)\nfive_1_x = data_transform.normalize_data(five_1_x)\n\n\n\ndistance_matrix_x = pDTW.get_distance_matrix_DTW(five_0_x, five_1_x)\n\n\n\ncost_matrix_x = pDTW.get_cost_matrix(distance_matrix_x)\npath_x = pDTW.get_warp_path(cost_matrix_x)\n\np_plot.save_plot_matrix_line(distance_matrix_x, path_x)\np_plot.save_plot_matrix_line(cost_matrix_x, path_x)\n\noffset_1 = 1\n\nfor i in range(five_1_x.shape[0]):\n\tfive_1_x[i][1] = five_1_x[i][1] + offset_1\n\nfig = plt.figure()\nfor i in range(path_x.shape[0]):\n\tx0 = five_0_x[path_x[i][0]][0]\n\tx1 = five_1_x[path_x[i][1]][0]\n\ty0 = five_0_x[path_x[i][0]][1]\n\ty1 = five_1_x[path_x[i][1]][1]\n\tplt.plot((x0, x1), (y0, y1), lw = 2)\n\nplt.plot(five_0_x[:,0], five_0_x[:,1], c = (0,0,0), lw = 2)\nplt.plot(five_1_x[:,0], five_1_x[:,1], c = (0,0,0), lw = 2)\n\nplt.show()\n\n\n\n","repo_name":"tphinkle/kaggle_digit_recognizer","sub_path":"dtw_plot.py","file_name":"dtw_plot.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"2709547625","text":"__author__ = 'Connor'\n\nclass Solution:\n # @return an integer\n def numTrees(self, n):\n if n == 0 or n == 1:\n return 1\n ans = 0\n for i in range(n):\n ans += self.numTrees(i) * self.numTrees(n-1-i)\n return ans\n\nif __name__ == '__main__':\n so = Solution()\n print(so.numTrees(3))","repo_name":"buptconnor/myleet","sub_path":"solved/P96_numTrees.py","file_name":"P96_numTrees.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"7395664772","text":"#Import objects\nimport os\nimport csv\n\n#Set the path for the csv file\nfile_path = os.path.join('..', 'Resources', 'budget_data.csv')\n\n#Initiate lists\nlist_month = []\nlist_profit_loss = []\nlist_profit_change = []\n\n#Initiate variables\ntotal_months = 0\ntotal_profit_loss = 0\navg_change = 0\ntotal_changes = 0\ngreatest_increase = 0\ngreatest_decrease = 0\ni = 0\n\n#Open and read csv file\nwith open(file_path,newline=\"\",encoding=\"utf8\") as budget_data:\n budget = csv.reader(budget_data,delimiter=',')\n\n #Skip the header\n budget_header = next(budget)\n\n #Sum the profit_loss values and create separate lists for each row\n for row in budget:\n\n total_profit_loss += int(row[1])\n total_months += 1\n\n list_month.append(row[0])\n list_profit_loss.append(int(row[1]))\n\n #Loop through the lists\n while i < len(list_month):\n\n if ((i+1) < len(list_month)):\n\n profit_diff = (list_profit_loss[i+1]) - (list_profit_loss[i])\n\n #Create a list of the profit/loss changes\n list_profit_change.append(profit_diff)\n\n #Determine if the difference is the greatest increase or decrease\n if profit_diff > greatest_increase:\n greatest_increase = profit_diff\n greatest_increase_month = list_month[i+1]\n if profit_diff < greatest_decrease:\n greatest_decrease = profit_diff\n greatest_decrease_month = list_month[i+1]\n\n i += 1\n\n #Loop through profit change list to determine thw average\n i = 0\n while i < len(list_profit_change):\n total_changes += list_profit_change[i]\n i += 1\n\n avg_change = total_changes / len(list_profit_change)\n\n#Display the results on the terminal\nprint(f'---text')\nprint(f'Financial Analysis')\nprint(f'--------------------------------------')\nprint(f'Total Months: {total_months}')\nprint(f'Total: ${total_profit_loss}')\nprint(f'Average Change: ${round(avg_change,2)}')\nprint(f'Greatest Increase in Profits: {greatest_increase_month} (${greatest_increase})')\nprint(f'Greatest Decrease in Profits: {greatest_decrease_month} (${greatest_decrease})')\nprint(f'---')\n\n\n#Write the results to text file\nBudget_File = open('Profit_Loss.txt','a')\n\nBudget_File.write('---text \\n')\nBudget_File.write('Financial Analysis \\n')\nBudget_File.write('-------------------------------------- \\n')\nBudget_File.write(f'Total Months: {total_months} \\n')\nBudget_File.write(f'Total: ${total_profit_loss} \\n')\nBudget_File.write(f'Average Change: ${round(avg_change,2)} \\n')\nBudget_File.write(f'Greatest Increase in Profits: {greatest_increase_month} (${greatest_increase}) \\n')\nBudget_File.write(f'Greatest Decrease in Profits: {greatest_decrease_month} (${greatest_decrease}) \\n')\nBudget_File.write(f'--- \\n')\n\n\nBudget_File.close()\n","repo_name":"deirdrebclark/python-challenge","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"22882777563","text":"# 전형적인\ntest_list = ['one', 'two', 'three']\nfor i in test_list:\n print(i)\n\n# 다양한\na = [(1, 2), (3, 4), (5, 6)]\nfor (first, last) in a:\n print(first + last)\n\n# 응용\n# 총 5명의 학생이 시험을 보았는데 시험 점수가 60점이 넘으면 합격이고 그렇지 않으면 불합격이다. 합격인지 불합격인지 결과를 보여 주시오.\nmarks = [90, 25, 67, 45, 80]\nnumber = 0\nfor mark in marks:\n number = number + 1\n if mark >= 60:\n print(f\"{number}번 학생은 합격입니다.\")\n else:\n print(f\"{number}번 학생은 불합격입니다.\")\n\n# 응용2 : for문과 continue\nfor mark in marks:\n number = number + 1\n if mark < 60:\n continue\n print(f\"{number}번 학생 축하합니다. 합격입니다.\")\n\n# range 함수\nadd = 0\nfor i in range(1, 11):\n add = add + i\nprint(add)\n\n# 응용3 : for문과 range 함수\nfor number in range(len(marks)):\n if marks[number] < 60:\n continue\n print(f\"{number}번 학생 축하합니다. 합격입니다.\")\n\n# 응용4 : 구구단\nfor i in range(2, 10):\n for j in range(1, 10):\n print(i * j, end=\" \")\n print('')\n\nresult = [x * y for x in range(2, 10)\n for y in range(1, 10)]\nprint(result)","repo_name":"joohy97/Jump-to-Python","sub_path":"3장/03-3-For.py","file_name":"03-3-For.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"1779808192","text":"\n\n\n\n\n\n\n\n\n\n\n\n\n# time for data analysis on this new dataset\n# first check the hypothesis. Plot the number of influences\n\n# 2d histogram\nsns.histplot(set_df, x=\"num_downstream_influences\", y=\"citations\")\nax.set_ylim(0, 100)\n\n\n\n## need to generate dataframe for analysis based on this data.\n## going for: paper_id, word, is_title_word, # downstream papers, # downstream influences,\n## influences per downstream paper, # unique words, # upstream papers, percent unique contribution\n\n\n\n\n# largely expecting that is_title_word means the average number of downstream influences is higher\n\n\n\n\n\n\n\n\n# so how does this work...\n# we need to come up with a temporal order\n\n\n\n# going to randomly sample down to 5000 to see what happens\n\n## too big, try reading from file\n\nalt.data_transformers.enable('json')\n\n# now let's see what's up. Let's do a double distribution plot of similarities.\n# two dsns..\nc1 = alt.Chart(melted_df).mark_area(\n opacity=0.5,\n interpolate='step'\n).encode(\n alt.X('similarity:Q', bin=alt.Bin(maxbins=100)),\n alt.Y('count()', stack=None),\n alt.Color('geo_dist:N')\n).properties(\n title='Overlapping Histograms from Tidy/Long Data'\n)\naltair_viewer.display(c1)\n\n\n\n## PICK UP HERE\n\n\nlen(words_to_compare)\n\n# See a distribution of counter values\nsource = pd.DataFrame({'word_freq': words_to_compare.values()})\n\nbase = alt.Chart(source)\n\nbar = base.mark_bar().encode(\n x=alt.X('word_freq', bin=alt.Bin(step=2), axis=alt.Axis(title='Word Frequency')),\n y=alt.Y('count()', axis=alt.Axis(title='Count'))\n # y='count()'\n)\n\naltair_viewer.display(bar)\n\nbar.save('word_freq.json')\n# save this image\nbar.save('word_freq.png', scale_factor=5.0)\nbar.save('word_freq.svg')\n\n# rule = base.mark_rule(color='red').encode(\n# x='mean(word_freq)',\n# size=alt.value(5)\n# )\n#\n# altair_viewer.display(bar + rule)\n\n# load from csv\n#['number', 'result', 'mmi', 'unsmoothed', 'mwer', 'corpus', 'error', 'translation', 'smooth']\ndf = pd.read_csv('experiment1_geo_dist_directed.csv')\n\n\n# some basic plots\n\n\n\n\n\nto_plot = df[df['geodesic_dist'] != -1]\n\n\nline = alt.Chart(to_plot).mark_line().encode(\n x='geodesic_dist',\n y='mean(number)'\n)\n\nband = alt.Chart(to_plot).mark_errorband(extent='ci').encode(\n x='geodesic_dist',\n y=alt.Y('number', title='Similarity in \"Error\" Embedding'),\n)\n\naltair_viewer.display(band + line)\n\n\n\n\n\n# plotting distributions to see what's up there\ndist_chart_1 = alt.Chart(df).mark_bar().encode(\n alt.X('corpus', bin=True),\n y='count()',\n)\naltair_viewer.display(dist_chart_1)\n\n\n\n\nchart1 = alt.Chart(to_plot).mark_point().encode(\n alt.X('geodesic_dist',\n scale=alt.Scale(domain=(0, 10))\n ),\n y='error'\n).configure_mark(\n opacity=0.1\n)\n\nerrorbars = chart1.mark_errorbar().encode(\n x=\"x\",\n y=\"ymin:Q\",\n y2=\"ymax:Q\"\n)\n\naltair_viewer.display(chart1 + errorbars)\n\n#OLS model to see if we find anything\n\nimport statsmodels.api as sm\n\ny = df['geodesic_dist']\nX = df['error']\nX = sm.add_constant(X)\nmodel11 = sm.OLS(y, X).fit()\nmodel11.summary()\n\n\n\nalt.Chart(source).mark_bar().encode(\n alt.X(\"IMDB_Rating:Q\", bin=True),\n y='count()',\n)\n\nchart2 = alt.Chart(df).mark_point().encode(\n alt.X('corpus',\n scale=alt.Scale(domain=(0, 1))\n ),\n y='citations'\n)\n\n\naltair_viewer.display(chart1)\naltair_viewer.display(chart2)\n\n\n\nexit()\n\n\n\n\n\n\n#OLS model to see if we find anything\n\nimport statsmodels.api as sm\n\ny = df['citations']\nX = df[shared_words]\nX = sm.add_constant(X)\nmodel11 = sm.OLS(y, X).fit()\nmodel11.summary()\n\n\n\n#### THIS IS JUST SOME BASIC COMPARISONS TO THE COMPASS... NOT VERY MEANINGFUL I GUESS\n\n\nmy_dicts = experiment1.get_df_for_compass_comparisons(all_models, c_handle, words_to_check)\n\nmy_dicts2 = experiment1.get_df_for_compass_comparisons(all_models, c_handle, shared_words)\n\n# now do some analysis in pd\n\ndf = pd.DataFrame(my_dicts2)\n\n# where is unsmoothed\ndf2 = pd.DataFrame(my_dicts)\n\n\nchart1 = alt.Chart(df2).mark_point().encode(\n alt.X('error',\n scale=alt.Scale(domain=(0, 1))\n ),\n y='citations'\n)\n\nchart2 = alt.Chart(df).mark_point().encode(\n alt.X('corpus',\n scale=alt.Scale(domain=(0, 1))\n ),\n y='citations'\n)\n\n\naltair_viewer.display(chart1)\naltair_viewer.display(chart2)\n\n\n\n\n\n\nexit()\n\n#test the cosine similarity\n\ntest_model = experiment1.get_model_handle(experiment1.models[subset[0]])\nmeep = test_model.wv.vocab\nmine = test_model['corpus']\n\nc_handle = experiment1.get_model_handle(experiment1.compass_path)\n\nsim_dict_all = experiment1.get_similarity_dict(test_model, c_handle)\n\nmeepers2 = get_intersection_vocab([test_model, c_handle])\n\nall_model_handles = [experiment1.get_model_handle(i) for i in experiment1.models.values()]\n\nmeepersAll = get_intersection_vocab(all_model_handles)\n\nsimilarities = {}\nfor id, m in experiment1.models.items():\n curr_model = experiment1.get_model_handle(m)\n sim_dict_intersection = experiment1.get_similarity_dict(curr_model, c_handle, words=meepersAll)\n similarities[id] = get_average_similarity(sim_dict_intersection)\n\n\n# combine with citation counts and make a list of dicts for turning into a pandas dataframe\nfor_df = []\nfor myId, sim in similarities.items():\n # make a list of dicts to convert to pandas dataframe\n new_item = {}\n new_item['id'] = myId\n new_item['avg_similarity_w_compass'] = sim\n new_item['citations'] = citation_counts[myId]\n for_df.append(new_item)\n\n\n# covert to pandas dataframe\ndf = pd.DataFrame(for_df)\n\ndf.to_csv(\"experiment1data.csv\", header=True,index=False)\n\n\ndf = pd.read_csv(\"experiment1data.csv\")\n\nchart = alt.Chart(df).mark_point().encode(\n alt.X('avg_similarity_w_compass',\n scale=alt.Scale(domain=(.96, .99))\n ),\n y='citations'\n)\n\naltair_viewer.display(chart)\n\n# just start by making a dataframe with each paper and the cosine similarity with each word (compared to compass)\n# are the word embeddings from the paper in question higher in similarity to the papers that came before it? Or after it?\n\n# I can do model.wv.vocab['word']['count'] and that should give me the count (?)\n\n\n# create csv file of similarities, to be read into a dataframe for viz.\n\n\ntest_compare = experiment1.compare_word_to_compass('corpus', experiment1.models[subset[0]])\n\n# so I can quickly get a distribution of comparisons between two years.\n# first, find the intersection of the vocab\n# then do pairwise cosine similarity, store in a dict with word: similarity.\n\n\nprint(\"PAUSE\")\n\n# TRAIN MODEL on every single individual paper\n\n\n# remove external\n# all_internal = [i for i in list(all_papers) if 'External' not in i]\n\n# UNCOMMENT TO CREATE CORPUS\n#create_xml_corpus(all_papers2, p, 'largest_id_corpus_sketch_engine')\n\nexit()\n#### EXPERIMENT 1 ########\n#### COMPARE VECTOR ALIGNMENT BETWEEN EACH PAPER AND THE LARGEST WEAKLY CONNECTED COMPONENT #####\n\n\n### FIRST STEP: GET THE LARGEST COMPONENT OF THE NETWORK (~98.3% of the corpus)\nlargest = max(nx.weakly_connected_components(G), key=len)\n\n### NEXT, COMBINE ALL THE PAPERS IN THE COMPONENT INTO A SINGLE TEXT FILE\n### COMMENTED BECUASE IT TAKES SOME TIME AND WE ALREADY RAN IT\n#start1 = time.time()\n#create_text_slice(get_paths_from_strings(largest, p), 'LARGEST_WEAK_COMPONENT.txt')\n#end1 = time.time()\n#elapsed1 = end1 - start1\n#print (elapsed1)\n\n### TRAIN THE COMPASS WORD EMBEDDINGS FOR THIS COMPONENT #####\n### TAKES A WHILE SO WE WILL TIME IT ####\naligner = TWEC(size=50, siter=10, diter=10, workers=4)\nstart2 = time.time()\naligner.train_compass('LARGEST_WEAK_COMPONENT.txt', overwrite=False, filename=\"LARGEST_WEAK_COMPONENT.model\")\nend2 = time.time()\nelapsed2 = end2 - start2\nprint (elapsed2)\n\n\n# write the training time to a file\nwith open(\"experiment_1_train_compass_time.log\", 'w', encoding='utf-8') as outfile:\n outfile.write(\"time to train compass on largest weakly connected component was \\n\" + str(elapsed2) + \" seconds\")\n\n\nid = 'J92-1001'\nfileP = get_path_from_id(id, p)\nslice_one = aligner.train_slice(str(fileP), save=True)\n\n### NOW GO THROUGH AND TRAIN MODELS FOR EVERY INDIVIDUAL PAPER\n### THIS WILL TAKE QUITE A WHILE BECAUSE THERE'S 80k+ papers\n\n### UHHH I NEED 86 gb of free space to actually be able to save all these word embedding models\n## I might have to run this on the free PC I got... that should have space... lol\n\nfor paper in largest:\n fileP = get_path_from_id(paper, p)\n slice_one = aligner.train_slice(str(fileP), save=True, saveName='EXP1-' + paper)\n\n### END EXPERIMENT !\n\n\n\n\n\n\n\n\ndownstreams = get_connected_papers(G, id, upstream=False) # length of zero here means nobody cited it :(\nupstreams = get_connected_papers(G, id, upstream=True) # these are the papers the given paper cites\nall = downstreams.union(upstreams)\nall.add(id)\n\n# f_all = create_text_slice(get_paths_from_strings(all, p), 'J92-1001ALL.txt')\n# f_up = create_text_slice(get_paths_from_strings(upstreams, p), 'J92-1001up.txt')\n# f_down = create_text_slice(get_paths_from_strings(downstreams, p), 'J92-1001down.txt')\n# f_self = create_text_slice(get_paths_from_strings([id], p), 'J92-1001self.txt')\n#\n#\n# # decleare a TWEC object, siter is the number of iterations of the compass, diter is the number of iterations of each slice\n# aligner = TWEC(size=50, siter=10, diter=10, workers=4)\n#\n# start = time.time()\n#\n# # train the compass (we are now learning the matrix that will be used to freeze the specific CBOW slices)\n# # this may need some path modification to enable experimentation\n# aligner.train_compass(str(f_down), overwrite=True)\n#\n# end = time.time()\n#\n# elapsed = end-start\n# print (elapsed)\n\n#### TRAINING COMPASS FOR LARGEST COMPONENT ###\n\nlargest = max(nx.strongly_connected_components(G), key=len)\n\n\n\n#\n# upstreams = get_connected_papers(G, 'J92-1001', upstream=True)\n\n\n### Testing out running the embeddings on the whole corpus to get an idea of time\np = Path('.')\np = p / '..' / 'project_code' / 'papers'\np = p / 'acl-arc-json' / 'json'\n\n\nall_nodes = list(G.nodes)\n\npapers = []\nfor node in all_nodes:\n temp = get_path_from_id(node, p)\n if temp:\n papers.append(temp)\n\n\ncreate_text_slice(papers, 'every_paper_text.txt')\n\n# decleare a TWEC object, siter is the number of iterations of the compass, diter is the number of iterations of each slice\naligner = TWEC(size=50, siter=10, diter=10, workers=4)\n\nstart = time.time()\n\n# train the compass (we are now learning the matrix that will be used to freeze the specific CBOW slices)\n# this may need some path modification to enable experimentation\naligner.train_compass('every_paper_text.txt', overwrite=True)\n\nend = time.time()\n\nelapsed = start-end\nprint (elapsed)\n# now see how long it takes to train the compass on that...\n\n\n#len(list(G.successors('External_89521')))\n\nexit()\n\n\nG.number_of_edges()\nG.number_of_nodes()\n\nin_degs = list(G.in_degree())\n\nin_degs_s = sorted(in_degs,key=itemgetter(1), reverse=True)\n\nt = G.nodes['P13-1037']\n\ntesting =sorted(G.successors('P13-1037'))\n\nall_nodes = list(G.nodes)\n\npapers = []\nfor node in all_nodes:\n papers.append(get_path_from_id(node, ))\n\ntest = nx.weakly_connected_components(G)\n\nnx.is_strongly_connected(G)\n\ntest1 = sorted(test)\ny = [\n len(c)\n for c in sorted(nx.weakly_connected_components(G), key=len, reverse=True)\n]\nlargest = max(nx.strongly_connected_components(G), key=len)\n# get the top 10 papers that are not 'external' to the corpus\nnum_papers = 0\nmax_papers = 10\npapers_to_look_at = []\nfor i, (key, val) in enumerate(in_degs_s):\n if num_papers > max_papers:\n break\n if not key.startswith(\"External\"):\n papers_to_look_at.append((key, val))\n num_papers += 1\n\n\n\n\n\n\n\n\nexit()\n\n# example below\n\n\n\np = Path('.')\np = p / '..' / 'project_code' / 'papers'\np = p / 'acl-arc-json' / 'json'\n\nexperiment_dir = Path('.') / 'text_files'\n\ntest = get_path_from_id('J11-1005', p)\ntest1 = test\ntest2 = test\n\nmyList = [test, test1, test2]\n\nslice1 = create_text_slice(myList, experiment_dir / 'testout.txt')\n\n\ntest = get_path_from_id('J11-1006', p)\ntest1 = test\ntest2 = test\n\nmyList = [test, test1, test2]\n\nslice2= create_text_slice(myList, experiment_dir / 'testout2.txt')\n\n\nslices = [slice1, slice2]\n\ncompass = create_text_slice(slices, experiment_dir / 'testCompass.txt')\n\n\n# decleare a TWEC object, siter is the number of iterations of the compass, diter is the number of iterations of each slice\naligner = TWEC(size=50, siter=10, diter=10, workers=4)\n\n# train the compass (we are now learning the matrix that will be used to freeze the specific CBOW slices)\n# this may need some path modification to enable experimentation\naligner.train_compass(str(compass), overwrite=True)\n\n# now you can train slices and they will be already aligned (we use two collections of arxiv papers of different years)\n# these two objects are gensim objects\nslice_one = aligner.train_slice(str(slice1), save=True)\nslice_two = aligner.train_slice(str(slice2), save=True)\n\n#once trained you can also load the trained and aligned embeddings\nmodel1 = Word2Vec.load(\"model/testout.model\")\nmodel2 = Word2Vec.load(\"model/testout2.model\")\n\n\nmodel1['algorithm']\nmodel2['algorithm']\n\n\n\n\n\n\n\n\n\n\n\n\n### OLD JUNK\n\n\n\nall_papers = set()\n\n# recursive function that adds papers to the global variable.\ndef get_downstream_papers(G, node_id):\n global all_papers\n\n # get all the papers this one cites\n node_successors = list(G.successors(node_id))\n\n # and remove any elements that are already captured in the global list\n node_successors_real = [node for node in node_successors if node not in all_papers]\n\n # end condition - no new nodes to add to the global list\n if len(node_successors_real) == 0:\n return None\n else:\n for node in node_successors_real:\n all_papers.add(node)\n get_downstream_papers(G, node)\n\n\n\n\n# SHORTEST PATH JUNK\n\n shortest_paths = nx.shortest_path_length(G_undirected, source='P13-1037')\n\n shortest_paths['P13-1037']\n\n # go through shortest path generator and only keep distances between internal papers (not starting with external)\n dict_o_lengths = {} # will hold everything\n i = 0\n for (myKey, myDict) in shortest_paths:\n print(i)\n i += 1\n curr_dict = {} # holds the key pairs for a single paper\n if not str.startswith(myKey, 'External'):\n for key1, dist in myDict.items():\n if not str.startswith(key1, 'External'):\n curr_dict[key1] = dist\n dict_o_lengths[myKey] = curr_dict\n\n s2 = nx.shortest_path_length(G_undirected)\n s2dict = dict(s2)\n\n shortest_paths_dict = dict(shortest_paths)","repo_name":"mjhoefer/scilangevo","sub_path":"backup_analysis.py","file_name":"backup_analysis.py","file_ext":"py","file_size_in_byte":14515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"36844953609","text":"\"\"\"\r\nEste script se utiliza para iniciar la interfaz grafica del programa\r\n\"\"\"\r\nimport graficos as gf\r\nimport conexion_mysql as sql\r\n# realiza conxeion con la base de datos\r\nCONN = sql.realizar_conexion()\r\nif CONN == -1:\r\n # grafico de error si la conexion falla\r\n gf.error_servidor()\r\nelse:\r\n # grafico de conexion establecida si no falla la conexion con la base de datos\r\n gf.inicio(CONN)\r\n sql.cerrar_conexion(CONN)\r\n","repo_name":"AldairSoledispa/2T2018_Sistema_de_configuraci-n_de_enrutamiento_BGP_para_la_interconexi-n_entre_empresa_ISP_GRUPO_2","sub_path":"Codigo/Version2.2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"40423178109","text":"from PyQt4 import QtCore, QtGui\n\nfrom library.crbcombobox import CRBComboBox\nfrom library.InDocTable import CRBInDocTableCol\nfrom library.TableModel import CTableModel, CTextCol\nfrom library.Utils import getPref, setPref\n\nfrom Ui_SuiteReagentComboBoxPopup import Ui_SuiteReagentPopupForm\n\n\nclass CSuiteReagentPopup(QtGui.QFrame, Ui_SuiteReagentPopupForm):\n __pyqtSignals__ = ('suiteReagentSelected(int)',\n )\n def __init__(self, parent=None):\n QtGui.QFrame.__init__(self, parent, QtCore.Qt.Popup)\n self.tableModel = CSuiteReagentTableModel(self)\n self.tableSelectionModel = QtGui.QItemSelectionModel(self.tableModel, self)\n self.tableSelectionModel.setObjectName('tableSelectionModel')\n self.setupUi(self)\n self.tblSuiteReagent.setModel(self.tableModel)\n self.tblSuiteReagent.setSelectionModel(self.tableSelectionModel)\n # preferences = getPref(QtGui.qApp.preferences.windowPrefs, 'CSuiteReagentPopup', {})\n # self.tblSuiteReagent.loadPreferences(preferences)\n self._testId = None\n self.setTestId(self._testId)\n self._tissueJournalDate = None\n self.setTissueJournalDate(self._tissueJournalDate)\n \n def setTissueJournalDate(self, date):\n self._tissueJournalDate = date if date and date.isValid() else None\n self.setVisibleNotOverdue(bool(self._tissueJournalDate))\n self.setVisibleStartOperation(bool(self._tissueJournalDate))\n \n def setVisibleNotOverdue(self, value):\n self.chkNotOverdue.setChecked(value)\n self.chkNotOverdue.setVisible(value)\n \n def setVisibleStartOperation(self, value):\n self.chkStartOperation.setChecked(value)\n self.chkStartOperation.setVisible(value)\n \n def setTestId(self, testId):\n self._testId = testId\n self.setVisibleOnlyByTest(bool(self._testId))\n \n def setVisibleOnlyByTest(self, value):\n self.chkOnlyByTest.setChecked(value)\n self.chkOnlyByTest.setVisible(value)\n \n # def closeEvent(self, event):\n # preferences = self.tblSuiteReagent.savePreferences()\n # setPref(QtGui.qApp.preferences.windowPrefs, 'CEquipmentPopupView', preferences)\n # QtGui.QFrame.closeEvent(self, event)\n \n def getSuiteReagentIdList(self):\n db = QtGui.qApp.db\n tableSuiteReagent = db.table('SuiteReagent')\n tableSuiteReagentTest = db.table('SuiteReagent_Test')\n tableProbe = db.table('Probe')\n \n queryTable = tableSuiteReagent\n \n cond = []\n if self.chkOnlyByTest.isChecked():\n queryTable = queryTable.innerJoin(tableSuiteReagentTest, \n tableSuiteReagentTest['master_id'].eq(tableSuiteReagent['id']))\n cond.append(tableSuiteReagentTest['test_id'].eq(self._testId))\n \n if self.chkNotOverdue.isChecked():\n cond.append(tableSuiteReagent['expiryDate'].ge(self._tissueJournalDate))\n \n if self.chkStartOperation.isChecked():\n cond.append(tableSuiteReagent['startOperationDate'].le(self._tissueJournalDate))\n \n if self.chkNotOverLimit.isChecked():\n cond.append('SuiteReagent.`execTestQuantity` <= (SELECT SUM(Probe.`id`) FROM Probe WHERE `suiteReagent_id`=SuiteReagent.`id`)')\n \n idList = db.getDistinctIdList(queryTable, tableSuiteReagent['id'].name(), cond)\n return idList\n\n \n def setIdList(self, idList, posToId=None):\n if bool(idList):\n self.tblSuiteReagent.setIdList(idList, posToId)\n self.tabWidget.setCurrentIndex(0)\n self.tabWidget.setTabEnabled(0, True)\n self.tblSuiteReagent.setFocus(QtCore.Qt.OtherFocusReason)\n else:\n self.tabWidget.setCurrentIndex(1)\n self.tabWidget.setTabEnabled(0, False)\n \n def on_buttonBox_apply(self, id=None):\n idList = self.getSuiteReagentIdList()\n self.setIdList(idList, id)\n \n def on_buttonBox_reset(self):\n for chkWidget in [self.chkOnlyByTest, \n self.chkNotOverdue, \n self.chkStartOperation, \n self.chkNotOverLimit]:\n chkWidget.setChecked(True)\n \n self.on_buttonBox_apply()\n \n def emitSuiteReagentSelected(self, id):\n self.emit(QtCore.SIGNAL('suiteReagentSelected(int)'), id)\n self.hide()\n \n def setSuiteReagents(self):\n self.on_buttonBox_apply(None)\n \n @QtCore.pyqtSlot(QtGui.QAbstractButton)\n def on_buttonBox_clicked(self, button):\n buttonCode = self.buttonBox.standardButton(button)\n if buttonCode == QtGui.QDialogButtonBox.Apply:\n self.on_buttonBox_apply()\n elif buttonCode == QtGui.QDialogButtonBox.Reset:\n self.on_buttonBox_reset()\n \n @QtCore.pyqtSlot(QtCore.QModelIndex)\n def on_tblSuiteReagent_clicked(self, index):\n itemId = self.tblSuiteReagent.itemId(index)\n self.emitSuiteReagentSelected(itemId)\n\n\nclass CSuiteReagentComboBox(CRBComboBox):\n def __init__(self, parent):\n CRBComboBox.__init__(self, parent)\n self.popupView = None\n self._tableName = 'SuiteReagent'\n self._testId = None\n self._tissueJournalDate = None\n CRBComboBox.setTable(self, self._tableName)\n \n def showPopup(self):\n if not self.popupView:\n self.popupView = CSuiteReagentPopup(self)\n self.connect(self.popupView,QtCore.SIGNAL('suiteReagentSelected(int)'), self.setValue)\n self.popupView.setTestId(self._testId)\n self.popupView.setTissueJournalDate(self._tissueJournalDate)\n pos = self.rect().bottomLeft()\n pos2 = self.rect().topLeft()\n pos = self.mapToGlobal(pos)\n pos2 = self.mapToGlobal(pos2)\n size = self.popupView.sizeHint()\n width= max(size.width(), self.width())\n size.setWidth(width)\n screen = QtGui.QApplication.desktop().availableGeometry(pos)\n pos.setX( max(min(pos.x(), screen.right()-size.width()), screen.left()) )\n pos.setY( max(min(pos.y(), screen.bottom()-size.height()), screen.top()) )\n self.popupView.move(pos)\n self.popupView.resize(size)\n self.popupView.setSuiteReagents()\n self.popupView.show()\n \n def setTestId(self, testId):\n self._testId = testId\n\n def setTissueJournalDate(self, tissueJournalDate):\n self._tissueJournalDate = tissueJournalDate\n \n\n# #############################################################\n\nclass CSuiteReagentTableModel(CTableModel):\n def __init__(self, parent):\n CTableModel.__init__(self, parent, cols=[\n CTextCol(u'Код', ['code'], 20),\n CTextCol(u'Наименование', ['name'], 40),\n# CRefBookCol(u'Ответственный', ['recipientPerson_id'], 'vrbPersonWithSpeciality', 10), \n# CDateCol(u'Дата выпуска', ['releaseDate'], 10), \n# CDateCol(u'Дата поступления', ['supplyDate'], 12), \n# CDateCol(u'Дата передачи в работу', ['startOperationDate'], 14), \n# CDateCol(u'Срок годности', ['expiryDate'], 10),\n# CNumCol(u'Плановое количество тестов', ['planTestQuantity'], 15), \n# CNumCol(u'Выполненное количество тестов', ['execTestQuantity'], 15), \n# CTextCol(u'Производитель', ['manufacturer'], 10), \n# CTextCol(u'Условия хранения', ['storageConditions'], 12)\n ], tableName='SuiteReagent')\n \nclass CRBSuiteReagentCol(CRBInDocTableCol):\n def __init__(self, title, fieldName, width, tableName, **params):\n CRBInDocTableCol.__init__(self, title, fieldName, width, tableName, **params)\n self._testId = params.get('testId', None)\n self._tissueJournalDate = params.get('tissueJournalDate', None)\n \n def createEditor(self, parent):\n editor = CSuiteReagentComboBox(parent)\n editor.setTable(self.tableName, addNone=self.addNone, filter=self.filter, needCache=False, order = self.order)\n editor.setShowFields(self.showFields)\n editor.setPrefferedWidth(self.prefferedWidth)\n if self._testId:\n editor.setTestId(self._testId)\n if self._tissueJournalDate:\n editor.setTissueJournalDate(self._tissueJournalDate)\n return editor\n","repo_name":"dio4/vista_1","sub_path":"Orgs/SuiteReagentComboBox.py","file_name":"SuiteReagentComboBox.py","file_ext":"py","file_size_in_byte":8911,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"35668772625","text":"from board import Direction, Rotation, Action\nfrom random import Random\nfrom exceptions import NoBlockException\nimport time\n\nclass Player:\n def choose_action(self, board):\n raise NotImplementedError\n\nclass MyPlayer(Player):\n def __init__(self, seed=None):\n self.random = Random(seed)\n self.prev_score = 0\n\n\n def get_column_height(self,cloned_board):\n column_heights = [0,0,0,0,0,0,0,0,0,0]\n for x in range(cloned_board.width):\n for y in range(cloned_board.height,0,-1):\n if (x,y) in cloned_board.cells:\n column_heights[x] = cloned_board.height-y\n return column_heights\n\n\n def avg_height(self,cloned_board):\n column_heights = self.get_column_height(cloned_board)\n avg_height = sum(column_heights)/len(column_heights)\n return avg_height\n\n\n\n def get_bumpiness(self, cloned_board):\n bumpiness = 0\n column_heights = self.get_column_height(cloned_board)\n for x in range(cloned_board.width -1):\n if column_heights[x] > column_heights[x+1]:\n bumpiness += column_heights[x] - column_heights[x+1]\n else:\n bumpiness += column_heights[x+1] - column_heights[x]\n return bumpiness\n\n\n\n def get_blocks_above_holes(self, cloned_board): #blocks above holes\n blocks_above_holes = 0\n for x, y in cloned_board.cells:\n flag = True\n count_y = 1\n while flag==True:\n if ((x,y + count_y) not in cloned_board.cells) and (count_y+y!=24):\n blocks_above_holes+=1\n count_y+=1\n else:\n flag = False\n return blocks_above_holes\n\n\n\n def get_holes(self, cloned_board):\n holes = 0\n board_cells = list(cloned_board.cells) + [(10, i) for i in range(24)] + [(i, 24) for i in range(20)] + [(i, -1) for i in range(10)] + [(-1, i) for i in range(24)]\n for x in range(10):\n for y in range(24):\n if (x, y) not in board_cells:\n if (x+1, y) in board_cells and (x-1, y) in board_cells and (x, y+1) in board_cells and (x, y-1) in board_cells:\n holes+=1\n return holes\n\n \n\n def score_board(self, board):\n score_change = board.score - self.prev_score\n blocks_above_holes = self.get_blocks_above_holes(board)\n bumpiness = self.get_bumpiness(board)\n avg_height = self.avg_height(board)\n # max_height = max(self.get_column_height(board))\n holes = self.get_holes(board)\n # if score_change > 1500:\n # score = bumpiness* -0.8 + holes*-3.9+ blocks_above_holes*-3.6 + avg_height*-1.6 + score_change*2\n # elif score_change > 300:\n # score = bumpiness* -1.1 + holes*-3.9+ blocks_above_holes*-4.6 + avg_height*-2.6 + score_change*0.4\n # elif score_change > 90:\n # score = bumpiness* -1.16 + holes*-3.9+ blocks_above_holes*-4.9 + avg_height*-2.6 + score_change*-0.1\n # elif score_change > 24:\n # score = bumpiness* -2.8 + holes*-4.9+ blocks_above_holes*-5.2 + avg_height*-3.6 + score_change*-0.3\n # else:\n # score = bumpiness* -3.1+ holes*-8.9+ blocks_above_holes*-7.2 + avg_height*-4.6 + score_change*-0.5\n score = bumpiness* -220 + holes*-780+ blocks_above_holes*-720 + avg_height*120\n return score\n\n\n\n def move_to_target(self, board, cloned_board, t_pos, t_rot):\n for i in range(0, t_rot):\n try:\n cloned_board.rotate(Rotation.Anticlockwise)\n except NoBlockException:\n pass\n left_of_shape = board.falling.left\n while t_pos != left_of_shape:\n if t_pos < left_of_shape:\n try:\n left_of_shape -= 1\n cloned_board.move(Direction.Left)\n except NoBlockException:\n pass\n elif t_pos > left_of_shape:\n left_of_shape += 1\n try:\n cloned_board.move(Direction.Right)\n except NoBlockException:\n pass\n try:\n cloned_board.move(Direction.Drop)\n except NoBlockException:\n pass\n\n\n def make_best_move(self, board, best_pos, best_rot):\n moves = []\n # Specific rotation\n for i in range(best_rot):\n moves.append(Rotation.Anticlockwise)\n\n curr_pos = board.falling.left\n while best_pos != curr_pos:\n\n if best_pos < curr_pos:\n curr_pos -= 1\n moves.append(Direction.Left)\n\n elif best_pos > curr_pos:\n curr_pos += 1\n moves.append(Direction.Right)\n\n moves.append(Direction.Drop)\n\n return moves\n\n\n def choose_action(self, board):\n best_score = -100000\n self.prev_score = board.score\n for t_pos in range(board.width):\n for t_rot in range(4):\n clone_board = board.clone()\n self.move_to_target(board, clone_board, t_pos, t_rot)\n score = self.score_board(clone_board)\n if score > best_score:\n best_score = score\n best_pos = t_pos\n best_rot = t_rot\n return self.make_best_move(board, best_pos, best_rot)\n\nSelectedPlayer = MyPlayer\n \n\n","repo_name":"ProgrammerFS/Tetris-AI","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":5456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"29477947449","text":"s = ' nonono'\ndef cod(s):\n letras = \"AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz\"\n trans = letras[26:]+letras[:26]\n rot_char = lambda c: trans[letras.find(c)] if letras.find(c) > -1 else c\n c = ''.join(rot_char(c) for c in s)\n \n return c\n\nprint(cod(s))","repo_name":"pabloschwarzenberg/grader","sub_path":"tema8_ej4/tema8_ej4_9528d3fa20374d277266264a6349f1b0.py","file_name":"tema8_ej4_9528d3fa20374d277266264a6349f1b0.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"3538710419","text":"from visualizer import Visualizer # Import Visualizer class\n\ndt = 0.05 # ΔT (sampling period) seconds\n\n# Initial values\nposition = 15\nvelocity = 0\nacceleration = 0\n\n# Constants\nmass = 1 # mass\nk = 2.5 # spring coefficient\nb = 0.3 # damping coefficient\n\n# Callback Function\ndef set(arg):\n global dt, position, velocity, acceleration, mass, k, b # Get global variables\n\n spring_force = k * position # Fs = k * x\n damper_force = b * velocity # Fb = b * x'\n\n # If we leave the acceleration alone in equation\n # acceleration = - ((b * velocity) + (k * position)) / mass\n acceleration = - (spring_force + damper_force) / mass\n velocity += (acceleration * dt) # Integral(a) = v\n position += (velocity * dt) # Integral(v) = x\n\n return (position, 0) # Return position\n\n# Start simulation\nVisualizer(callback=set, interval=dt * 1000, simulation_time=30, initial=(position, 0, velocity, 0, acceleration, 0))","repo_name":"enesdemirag/programming-exercises","sub_path":"exercises/materials/mass-spring-damper-simulation/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"77"}
+{"seq_id":"35802960542","text":"\"\"\"instanciate Spam Discord bot\"\"\"\nimport asyncio\nimport logging\nimport os\nimport time\n\nimport discord\nfrom discord.ext import commands\nfrom dotenv import load_dotenv\n\nfrom cogs.basic_cog import Misc\nfrom cogs.spam_cog import Spam\n\nload_dotenv()\n\nlogger = logging.getLogger('discord')\nlogger.setLevel(logging.INFO)\nhandler = logging.FileHandler(\n filename=time.strftime(os.path.join(\"logs\", \"spam_bot_%Y-%m-%d_%H-%M-%S.log\")),\n encoding='utf-8',\n mode='w'\n)\nhandler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))\nlogger.addHandler(handler)\n\nintents = discord.Intents.all()\n\nbot = commands.Bot(\n command_prefix=\"s$\",\n case_insensitive=True,\n description=\"Bot to help you spam some sh****t\",\n intents=intents\n)\n\n\nasync def main():\n # cogs setup\n await bot.add_cog(Misc(bot))\n await bot.add_cog(Spam(bot))\n\n await bot.start(os.environ.get('SpamBot'))\n\nasyncio.run(main())\n","repo_name":"Larsluph/bots_discord","sub_path":"spam_bot.py","file_name":"spam_bot.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"43462835114","text":"from django.template import RequestContext, loader\nfrom django.core.urlresolvers import reverse\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.views.generic import CreateView, DeleteView, DetailView, ListView, UpdateView\nfrom django.shortcuts import render, redirect\nfrom django.http import HttpResponse\n\nfrom members.models import Member\nfrom groups.models import Group, Meeting\n\nimport json\nfrom datetime import datetime\n\ndef autocomplete_member(request):\n if request.is_ajax():\n q = request.GET.get('term', '')\n members = Member.objects.filter(name__icontains = q )[:20]\n results = []\n\t\t\n for member in members:\n member_json = {}\n member_json['id'] = member.id\n member_json['label'] = member.name\n member_json['value'] = member.name\n results.append(member_json)\n\n data = json.dumps(results)\n else:\n data = 'fail'\n\n mimetype = 'application/json'\n return HttpResponse(data, mimetype)\n\n\n\ndef search_member_for_group(request, pk):\n\t\"\"\" Receives pk as the key for the Group which we want to add members to \"\"\"\n\tcontext = { 'group_id': pk}\n\treturn render(request, 'groups/search_member_for_group.html', context)\n\n\n\ndef remove_member_from_group(request, group_id, member_id):\n\tmember = Member.objects.get(pk=member_id)\n\tgroup = Group.objects.get(pk=group_id)\n\n\tgroup.members.remove(member)\n\tgroup.save()\n\n\tcontext = {'member': member, 'group': group}\n\t\n\treturn render(request, 'groups/member_removed_from_group.html', context)\n\n\n\ndef add_member_to_group(request, group_id):\n\tnew_group_member = Member.objects.get(pk=request.POST['member_id'])\n\tgroup = Group.objects.get(pk=group_id)\n\t\n\tgroup.members.add(new_group_member)\n\tgroup.save()\n\n\tcontext = {'new_group_member': new_group_member.name, 'group_name': group.name}\n\n\treturn render(request, 'groups/member_added_to_group_sucess.html', context)\n\n\n\ndef register_meeting(request, group_id):\n\tgroup = Group.objects.get(pk=group_id)\n\tgroup_members = group.members.all()\n\tcontext = {'group': group, 'group_members': group_members}\n\n\treturn render(request, 'groups/register_meeting.html', context)\n\n\n\ndef submit_meeting(request, group_id):\n\tpresent_members_ids = request.POST.getlist('members')\n\tpresent_members = []\n\n\tfor member_id in present_members_ids:\n\t\tpresent_members.append(Member.objects.get(pk=member_id))\n\n\tgroup = Group.objects.get(pk=group_id)\n\tcomments = request.POST['comments']\n\tmeeting_type = request.POST['type']\n\tdate = datetime.strptime(request.POST['date'], \"%d/%m/%Y\").strftime(\"%Y-%m-%d\")\n\n\tmeeting = Meeting()\n\n\tgroup.meeting_set.add(meeting)\n\n\tmeeting.group = group\n\tmeeting.type = meeting_type\n\tmeeting.comments = comments\n\tmeeting.date = date\n\tmeeting.members_who_attended = present_members\n\n\tmeeting.save()\n\n\tcontext = {}\n\n\treturn render(request, 'groups/submit_meeting.html', context)\n\n\n\nclass GroupListView(ListView):\n\ttemplate_name = 'groups/list.html'\n\tcontext_object_name = 'group_list'\n\n\tdef get_queryset(self):\n\t\t\"\"\" Return all registered members \"\"\"\n\t\treturn Group.objects.all()\n\n\n\nclass GroupDetailView(DetailView):\n\tmodel = Group\n\ttemplate_name = 'groups/detail.html'\n\n\tdef get_context_data(self, **kwargs):\n\t\tcontext = super(GroupDetailView, self).get_context_data(**kwargs)\n\t\tcontext[\"group_members\"] = context['group'].members.all()\n\t\tcontext[\"last_meetings\"] = Meeting.objects.filter(group=context['group']).order_by('-date')[:5]\n\t\t\n\t\treturn context\n\n\n\nclass GroupCreateView(CreateView):\n\tmodel = Group\n\ttemplate_name = 'groups/form.html'\n\tfields = ['name', 'leader']\n\tsuccess_url = reverse_lazy('groups:group_list')\n\n\n\nclass GroupUpdateView(UpdateView):\n\tmodel = Group\n\ttemplate_name = 'groups/form.html'\n\tfields = ['name', 'leader']\n\tsuccess_url = reverse_lazy('groups:group_list')\n\n\n\nclass GroupDeleteView(DeleteView):\n\tmodel = Group\n\ttemplate_name = 'groups/confirm_delete.html'\n\tsuccess_url = reverse_lazy('groups:group_list')","repo_name":"ernestocid/meuatreze","sub_path":"groups/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"18533381122","text":"\"\"\"result column from game to users_games\n\nRevision ID: aed8d781d740\nRevises: 3c7e757a82df\nCreate Date: 2023-09-07 12:32:56.930551\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'aed8d781d740'\ndown_revision = '3c7e757a82df'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n op.drop_column(\"games\", \"result\")\n op.add_column(\"users_games\", sa.Column(\"score\", sa.Float, default=0))\n\n\ndef downgrade() -> None:\n op.drop_column(\"users_games\", \"score\")\n op.add_column(\"game\", sa.Column(\"result\", sa.Float))\n","repo_name":"injornal/chess-rating-system","sub_path":"alembic/versions/aed8d781d740_result_column_from_game_to_usersgames.py","file_name":"aed8d781d740_result_column_from_game_to_usersgames.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"13053243176","text":"from django.shortcuts import render, redirect\r\nfrom django.shortcuts import render, redirect, get_object_or_404\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom .models import Topic, Entry\r\nfrom .forms import TopicForm, EntryForm\r\nfrom django.http import Http404\r\nfrom django.db.models import Q\r\n# Create your views here.\r\ndef index(request):\r\n \"\"\"The homepage for learning log.\"\"\"\r\n return render(request, 'learning_logs/index.html')\r\n\r\ndef _get_topics_for_user(user):\r\n \"\"\"return a queryset of topics and the user can access.\"\"\"\r\n q = Q(public=True)\r\n #if django \"user.is_authenticated()\" (with parens)\r\n if user.is_authenticated:\r\n #adds user's own private topics to the query\r\n q = q | Q(public=False, owner=user)\r\n return Topic.objects.filter(q)\r\n\r\ndef topics(request):\r\n \"\"\"Show all topics\"\"\"\r\n topics = _get_topics_for_user(request.user).order_by('date_added')\r\n context = {'topics': topics}\r\n return render(request, 'learning_logs/topics.html', context)\r\n\r\n@login_required\r\ndef topic(request, topic_id):\r\n \"\"\"show a simple topic and all it's entries\"\"\"\r\n topics = _get_topics_for_user(request.user)\r\n # here we're passing the filtered queryset, so\r\n # if the topic \"topic_id\" is private and the user is with\r\n #anonymos or not the topic owner, it will raise a 404\r\n topic = get_object_or_404(Topic, id=topic_id)\r\n #Make sure the topic belongs to the current user\r\n check_topic_owner(topic.owner, request)\r\n entries = topic.entry_set.order_by('-date_added')\r\n context = {'topic': topic, 'entries':entries}\r\n return render(request, 'learning_logs/topic.html', context,)\r\n\r\n@login_required\r\ndef new_topic(request):\r\n \"\"\"Add a new topic.\"\"\"\r\n if request.method != 'POST':\r\n #No data submitted;create a blank form.\r\n form = TopicForm()\r\n else:\r\n # POST data submitted; process data.\r\n form = TopicForm(data=request.POST)\r\n if form.is_valid():\r\n new_topic = form.save(commit=False)\r\n new_topic.owner = request.user\r\n new_topic.save()\r\n return redirect('learning_logs:topics')\r\n #Display a blank or invalid form.\r\n context = {'form': form}\r\n return render(request, 'learning_logs/new_topic.html', context)\r\n\r\n@login_required\r\ndef new_entry(request, topic_id):\r\n \"\"\"Add a new entry for a particular Topic.\"\"\"\r\n topic = get_object_or_404(Topic, id=topic_id)\r\n check_topic_owner(topic.owner, request)\r\n if request.method != 'POST':\r\n #NO data sumbitted create a blank form.\r\n form = EntryForm()\r\n else:\r\n #Post data submitted, process data.\r\n form = EntryForm(data=request.POST)\r\n if form.is_valid():\r\n new_entry = form.save(commit=False)\r\n new_entry.topic = topic\r\n new_entry.save()\r\n return redirect('learning_logs:topic', topic_id=topic_id)\r\n #Display a blank or invalid form.\r\n context = {'topic': topic, 'form': form}\r\n return render(request, 'learning_logs/new_entry.html', context)\r\n\r\n@login_required\r\ndef edit_entry(request, entry_id):\r\n \"\"\"Edit an exiting entry.\"\"\"\r\n entry = get_object_or_404(Entry, id=entry_id)\r\n topic = entry.topic\r\n check_topic_owner(topic.owner, request)\r\n if request.method != 'POST':\r\n #Intial request; pre-fill form with the current entry.\r\n form = EntryForm(instance=entry)\r\n else:\r\n # Post data submitted;process data\r\n form = EntryForm(instance=entry, data=request.POST)\r\n if form.is_valid():\r\n form.save()\r\n return redirect('learning_logs:topic', topic_id=topic.id)\r\n context = {'entry': entry, 'topic': topic, 'form': form}\r\n return render(request, 'learning_logs/edit_entry.html', context)\r\ndef check_topic_owner(owner, request):\r\n if owner != request.user:\r\n raise Http404","repo_name":"IamLiam09/learning_log","sub_path":"learning_logs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3899,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"74418271288","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n # /blog/\n path('', views.index, name='index'),\n path('post/', views.PostDetailView.as_view(), name='post'),\n path('post/create', views.PostCreate.as_view(), name='post_create'),\n # path('post/record', views.button, name='record'),\n]\n","repo_name":"ddubbu/Univ-Grad-Portfolio","sub_path":"mysite/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"74410006967","text":"import re\nfrom pythonds.basic.stack import Stack\n# Обьявим все контейнеры для хранения комманд, переменных.\n# Собственно, вся логика интрепретации работает на них\n\nvariables = {}\ncommands = []\nfuncd = {}\nsave = []\nlist_of_keys = []\n\n\ndef postfix(infixexpr):\n priority_of_operations = {\"*\": 3, \"/\": 3, \"%\": 2, \"+\": 1, \"-\": 1, \"(\":0}\n opStack = Stack()\n postfixList = []\n tokenList = infixexpr.split()\n\n for token in tokenList:\n if token in \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" or token in \"0123456789\":\n postfixList.append(token)\n elif token == '(':\n opStack.push(token)\n elif token == ')':\n topToken = opStack.pop()\n while topToken != '(':\n postfixList.append(topToken)\n topToken = opStack.pop()\n else:\n while (not opStack.isEmpty()) and \\\n (priority_of_operations[opStack.peek()] >= priority_of_operations[token]):\n postfixList.append(opStack.pop())\n opStack.push(token)\n\n while not opStack.isEmpty():\n postfixList.append(opStack.pop())\n return \" \".join(postfixList)\n\n\n# Чтение файла и получение списка строк. \n# Аргументом является название файлы\ndef read_file(file_name):\n with open(file_name) as f:\n for line in f:\n if line[0] != '?': # Проверка, закоментированны ли строки \n commands.append(line)\n\n# Функция собирает логическое выражение и решает его, выводит True или False\ndef logical_eval(comm, lvl):\n del comm[0]\n for i in range(2, len(comm)):\n\n # Здесь идет замена на служебные слова python для функции eval()\n\n if comm[i] == \"not\":\n comm[i] = \"!=\"\n\n elif comm[i] == \"xor\":\n comm[i] = \"^\"\n\n elif comm[i] == \"eqv\":\n comm[i] = \"==\"\n \n # Отрезаем \"log:\"\n comm_slice = comm[2:]\n final_expression = ' '.join(comm_slice)\n # Решаем лог.выражение и выводим его\n try:\n result = eval(final_expression)\n\n if result == 0:\n result = False\n\n if result == 1:\n result = True\n\n print(\"Ответ на логическое выражение '{}' = {}\".format(final_expression, str(result)))\n variables[lvl][comm[0]] = result\n # Обработка ошибки ввода\n except Exception:\n print(\"Ошибка в введенных данных\")\n\n return comm\n\n# Функция для реализации присваивания переменных, получает два значения счетчика прохода по файлу\ndef assignment_variable(comm, lvl, first_iter, second_iter):\n if comm[second_iter + 1] == list_of_keys[0]:\n gg = re.sub(r'[^\\w\\s]', '', commands[first_iter])\n ggg = gg.split()\n lvl += 1\n variables[lvl] = {}\n # Добавляем в переменные\n for k in range(2, len(ggg)):\n variables[lvl][ggg[k]] = variables[lvl - 1][ggg[k]]\n abc = funcd[comm[second_iter + 1]] + 1\n\n work_with_variables(abc, lvl)\n\n else:\n add_variable(comm, lvl)\n\n# Функция для вычисления математических значений\n# Работает по такому же принципу, как и logical_eval()\ndef math_eval(comm, lvl):\n del comm[0]\n \n for i in range(2, len(comm)):\n try:\n comm[i] = variables[lvl][comm[i]]\n \n except Exception:\n continue\n \n comm_slice = comm[2:]\n final_expression = ' '.join(comm_slice)\n result = eval(final_expression)\n print(\"Постфиксная форма: \", postfix(str(final_expression)))\n print(\"Ответ на математическое выражение '{}' = {}\".format(final_expression, result))\n variables[lvl][comm[0]] = result\n return comm\n\n\n# Сохранение значения переменной\ndef add_variable(comm, lvl):\n try:\n int(comm[2])\n variables[lvl][comm[0]] = comm[2]\n \n except Exception:\n pass\n\n# Основная функция для работы со строками программы\ndef work_with_variables(amp, lvl):\n # Разбивает программу на список\n for i in range(amp + 1, len(commands)-1):\n comm = commands[i].split()\n \n # В зависимости от ключевого слова выполняется функции, объявленная выше\n for j in range(0, 2):\n # Пользовательский ввод переменной для работы\n if comm[j] == \"reader\":\n input_result = input(\"Введите значение переменной = \")\n variables[lvl][comm[1]] = input_result\n # Вывод переменной\n elif comm[j] == \"printer\":\n print(\"Переменная '{}' = {}\".format(comm[1], variables[lvl][comm[1]]))\n # Решение математических примеров\n elif comm[j] == \"mat:\":\n math_eval(comm, lvl)\n continue\n\n # Возврат функции\n elif comm[j] == \"return\":\n variables[0][save[2]] = variables[lvl][comm[1]]\n\n #Решение логических выражений\n elif comm[j] == \"log:\":\n logical_eval(comm, lvl)\n continue\n # Закрытие видимости, удаление значения словаря\n elif comm[j] == \"}\":\n if lvl > 1:\n del variables[lvl]\n lvl -= 1\n # Открытие видимости, добавление нового ключа\n elif comm[j] == \"{\":\n lvl += 1\n variables[lvl] = {}\n # Присваивание переменной значения\n elif comm[j] == \":=\":\n assignment_variable(comm, lvl, i, j)\n\n\n# Запуск всех функций, парсер функций и main\ndef main():\n global list_of_keys\n\n for i in range(len(commands)):\n comm = commands[i].split()\n\n if comm[0] == \"def\":\n funcd = {comm[1]: i}\n\n elif comm[0] == \"main\":\n amp = i\n lvl = 0\n variables[lvl] = {}\n list_of_keys = list(funcd.keys())\n work_with_variables(amp, lvl)\n\n# Точка входа в программу, чтение файла и запуск программы\nread_file('test.txt')\nmain()\n\n\n","repo_name":"bunsanandme/pseudo_translator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6506,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"29316041729","text":"num = int(input(\"Introduce el número: \")) \ndef factor(num): \n lista =[]\n for i in range(2,int(num)+1):\n if prime(i):\n if num%i==0:\n c =1\n while num%i**c==0:\n c +=1\n print(i)\n \n return(lista)\ndef prime(num):\n if num == 2:\n return True\n \n if num !=2 and num%2 == 0:\n return False\n \n for i in range(3,int(num**0.5)+1,2):\n if num%i==0:\n return False\n \n \n return True\nx=(factor(num))\nprint((x))","repo_name":"pabloschwarzenberg/grader","sub_path":"hito1_ej13/hito1_ej13_b6103645f0f486e515d8b8a34fe0d299.py","file_name":"hito1_ej13_b6103645f0f486e515d8b8a34fe0d299.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"37512353323","text":"from bottle import get, post, request, run \n\n@get('/') \ndef circle_area():\n return '''\n \n '''\n\n@post('/calc')\ndef circle_area():\n r = request.forms.get('radius')\n print(type(r))\n calc = int(r) * int(r) * 3.14\n return \"円の面積:\" + str(calc) + \"cm2\"\n\nrun(host='localhost', port=8080, debug=True)\n\nserver.stop()","repo_name":"oshimamasara/bottle_basic","sub_path":"calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"18982360885","text":"import os\nimport csv\nimport string\nfor folder, subs, files in os.walk('C:/Users/amishr28.ASURITE/NLP--Project-Group-16'):\n print(\"here\")\n with open(os.path.join(folder, 'English.csv'), 'w+') as dest1, open(os.path.join(folder, 'Hindi.csv'), 'w+') as dest2:\n wr1 = csv.writer(dest1)\n wr2 = csv.writer(dest2)\n for filename in files:\n if filename.endswith('en'):\n with open(os.path.join(folder, filename), 'r') as src:\n text = src.readlines()\n words = []\n for str in text:\n str = str.translate(None, string.punctuation)\n words = str.split()\n #words.append(\"EOF\")\n wr1.writerow(words)\n src.close()\n if filename.endswith('hi'):\n with open(os.path.join(folder, filename), 'r') as src:\n text = src.readlines()\n words = []\n for str in text:\n str = str.translate(None, string.punctuation)\n words = str.split()\n #words.append(\"EOF\")\n wr2.writerow(words)\n src.close()\n dest2.close()\n dest1.close()\nprint(\"Completed\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"AdityaPrasadMishra/NLP--Project-Group-16","sub_path":"CorpusExtraction.py","file_name":"CorpusExtraction.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"23507616068","text":"from cbc_sdk.errors import ApiError, ServerError, NonQueryableModel\nfrom cbc_sdk.platform import PlatformModel\nfrom cbc_sdk.platform.vulnerability_assessment import Vulnerability, VulnerabilityQuery\nfrom cbc_sdk.base import (UnrefreshableModel, BaseQuery, QueryBuilder, QueryBuilderSupportMixin,\n CriteriaBuilderSupportMixin, IterableQueryMixin, AsyncQueryMixin)\nfrom cbc_sdk.workload import NSXRemediationJob\n\nimport time\n\n\n\"\"\"\"Device Models\"\"\"\n\n\nclass Device(PlatformModel):\n \"\"\"\n Represents a device (endpoint) within the Carbon Black Cloud.\n\n ``Device`` objects are generally located through a search (using ``DeviceSearchQuery``) before they can be\n operated on.\n \"\"\"\n urlobject = \"/appservices/v6/orgs/{0}/devices\"\n urlobject_single = \"/appservices/v6/orgs/{0}/devices/{1}\"\n primary_key = \"id\"\n swagger_meta_file = \"platform/models/device.yaml\"\n\n def __init__(self, cb, model_unique_id, initial_data=None):\n \"\"\"\n Initialize the ``Device`` object.\n\n Args:\n cb (BaseAPI): Reference to API object used to communicate with the server.\n model_unique_id (str): ID of the device represented.\n initial_data (dict): Initial data used to populate the device.\n \"\"\"\n super(Device, self).__init__(cb, model_unique_id, initial_data)\n if model_unique_id is not None and initial_data is None:\n self._refresh()\n\n @classmethod\n def _query_implementation(cls, cb, **kwargs):\n \"\"\"\n Returns the appropriate query object for the ``Device`` type.\n\n Args:\n cb (BaseAPI): Reference to API object used to communicate with the server.\n **kwargs (dict): Not used, retained for compatibility.\n \"\"\"\n return DeviceSearchQuery(cls, cb)\n\n @property\n def deviceId(self):\n \"\"\"\n Warn user that Platform Devices use 'id', not 'device_id'.\n\n Platform Device APIs return 'id' in API responses, where Endpoint Standard APIs return 'deviceId'.\n\n Raises:\n AttributeError: In all cases.\n \"\"\"\n raise AttributeError(\"Platform Devices use .id property for device ID.\")\n\n def _refresh(self):\n \"\"\"\n Rereads the device data from the server.\n\n Required Permissions:\n device(READ)\n\n Returns:\n bool: ``True`` if refresh was successful, ``False`` if not.\n \"\"\"\n url = self.urlobject_single.format(self._cb.credentials.org_key, self._model_unique_id)\n resp = self._cb.get_object(url)\n self._info = resp\n self._last_refresh_time = time.time()\n return True\n\n def lr_session(self, async_mode=False):\n \"\"\"\n Retrieve a Live Response session object for this ``Device``.\n\n Required Permissions:\n org.liveresponse.session(CREATE)\n\n Returns:\n LiveResponseSession: Live Response session for the ``Device``.\n\n Raises:\n ApiError: If there is an error establishing a Live Response session for this ``Device``.\n \"\"\"\n return self._cb._request_lr_session(self._model_unique_id, async_mode=async_mode)\n\n def background_scan(self, flag):\n \"\"\"\n Set the background scan option for this device.\n\n Required Permissions:\n device.bg-scan(EXECUTE)\n\n Args:\n flag (bool): ``True`` to turn background scan on, ``False`` to turn it off.\n\n Returns:\n str: The JSON output from the request.\n \"\"\"\n return self._cb.device_background_scan([self._model_unique_id], flag)\n\n def bypass(self, flag):\n \"\"\"\n Set the bypass option for this device.\n\n Required Permissions:\n device.bypass(EXECUTE)\n\n Args:\n flag (bool): ``True`` to enable bypass, ``False`` to disable it.\n\n Returns:\n str: The JSON output from the request.\n \"\"\"\n return self._cb.device_bypass([self._model_unique_id], flag)\n\n def delete_sensor(self):\n \"\"\"\n Delete this sensor device.\n\n Required Permissions:\n device.deregistered(DELETE)\n\n Returns:\n str: The JSON output from the request.\n \"\"\"\n return self._cb.device_delete_sensor([self._model_unique_id])\n\n def uninstall_sensor(self):\n \"\"\"\n Uninstall this sensor device.\n\n Required Permissions:\n device.uninstall(EXECUTE)\n\n Returns:\n str: The JSON output from the request.\n \"\"\"\n return self._cb.device_uninstall_sensor([self._model_unique_id])\n\n def quarantine(self, flag):\n \"\"\"\n Set the quarantine option for this device.\n\n Required Permissions:\n device.quarantine(EXECUTE)\n\n Args:\n flag (bool): ``True`` to enable quarantine, ``False`` to disable it.\n\n Returns:\n str: The JSON output from the request.\n \"\"\"\n return self._cb.device_quarantine([self._model_unique_id], flag)\n\n def update_policy(self, policy_id):\n \"\"\"\n Set the current policy for this device.\n\n Required Permissions:\n device.policy(UPDATE)\n\n Args:\n policy_id (int): ID of the policy to set for the device.\n\n Returns:\n str: The JSON output from the request.\n \"\"\"\n return self._cb.device_update_policy([self._model_unique_id], policy_id)\n\n def update_sensor_version(self, sensor_version):\n \"\"\"\n Update the sensor version for this device.\n\n Required Permissions:\n org.kits(EXECUTE)\n\n Args:\n sensor_version (dict): New version properties for the sensor.\n\n Returns:\n str: The JSON output from the request.\n \"\"\"\n return self._cb.device_update_sensor_version([self._model_unique_id], sensor_version)\n\n def vulnerability_refresh(self):\n \"\"\"\n Refresh vulnerability information for the device.\n\n Required Permissions:\n vulnerabilityAssessment.data(EXECUTE)\n \"\"\"\n request = {\"action_type\": 'REFRESH'}\n url = \"/vulnerability/assessment/api/v1/orgs/{}\".format(self._cb.credentials.org_key)\n\n url += '/devices/{}/device_actions'.format(self._model_unique_id)\n\n resp = self._cb.post_object(url, body=request)\n if resp.status_code == 200:\n return resp.json()\n elif resp.status_code == 204:\n return None\n else:\n raise ServerError(error_code=resp.status_code, message=\"Device action error: {0}\".format(resp.content),\n uri=url)\n\n def get_vulnerability_summary(self, category=None):\n \"\"\"\n Get the vulnerabilities associated with this device.\n\n Required Permissions:\n vulnerabilityAssessment.data(READ)\n\n Args:\n category (string): (optional) Vulnerabilty category (OS, APP).\n\n Returns:\n dict: Summary of the vulnerabilities for this device.\n \"\"\"\n VALID_CATEGORY = [\"OS\", \"APP\"]\n\n query_params = {}\n\n url = '/vulnerability/assessment/api/v1/orgs/{}'\n\n if category and category not in VALID_CATEGORY:\n raise ApiError(\"Invalid category provided\")\n elif category:\n query_params[\"category\"] = category\n\n req_url = url.format(self._cb.credentials.org_key) + '/devices/{}/vulnerabilities/summary'.format(self.id)\n return self._cb.get_object(req_url, query_params)\n\n def get_vulnerabilties(self):\n \"\"\"\n Return a query to get an operating system or application vulnerability list for this device.\n\n Returns:\n VulnerabilityQuery: Query for searching for vulnerabilities on this device.\n \"\"\"\n return VulnerabilityQuery(Vulnerability, self._cb, self)\n\n @property\n def nsx_available(self):\n \"\"\"\n Returns whether NSX actions are available on this device.\n\n Returns:\n bool: ``True`` if NSX actions are available, ``False`` if not.\n \"\"\"\n return self._info['deployment_type'] == 'WORKLOAD' and self._info['nsx_enabled']\n\n def nsx_remediation(self, tag, set_tag=True):\n \"\"\"\n Start an NSX Remediation job on this device to change the tag.\n\n Required Permissions:\n appliances.nsx.remediation(EXECUTE)\n\n Args:\n tag (str): The NSX tag to apply to this device. Valid values are \"CB-NSX-Quarantine\",\n \"CB-NSX-Isolate\", and \"CB-NSX-Custom\".\n set_tag (bool): ``True`` to toggle the specified tag on, ``False`` to toggle it off. Default ``True``.\n\n Returns:\n NSXRemediationJob: The object representing all running jobs. ``None`` if the operation is a no-op.\n \"\"\"\n if not self.nsx_available:\n raise ApiError(\"NSX actions are not available on this device\")\n current = self._info['nsx_distributed_firewall_policy']\n if current is None:\n if not set_tag:\n return None # clearing tag is a no-op if no tag is set\n elif current == tag:\n if set_tag:\n return None # setting tag is a no-op if already set\n else:\n if set_tag:\n raise ApiError(f\"NSX tag already set to {current}, cannot set another tag without clearing it\")\n return None # clearing tag is a no-op in this case\n return NSXRemediationJob.start_request(self._cb, self.id, tag, set_tag)\n\n\nclass DeviceFacet(UnrefreshableModel):\n \"\"\"\n Represents a device field in a facet search.\n\n *Faceting* is a search technique that categorizes search results according to common attributes. This allows\n users to explore and discover information within a dataset, in this case, the set of devices.\n\n Example:\n >>> facets = api.select(Device).facets(['policy_id'])\n >>> for value in facets[0].values_:\n ... print(f\"Policy ID {value.id}: {value.total} device(s)\")\n \"\"\"\n urlobject = \"/appservices/v6/orgs/{0}/devices/_facet\"\n primary_key = \"id\"\n swagger_meta_file = \"platform/models/device_facet.yaml\"\n\n def __init__(self, cb, model_unique_id, initial_data=None):\n \"\"\"\n Initialize the ``DeviceFacet`` object.\n\n Args:\n cb (BaseAPI): Reference to API object used to communicate with the server.\n model_unique_id (str): Not used.\n initial_data (dict): Initial data used to populate the facet.\n \"\"\"\n super(DeviceFacet, self).__init__(cb, model_unique_id, initial_data, force_init=False, full_doc=True)\n self._values = [DeviceFacet.DeviceFacetValue(cb, self, item['id'], item) for item in initial_data['values']]\n\n class DeviceFacetValue(UnrefreshableModel):\n \"\"\"\n Represents a value of a particular faceted field.\n\n *Faceting* is a search technique that categorizes search results according to common attributes. This allows\n users to explore and discover information within a dataset, in this case, the set of devices.\n \"\"\"\n def __init__(self, cb, outer, model_unique_id, initial_data):\n \"\"\"\n Initialize the ``DeviceFacetValue`` object.\n\n Args:\n cb (BaseAPI): Reference to API object used to communicate with the server.\n outer (DeviceFacet): Reference to outer facet object.\n model_unique_id (str): Value ID.\n initial_data (dict): Initial data used to populate the facet value.\n \"\"\"\n super(DeviceFacet.DeviceFacetValue, self).__init__(cb, model_unique_id, initial_data, force_init=False,\n full_doc=True)\n self._outer = outer\n\n def query_devices(self):\n \"\"\"\n Set up a device query to find all devices that match this facet value.\n\n Example:\n >>> facets = api.select(Device).facets(['policy_id'])\n >>> for value in facets[0].values_:\n ... print(f\"Policy ID = {value.id}:\")\n ... for dev in value.query_devices():\n ... print(f\" {dev.name} ({dev.last_external_ip_address})\")\n\n Returns:\n DeviceQuery: A new ``DeviceQuery`` set with the criteria, which may have additional criteria added\n to it.\n \"\"\"\n query = self._cb.select(Device)\n if self._outer.field == 'policy_id':\n query.set_policy_ids([int(self.id)])\n elif self._outer.field == 'status':\n query.set_status([self.id])\n elif self._outer.field == 'os':\n query.set_os([self.id.upper()])\n elif self._outer.field == 'ad_group_id':\n query.set_ad_group_ids([int(self.id)])\n elif self._outer.field == \"cloud_provider_account_id\":\n query.set_cloud_provider_account_id([self.id])\n elif self._outer.field == \"auto_scaling_group_name\":\n query.set_auto_scaling_group_name([self.id])\n elif self._outer.field == \"virtual_private_cloud_id\":\n query.set_virtual_private_cloud_id([self.id])\n return query\n\n @classmethod\n def _query_implementation(cls, cb, **kwargs):\n \"\"\"\n Returns the appropriate query object for the Device type.\n\n Args:\n cb (BaseAPI): Reference to API object used to communicate with the server.\n **kwargs (dict): Not used, retained for compatibility.\n \"\"\"\n raise NonQueryableModel(\"use facets() on DeviceQuery to get DeviceFacet\")\n\n def _subobject(self, name):\n \"\"\"\n Returns the \"subobject value\" of the given attribute.\n\n Args:\n name (str): Name of the subobject value to be returned.\n\n Returns:\n Any: Subobject value for the attribute, or ``None`` if there is none.\n \"\"\"\n if name == 'values':\n return self._values\n return super(DeviceFacet, self)._subobject(name)\n\n @property\n def values_(self):\n \"\"\"Returns the list of facet values for this facet.\"\"\"\n return self._values\n\n\n############################################\n# Device Queries\n\nclass DeviceSearchQuery(BaseQuery, QueryBuilderSupportMixin, CriteriaBuilderSupportMixin,\n IterableQueryMixin, AsyncQueryMixin):\n \"\"\"\n Query object that is used to locate ``Device`` objects.\n\n The ``DeviceSearchQuery`` is constructed via SDK functions like the ``select()`` method on ``CBCloudAPI``.\n The user would then add a query and/or criteria to it before iterating over the results.\n \"\"\"\n VALID_OS = [\"WINDOWS\", \"ANDROID\", \"MAC\", \"IOS\", \"LINUX\", \"OTHER\"]\n VALID_STATUSES = [\"PENDING\", \"REGISTERED\", \"UNINSTALLED\", \"DEREGISTERED\",\n \"ACTIVE\", \"INACTIVE\", \"ERROR\", \"ALL\", \"BYPASS_ON\",\n \"BYPASS\", \"QUARANTINE\", \"SENSOR_OUTOFDATE\",\n \"DELETED\", \"LIVE\"]\n VALID_PRIORITIES = [\"LOW\", \"MEDIUM\", \"HIGH\", \"MISSION_CRITICAL\"]\n VALID_DEPLOYMENT_TYPES = [\"ENDPOINT\", \"WORKLOAD\", \"VDI\", \"AWS\", \"AZURE\", \"GCP\"]\n VALID_FACET_FIELDS = [\"policy_id\", \"status\", \"os\", \"ad_group_id\", \"cloud_provider_account_id\",\n \"auto_scaling_group_name\", \"virtual_private_cloud_id\"]\n\n def __init__(self, doc_class, cb):\n \"\"\"\n Initialize the ``DeviceSearchQuery``.\n\n Args:\n doc_class (class): The model class that will be returned by this query.\n cb (BaseAPI): Reference to API object used to communicate with the server.\n \"\"\"\n self._doc_class = doc_class\n self._cb = cb\n self._count_valid = False\n super(DeviceSearchQuery, self).__init__()\n\n self._query_builder = QueryBuilder()\n self._criteria = {}\n self._time_filter = {}\n self._exclusions = {}\n self._sortcriteria = {}\n self.max_rows = -1\n\n def _update_exclusions(self, key, newlist):\n \"\"\"\n Updates the exclusion criteria being collected for a query.\n\n Assumes the specified criteria item is defined as a list; the list passed in will be set as the value for this\n criteria item, or appended to the existing one if there is one.\n\n Args:\n key (str): The key for the criteria item to be set.\n newlist (list): List of values to be set for the criteria item.\n \"\"\"\n oldlist = self._exclusions.get(key, [])\n self._exclusions[key] = oldlist + newlist\n\n def set_ad_group_ids(self, ad_group_ids):\n \"\"\"\n Restricts the devices that this query is performed on to the specified AD group IDs.\n\n Args:\n ad_group_ids (list): List of AD group IDs to restrict the search to.\n\n Returns:\n DeviceSearchQuery: This instance.\n \"\"\"\n if not all(isinstance(ad_group_id, int) for ad_group_id in ad_group_ids):\n raise ApiError(\"One or more invalid AD group IDs\")\n self._update_criteria(\"ad_group_id\", ad_group_ids)\n return self\n\n def set_device_ids(self, device_ids):\n \"\"\"\n Restricts the devices that this query is performed on to the specified device IDs.\n\n Args:\n device_ids (list): List of device IDs to restrict the search to.\n\n Returns:\n DeviceSearchQuery: This instance.\n \"\"\"\n if not all(isinstance(device_id, int) for device_id in device_ids):\n raise ApiError(\"One or more invalid device IDs\")\n self._update_criteria(\"id\", device_ids)\n return self\n\n def set_last_contact_time(self, *args, **kwargs):\n \"\"\"\n Restricts the devices that this query is performed on to the specified last contact time.\n\n Args:\n *args (list): Not used, retained for compatibility.\n **kwargs (dict): Keyword arguments to this function. The critical ones are \"start\" (the start time),\n \"end\" (the end time), and \"range\" (the range value).\n\n Returns:\n DeviceSearchQuery: This instance.\n \"\"\"\n if kwargs.get(\"start\", None) and kwargs.get(\"end\", None):\n if kwargs.get(\"range\", None):\n raise ApiError(\"cannot specify range= in addition to start= and end=\")\n stime = kwargs[\"start\"]\n if not isinstance(stime, str):\n stime = stime.isoformat()\n etime = kwargs[\"end\"]\n if not isinstance(etime, str):\n etime = etime.isoformat()\n self._time_filter = {\"start\": stime, \"end\": etime}\n elif kwargs.get(\"range\", None):\n if kwargs.get(\"start\", None) or kwargs.get(\"end\", None):\n raise ApiError(\"cannot specify start= or end= in addition to range=\")\n self._time_filter = {\"range\": kwargs[\"range\"]}\n else:\n raise ApiError(\"must specify either start= and end= or range=\")\n return self\n\n def set_os(self, operating_systems):\n \"\"\"\n Restricts the devices that this query is performed on to the specified operating systems.\n\n Args:\n operating_systems (list): List of operating systems to restrict search to. Valid values in this list are\n \"WINDOWS\", \"ANDROID\", \"MAC\", \"IOS\", \"LINUX\", and \"OTHER\".\n\n Returns:\n DeviceSearchQuery: This instance.\n \"\"\"\n if not all((osval in DeviceSearchQuery.VALID_OS) for osval in operating_systems):\n raise ApiError(\"One or more invalid operating systems\")\n self._update_criteria(\"os\", operating_systems)\n return self\n\n def set_policy_ids(self, policy_ids):\n \"\"\"\n Restricts the devices that this query is performed on to the specified policy IDs.\n\n Args:\n policy_ids (list): List of policy IDs to restrict the search to.\n\n Returns:\n DeviceSearchQuery: This instance.\n \"\"\"\n if not all(isinstance(policy_id, int) for policy_id in policy_ids):\n raise ApiError(\"One or more invalid policy IDs\")\n self._update_criteria(\"policy_id\", policy_ids)\n return self\n\n def set_status(self, statuses):\n \"\"\"\n Restricts the devices that this query is performed on to the specified status values.\n\n Args:\n statuses (list): List of statuses to restrict search to. Valid values in this list are \"PENDING\",\n \"REGISTERED\", \"UNINSTALLED\", \"DEREGISTERED\", \"ACTIVE\", \"INACTIVE\", \"ERROR\", \"ALL\",\n \"BYPASS_ON\", \"BYPASS\", \"QUARANTINE\", \"SENSOR_OUTOFDATE\", \"DELETED\", and \"LIVE\".\n\n Returns:\n DeviceSearchQuery: This instance.\n \"\"\"\n if not all((stat in DeviceSearchQuery.VALID_STATUSES) for stat in statuses):\n raise ApiError(\"One or more invalid status values\")\n self._update_criteria(\"status\", statuses)\n return self\n\n def set_target_priorities(self, target_priorities):\n \"\"\"\n Restricts the devices that this query is performed on to the specified target priority values.\n\n Args:\n target_priorities (list): List of priorities to restrict search to. Valid values in this list are \"LOW\",\n \"MEDIUM\", \"HIGH\", and \"MISSION_CRITICAL\".\n\n Returns:\n DeviceSearchQuery: This instance.\n \"\"\"\n if not all((prio in DeviceSearchQuery.VALID_PRIORITIES) for prio in target_priorities):\n raise ApiError(\"One or more invalid target priority values\")\n self._update_criteria(\"target_priority\", target_priorities)\n return self\n\n def set_cloud_provider_account_id(self, account_ids):\n \"\"\"\n Restricts the devices that this query is performed on to the specified cloud provider account IDs.\n\n Args:\n account_ids (list): List of account IDs to restrict search to.\n\n Returns:\n DeviceSearchQuery: This instance.\n \"\"\"\n self._update_criteria(\"cloud_provider_account_id\", account_ids)\n return self\n\n def set_auto_scaling_group_name(self, group_names):\n \"\"\"\n Restricts the devices that this query is performed on to the specified auto scaling group names.\n\n Args:\n group_names (list): List of group names to restrict search to.\n\n Returns:\n DeviceSearchQuery: This instance.\n \"\"\"\n self._update_criteria(\"auto_scaling_group_name\", group_names)\n return self\n\n def set_virtual_private_cloud_id(self, cloud_ids):\n \"\"\"\n Restricts the devices that this query is performed on to the specified virtual private cloud IDs.\n\n Args:\n cloud_ids (list): List of cloud IDs to restrict search to.\n\n Returns:\n DeviceSearchQuery: This instance.\n \"\"\"\n self._update_criteria(\"virtual_private_cloud_id\", cloud_ids)\n return self\n\n def set_exclude_sensor_versions(self, sensor_versions):\n \"\"\"\n Restricts the devices that this query is performed on to exclude specified sensor versions.\n\n Args:\n sensor_versions (list): List of sensor versions to be excluded.\n\n Returns:\n DeviceSearchQuery: This instance.\n \"\"\"\n if not all(isinstance(v, str) for v in sensor_versions):\n raise ApiError(\"One or more invalid sensor versions\")\n self._update_exclusions(\"sensor_version\", sensor_versions)\n return self\n\n def sort_by(self, key, direction=\"ASC\"):\n \"\"\"\n Sets the sorting behavior on a query's results.\n\n Example:\n >>> cb.select(Device).sort_by(\"status\")\n\n Args:\n key (str): The key in the schema to sort by.\n direction (str): The sort order, either \"ASC\" or \"DESC\".\n\n Returns:\n DeviceSearchQuery: This instance.\n \"\"\"\n if direction not in CriteriaBuilderSupportMixin.VALID_DIRECTIONS:\n raise ApiError(\"invalid sort direction specified\")\n self._sortcriteria = {\"field\": key, \"order\": direction}\n return self\n\n def set_deployment_type(self, deployment_type):\n \"\"\"\n Restricts the devices that this query is performed on to the specified deployment types.\n\n Args:\n deployment_type (list): List of deployment types to restrict search to.\n\n Returns:\n DeviceSearchQuery: This instance.\n \"\"\"\n if not all((type in DeviceSearchQuery.VALID_DEPLOYMENT_TYPES) for type in deployment_type):\n raise ApiError(\"invalid deployment_type specified\")\n self._update_criteria(\"deployment_type\", deployment_type)\n return self\n\n def set_max_rows(self, max_rows):\n \"\"\"\n Sets the max number of devices to fetch in a singular query\n\n Args:\n max_rows (integer): Max number of devices. Must be in the range (0, 10000).\n\n Returns:\n DeviceSearchQuery: This instance.\n \"\"\"\n if max_rows < 0 or max_rows > 10000:\n raise ApiError(\"Max rows must be between 0 and 10000\")\n self.max_rows = max_rows\n return self\n\n def _build_request(self, from_row, max_rows):\n \"\"\"\n Creates the request body for an API call.\n\n Args:\n from_row (int): The row to start the query at.\n max_rows (int): The maximum number of rows to be returned.\n\n Returns:\n dict: The complete request body.\n \"\"\"\n mycrit = self._criteria\n if self._time_filter:\n mycrit[\"last_contact_time\"] = self._time_filter\n request = {}\n if mycrit:\n request[\"criteria\"] = mycrit\n if self._exclusions:\n request[\"exclusions\"] = self._exclusions\n query = self._query_builder._collapse()\n if query:\n request[\"query\"] = query\n if from_row > 1:\n request[\"start\"] = from_row\n if max_rows >= 0:\n request[\"rows\"] = max_rows\n elif self.max_rows >= 0:\n request[\"rows\"] = self.max_rows\n if self._sortcriteria != {}:\n request[\"sort\"] = [self._sortcriteria]\n return request\n\n def _build_url(self, tail_end):\n \"\"\"\n Creates the URL to be used for an API call.\n\n Args:\n tail_end (str): String to be appended to the end of the generated URL.\n\n Returns:\n str: The complete URL.\n \"\"\"\n url = self._doc_class.urlobject.format(self._cb.credentials.org_key) + tail_end\n return url\n\n def _count(self):\n \"\"\"\n Returns the number of results from the run of this query.\n\n Required Permissions:\n device(READ)\n \"\"\"\n if self._count_valid:\n return self._total_results\n\n url = self._build_url(\"/_search\")\n request = self._build_request(0, -1)\n resp = self._cb.post_object(url, body=request)\n result = resp.json()\n\n self._total_results = result[\"num_found\"]\n self._count_valid = True\n\n return self._total_results\n\n def _perform_query(self, from_row=1, max_rows=-1):\n \"\"\"\n Performs the query and returns the results of the query in an iterable fashion.\n\n Note:\n Device v6 API uses base 1 instead of 0.\n\n Required Permissions:\n device(READ)\n\n Args:\n from_row (int): The row to start the query at (default 1).\n max_rows (int): The maximum number of rows to be returned (default -1, meaning \"all\").\n\n Yields:\n Device: The individual devices which match the query.\n \"\"\"\n url = self._build_url(\"/_search\")\n current = from_row\n numrows = 0\n still_querying = True\n while still_querying:\n request = self._build_request(current, max_rows)\n resp = self._cb.post_object(url, body=request)\n result = resp.json()\n\n self._total_results = result[\"num_found\"]\n self._count_valid = True\n\n results = result.get(\"results\", [])\n for item in results:\n yield self._doc_class(self._cb, item[\"id\"], item)\n current += 1\n numrows += 1\n\n if max_rows > 0 and numrows == max_rows:\n still_querying = False\n break\n\n from_row = current\n if current >= self._total_results:\n still_querying = False\n break\n\n def _run_async_query(self, context):\n \"\"\"\n Executed in the background to run an asynchronous query on devices.\n\n Required Permissions:\n device(READ)\n\n Args:\n context (object): The context returned by _init_async_query. May be ``None``.\n\n Returns:\n Any: Result of the async query, which is then returned by the future.\n \"\"\"\n url = self._build_url(\"/_search\")\n self._total_results = 0\n self._count_valid = False\n output = []\n while not self._count_valid or len(output) < self._total_results:\n request = self._build_request(len(output), -1)\n resp = self._cb.post_object(url, body=request)\n result = resp.json()\n\n if not self._count_valid:\n self._total_results = result[\"num_found\"]\n self._count_valid = True\n\n results = result.get(\"results\", [])\n output += [self._doc_class(self._cb, item[\"id\"], item) for item in results]\n return output\n\n def facets(self, fieldlist, max_rows=0):\n \"\"\"\n Return information about the facets for all matching devices, using the defined criteria.\n\n Example:\n >>> query = api.select(Device).where('')\n >>> facets = query.facets(['policy_id', 'status', 'os', 'ad_group_id'])\n >>> for f in facets:\n ... print(f\"Field {f.field} - {len(f.values_)} distinct values\")\n\n Required Permissions:\n device(READ)\n\n Args:\n fieldlist (list[str]): List of facet field names. Valid names are \"policy_id\", \"status\", \"os\",\n \"ad_group_id\", \"cloud_provider_account_id\", \"auto_scaling_group_name\",\n and \"virtual_private_cloud_id\".\n max_rows (int): The maximum number of rows to return. 0 means return all rows.\n\n Returns:\n list[DeviceFacet]: A list of facet information.\n \"\"\"\n if not fieldlist:\n raise ApiError(\"At least one term field must be specified\")\n if not all((field in DeviceSearchQuery.VALID_FACET_FIELDS) for field in fieldlist):\n raise ApiError(\"One or more invalid term field names\")\n request = self._build_request(-1, -1)\n if 'rows' in request:\n del request['rows']\n if 'sort' in request:\n del request['sort']\n terms = {'fields': fieldlist}\n if max_rows > 0:\n terms['rows'] = max_rows\n request['terms'] = terms\n url = self._build_url(\"/_facet\")\n resp = self._cb.post_object(url, body=request)\n result = resp.json()\n return [DeviceFacet(self._cb, None, item) for item in result['results']]\n\n def download(self):\n \"\"\"\n Uses the query parameters that have been set to download all device listings in CSV format.\n\n Example:\n >>> cb.select(Device).set_status([\"ALL\"]).download()\n\n Required Permissions:\n device(READ)\n\n Returns:\n str: The CSV raw data as returned from the server.\n\n Raises:\n ApiError: If status values have not been set before calling this function.\n \"\"\"\n tmp = self._criteria.get(\"status\", [])\n if not tmp:\n raise ApiError(\"at least one status must be specified to download\")\n query_params = {\"status\": \",\".join(tmp)}\n tmp = self._criteria.get(\"ad_group_id\", [])\n if tmp:\n query_params[\"ad_group_id\"] = \",\".join([str(t) for t in tmp])\n tmp = self._criteria.get(\"policy_id\", [])\n if tmp:\n query_params[\"policy_id\"] = \",\".join([str(t) for t in tmp])\n tmp = self._criteria.get(\"target_priority\", [])\n if tmp:\n query_params[\"target_priority\"] = \",\".join(tmp)\n tmp = self._query_builder._collapse()\n if tmp:\n query_params[\"query_string\"] = tmp\n if self._sortcriteria:\n query_params[\"sort_field\"] = self._sortcriteria[\"field\"]\n query_params[\"sort_order\"] = self._sortcriteria[\"order\"]\n url = self._build_url(\"/_search/download\")\n return self._cb.get_raw_data(url, query_params)\n\n def _bulk_device_action(self, action_type, options=None):\n \"\"\"\n Perform a bulk action on all devices matching the current search criteria.\n\n Required Permissions:\n Dependent on the action_type.\n\n Args:\n action_type (str): The action type to be performed.\n options (dict): Any options for the bulk device action.\n\n Returns:\n str: The JSON output from the request.\n \"\"\"\n request = {\"action_type\": action_type, \"search\": self._build_request(0, -1)}\n if options:\n request[\"options\"] = options\n return self._cb._raw_device_action(request)\n\n def background_scan(self, scan):\n \"\"\"\n Set the background scan option for the specified devices.\n\n Required Permissions:\n device.bg-scan(EXECUTE)\n\n Args:\n scan (bool): ``True`` to turn background scan on, ``False`` to turn it off.\n\n Returns:\n str: The JSON output from the request.\n \"\"\"\n return self._bulk_device_action(\"BACKGROUND_SCAN\", self._cb._action_toggle(scan))\n\n def bypass(self, enable):\n \"\"\"\n Set the bypass option for the specified devices.\n\n Required Permissions:\n device.bypass(EXECUTE)\n\n Args:\n enable (bool): ``True`` to enable bypass, ``False`` to disable it.\n\n Returns:\n str: The JSON output from the request.\n \"\"\"\n return self._bulk_device_action(\"BYPASS\", self._cb._action_toggle(enable))\n\n def delete_sensor(self):\n \"\"\"\n Delete the specified sensor devices.\n\n Required Permissions:\n device.deregistered(DELETE)\n\n Returns:\n str: The JSON output from the request.\n \"\"\"\n return self._bulk_device_action(\"DELETE_SENSOR\")\n\n def uninstall_sensor(self):\n \"\"\"\n Uninstall the specified sensor devices.\n\n Required Permissions:\n device.uninstall(EXECUTE)\n\n Returns:\n str: The JSON output from the request.\n \"\"\"\n return self._bulk_device_action(\"UNINSTALL_SENSOR\")\n\n def quarantine(self, enable):\n \"\"\"\n Set the quarantine option for the specified devices.\n\n Required Permissions:\n device.quarantine(EXECUTE)\n\n Args:\n enable (bool): ``True`` to enable quarantine, ``False`` to disable it.\n\n Returns:\n str: The JSON output from the request.\n \"\"\"\n return self._bulk_device_action(\"QUARANTINE\", self._cb._action_toggle(enable))\n\n def update_policy(self, policy_id):\n \"\"\"\n Set the current policy for the specified devices.\n\n Required Permissions:\n device.policy(UPDATE)\n\n Args:\n policy_id (int): ID of the policy to set for the devices.\n\n Returns:\n str: The JSON output from the request.\n \"\"\"\n return self._bulk_device_action(\"UPDATE_POLICY\", {\"policy_id\": policy_id})\n\n def update_sensor_version(self, sensor_version):\n \"\"\"\n Update the sensor version for the specified devices.\n\n Required Permissions:\n org.kits(EXECUTE)\n\n Args:\n sensor_version (dict): New version properties for the sensor.\n\n Returns:\n str: The JSON output from the request.\n \"\"\"\n return self._bulk_device_action(\"UPDATE_SENSOR_VERSION\", {\"sensor_version\": sensor_version})\n","repo_name":"carbonblack/carbon-black-cloud-sdk-python","sub_path":"src/cbc_sdk/platform/devices.py","file_name":"devices.py","file_ext":"py","file_size_in_byte":36422,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"77"}
+{"seq_id":"10590881736","text":"from random import random\nfrom tkinter import *\nimport tkinter as tk\nimport random\nimport tkinter.messagebox as mb\nwindow = tk.Tk()\nwindow.title('Крестики-нолики')\nwindow.geometry('380x375')\nwindow.resizable(width=False, height=False)\ngame = [None] * 9\ngame_left = list(range(9))\ndef push(a):\n global game\n global game_left\n game[a] = 'X'\n buttons[a].config(text = 'X', font= ('Verdana', 13, 'bold'), bg=\"yellow\", state = 'disable')\n game_left.remove(a)\n if check_win('X'):\n msg = \"Вы победили!\"\n mb.showinfo(\"Game Over\", msg)\n else:\n if (len(game_left) > 1):\n t = random.choice(game_left)\n game[t] = 'O'\n buttons[t].config(text = 'O', state = 'disable')\n game_left.remove(t)\n if check_win('O'):\n msg = \"Вы проиграли!\"\n mb.showinfo(\"Game Over\", msg)\n else:\n msg = \"Игра окончена!\"\n mb.showinfo(\"Game Over\", msg)\ndef check_win(n):\n global game\n if (game[0] == n and game[1] == n and game[2] == n) or (game[3] == n and game[4] == n and game[5] == n) or (game[6] == n and game[7] == n and game[8] == n)\\\n or (game[0] == n and game[3] == n and game[6] == n) or (game[1] == n and game[4] == n and game[7] == n) or (game[2] == n and game[5] == n and game[8] == n)\\\n or (game[0] == n and game[4] == n and game[8] == n) or (game[2] == n and game[4] == n and game[6] == n):\n return True\nbuttons = [Button(width=10, height=7, bg='blue', command=lambda x=i: push(x)) for i in range(9)]\nrow =1; col =0\nfor i in range(9):\n buttons[i].grid(row=row, column=col)\n col +=1\n if col == 3:\n row +=1\n col = 0\nwindow.mainloop()","repo_name":"scorysd/GB_Python_Homework_9","sub_path":"Criss-cross.py","file_name":"Criss-cross.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"32887734908","text":"from homeassistant.components.sensor import SensorEntity, SensorEntityDescription\nfrom homeassistant.const import STATE_UNAVAILABLE\nfrom homeassistant.helpers.device_registry import DeviceEntryType\nfrom homeassistant.helpers.entity import DeviceInfo\nfrom homeassistant.helpers.update_coordinator import CoordinatorEntity\n\nfrom . import EcologiUpdateCoordinator, DOMAIN\n\n\nclass EcologiSensorEntity(CoordinatorEntity[EcologiUpdateCoordinator], SensorEntity):\n \"\"\"Representation of an Ecologi sensor.\"\"\"\n\n entity_description: SensorEntityDescription\n\n def __init__(\n self,\n coordinator: EcologiUpdateCoordinator,\n description: SensorEntityDescription,\n ):\n \"\"\"Initialize the sensor and set the update coordinator.\"\"\"\n super().__init__(coordinator)\n self.entity_description = description\n self._attr_name = f\"{self.coordinator.username} {self.entity_description.name}\"\n self._attr_unique_id = f\"{self.coordinator.username}_{description.key}\"\n\n @property\n def native_value(self) -> str:\n if self.entity_description.key == \"trees\":\n return str(self.coordinator.data.get(\"trees\", STATE_UNAVAILABLE))\n if self.entity_description.key == \"carbon_offset\":\n return str(self.coordinator.data.get(\"carbonOffset\", STATE_UNAVAILABLE))\n\n @property\n def device_info(self) -> DeviceInfo:\n \"\"\"Return the device info.\"\"\"\n return DeviceInfo(\n name=f\"Ecologi ({self.coordinator.username})\",\n entry_type=DeviceEntryType.SERVICE,\n identifiers={(DOMAIN, self.coordinator.username)},\n manufacturer=\"Ecologi\",\n configuration_url=f\"https://ecologi.com/{self.coordinator.username}\",\n )\n","repo_name":"owenvoke/hass-ecologi","sub_path":"custom_components/ecologi/entity.py","file_name":"entity.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"4338011713","text":"# -*- coding: utf-8 -*-\n\nimport wtforms\nimport wtforms.fields.html5\nfrom baseframe.forms import Form, RichTextField\n\n__all__ = ['ParticipantForm']\n\n\nclass ParticipantForm(Form):\n skill_levels = [\n ('Beginner', 'Beginner'),\n ('Intermediate', 'Intermediate'),\n ('Advanced', 'Advanced')\n ]\n\n reason_to_join = RichTextField(\"Reason To Join\",\n description=\"Why would you love to join Hacknight\",\n validators=[wtforms.validators.Required()],\n content_css=\"/static/css/editor.css\")\n phone_no = wtforms.TextField(\"Telephone No\", description=\"Telephone No\",\n validators=[wtforms.validators.Required(), wtforms.validators.length(max=15)])\n email = wtforms.fields.html5.EmailField(\"Email\",\n description=\"Email Address, We will never spam you .\",\n validators=[wtforms.validators.Required(), wtforms.validators.length(max=80)])\n job_title = wtforms.TextField(\"Job Title\",\n description=\"What is your job title? E.G: Senior Software \"\n \"Engineer at Awesome company\",\n validators=[wtforms.validators.Optional(), wtforms.validators.length(max=120)])\n company = wtforms.TextField(\"Company\", description=\"Company Name\",\n validators=[wtforms.validators.Optional(), wtforms.validators.length(max=1200)])\n skill_level = wtforms.RadioField(\"Skill Level\", description=\"What is your skill level?\",\n choices=skill_levels)\n","repo_name":"hasgeek/hacknight","sub_path":"hacknight/forms/participant.py","file_name":"participant.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"77"}
+{"seq_id":"15761946748","text":"from pokemon import Pokemon\nimport random\nfrom tipo_arma import TipoArma\n\nclass PokemonAir(Pokemon):\n '''\n Hereda de la clase Pokemon y le modificamos su defensa.\n @attributes ID: int, identificación del pokemon.\n @attributes nombre: str, nombre del pokemon.\n @attributes arma: enum, tipo de arma del pokemon.\n @attributes vida: int, vida del pokemon.\n @attributes ataque: int, ataque del pokemon.\n @attributes defensa: int, defensa del pokemon.\n @method __init__: constructor de la clase\n @method defensa_pokemon: dependiendo del número el ataque tendrá más efecto o ninguno.\n '''\n def __init__(self, ID, nombre, arma, vida, ataque, defensa):\n super().__init__(ID, nombre, arma, vida, ataque, defensa)\n \n def defensa_pokemon(self, daño):\n n = random.randint(1,2)\n if n == 1:\n \n if self.defensa >= daño:\n return False #no ha recibido daño\n else:\n self.vida = self.vida - (daño - self.defensa) \n return True \n else: \n return False\n \n\n \ndef main():\n '''\n Comprueba que esté bien la programación de la clase.\n @param: None\n @return: None\n '''\n\n print(\"=================================================================.\")\n print(\"Test Caso 1: Crear un pokemon.\")\n print(\"=================================================================.\")\n pokemon_1 = PokemonAir(1, \"Pidgey\", TipoArma.CABEZAZO, 100, 8, 7)\n\n if pokemon_1.get_nombre() == \"Pidgey\":\n print(\"Has pasado el test. El parámetro get_nombre se ha puesto correctamente.\")\n else:\n print(\"Has suspendido el test. Revisa el métido __init__().\")\n\n if pokemon_1.get_arma().name == \"CABEZAZO\":\n print(\"Has pasado el test. El parámetro get_arma.nombre se ha puesto correctamente.\")\n else:\n print(\"Has suspendido el test. Revisa el métido __init__().\")\n\n if pokemon_1.get_salud() == 100:\n print(\"Has pasado el test. El parámetro get_salud se ha puesto correctamente.\")\n else:\n print(\"Has suspendido el test. Revisa el métido __init__().\")\n\n if pokemon_1.get_ataque() == 8:\n print(\"Has pasado el test. El parámetro get_arma se ha puesto correctamente.\")\n else:\n print(\"Has suspendido el test. Revisa el métido __init__().\")\n\n if pokemon_1.get_defensa() == 7:\n print(\"Has pasado el test. El parámetro get_defensa se ha puesto correctamente.\")\n else:\n print(\"Has suspendido el test. Revisa el métido __init__().\")\n\n\n print(\"=================================================================.\")\n print(\"Test Caso 2: Lenguaje humano del objeto.\")\n print(\"=================================================================.\")\n pokemon_2 = PokemonAir(7, \"Pidgey\", TipoArma.CABEZAZO, 100, 7, 6)\n\n if pokemon_2.descripcion_pokemon() == \"Pokemon ID: 7 se llama Pidgey, su arma es: CABEZAZO, tiene 100 de vida, una fuerza de ataque 7 y una defensa de 6\":\n print(\"Has pasado el test. El lenguaje humano del objeto ha sido implementado correctamente.\")\n else:\n print(\"Has suspendido el test. Revisa el método __str__().\" + \" RESULTADO: \" + pokemon_2.descripcion_pokemon())\n\n\n print(\"=================================================================.\")\n print(\"Test Caso 3: El pokemon está vivo?¿?.\")\n print(\"=================================================================.\")\n pokemon_3 = PokemonAir(3, \"Pidgey\", TipoArma.PATADA, 97, 8, 7)\n\n if pokemon_3.estas_vivo():\n pokemon_was_hit = pokemon_3.defensa_pokemon(200) # With this the Pokemon should be retired.\n\n if pokemon_was_hit:\n if not pokemon_3.estas_vivo():\n print(\"Has pasado el test. El método estas_vivo() ha sido implementado correctamente.\")\n else:\n print(\"Has suspendido el test. Revisa el métido estas_vivo().\")\n else:\n if pokemon_3.estas_vivo():\n print(\"Has pasado el test. El método estas_vivo() ha sido implementado correctamente.\")\n else:\n print(\"Has suspendido el test. Revisa el métido estas_vivo().\")\n \n else:\n print(\"Has suspendido el test. Revisa el métido estas_vivo().\")\n\n\n print(\"=================================================================.\")\n print(\"Test Caso 4: Revisando la defensa durante una pelea.\")\n print(\"=================================================================.\")\n pokemon_4 = PokemonAir(4, \"Pidgey\", TipoArma.CODAZO, 93, 9, 5)\n\n pokemon_was_hit = pokemon_4.defensa_pokemon(70)\n\n if pokemon_was_hit:\n if pokemon_4.get_salud() == 28:\n print(\"Has pasado el test. El método defensa_pokemon() ha sido implementado correctamente.\")\n else:\n print(\"Has suspendido el test. Revisa el métido defensa_pokemon().\")\n else:\n if pokemon_4.get_salud() == 93:\n print(\"Has pasado el test. El método defensa_pokemon() ha sido implementado correctamente.\")\n else:\n print(\"Has suspendido el test. Revisa el métido defensa_pokemon().\")\n\n\n print(\"=================================================================.\")\n print(\"Test Caso 5: Revisando el ataque durante una pelea.\")\n print(\"=================================================================.\")\n pokemon_5 = PokemonAir(5, \"Pidgey\", TipoArma.PUÑETAZO, 99, 10, 8)\n pokemon_6 = PokemonAir(6, \"Pidgey\", TipoArma.PUÑETAZO, 99, 9, 6)\n\n pokemon_was_hit = pokemon_6.ataque_pokemon(pokemon_5)\n\n if pokemon_was_hit:\n if pokemon_6.get_salud() == 95:\n print(\"Has pasado el test. El método ataque_pokemon() ha sido implementado correctamente.\")\n else:\n print(\"Has suspendido el test. Revisa el métido ataque_pokemon().\")\n else:\n if pokemon_6.get_salud() == 99:\n print(\"Has pasado el test. El método ataque_pokemon() ha sido implementado correctamente.\")\n else:\n print(\"Has suspendido el test. Revisa el métido ataque_pokemon().\")\n\n\n\n# Checking whether this module is executed just itself alone.\nif __name__ == \"__main__\":\n main()\n\n\n# EOF\n","repo_name":"andmansim/Parcial-del-8","sub_path":"clases/pokemon_aire.py","file_name":"pokemon_aire.py","file_ext":"py","file_size_in_byte":6207,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"36552623234","text":"from openerp import models, fields, api\n\n\nclass ProductTemplate(models.Model):\n _inherit = 'product.template'\n\n feed_machine_product_id = fields.Char(string='External Id')\n\n\nclass Product_product(models.Model):\n _inherit = 'product.product'\n\n @api.multi\n def name_get(self):\n displayName = []\n for product in self:\n if product.product_tmpl_id.feed_machine_product_id:\n displayName.append(\n (product.id, product.name_template + '-' +\n product.product_tmpl_id.feed_machine_product_id))\n else:\n displayName.append((product.id, product.name_template))\n return displayName\n","repo_name":"grottas/odoo-addons","sub_path":"feed_machine_connector/models/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"77"}
+{"seq_id":"42446964636","text":"\"\"\"Support for Bus Auditor Device Information.\"\"\"\nfrom math import factorial\nfrom expliot.core.interfaces.busauditor import BusAuditor\nfrom expliot.core.tests.test import TCategory, Test, TLog, TTarget\nfrom expliot.plugins.busauditor import (\n JTAG_REFERENCE, DEFAFULT_START, DEFAFULT_END,\n DEFAULT_VOLTS, VOLTAGE_RANGE, CHANNEL_MIN, CHANNEL_MAX\n)\n\n\n# pylint: disable=bare-except\nclass BaJtagScan(Test):\n \"\"\"\n Test selected channels for JTAG communication protocol.\n\n Output Format:\n # TRST is optional, dependes if it is included by user in jtag scan\n [\n {\n \"jtag_idcode\": \"0x4ba00477\",\n \"pins\": {\n \"trst\": 4, # \"TRST\" pin included in jtag scan\n \"tck\": 0,\n \"tms\": 1,\n \"tdo\": 3,\n \"tdi\": 2\n }\n },\n {\n \"jtag_idcode\": \"0x06431041\",\n \"pins\": {\n \"trst\": 4, # \"TRST\" pin included in jtag scan\n \"tck\": 0,\n \"tms\": 1,\n \"tdo\": 3,\n \"tdi\": 2\n }\n },\n # ... May be zero or more entries.\n # If zero JTAG devices found the above dict will not be present\n ]\n \"\"\"\n\n def __init__(self):\n \"\"\"Initialize the test.\"\"\"\n super().__init__(\n name=\"jtagscan\",\n summary=\"JTAG port scan\",\n descr=\"This plugin scans JTAG port for JTAG device id, JTAG pins \"\n \"(TMS, TCK, TDO, TDI and TRST) on the target hardware. \"\n \"TRST pin scan is optional and depends upon target HW, if TRST pin \"\n \"is active on target HW, then it must be include in scan. \"\n \"You need to connect Bus Auditor channels (pins) to the suspected \"\n \"pinouts on the target pcb board. \"\n \"Bus Auditor pins must be connected in a sequential range and \"\n \"specified by the start and end pin arguments. \"\n \"If you are seeing permission issues, kindly add a udev rule for \"\n \"your user for the Bus Auditor device.\",\n author=\"Dattatray Hinge\",\n email=\"dattatray@expliot.io\",\n ref=[JTAG_REFERENCE],\n category=TCategory(TCategory.BUS_AUDITOR, TCategory.HW, TCategory.RECON),\n target=TTarget(TTarget.GENERIC, TTarget.GENERIC, TTarget.GENERIC),\n )\n\n self.argparser.add_argument(\n \"-i\",\n \"--include_trst\",\n action=\"store_true\",\n help=\"Include TRST pin in scan\",\n )\n\n self.argparser.add_argument(\n \"-s\",\n \"--start\",\n type=int,\n default=DEFAFULT_START,\n help=\"First Bus Auditor channel for the scan. If not specified, \"\n \"it will start the scan from channel ({})\".format(DEFAFULT_START),\n )\n\n self.argparser.add_argument(\n \"-e\",\n \"--end\",\n type=int,\n default=DEFAFULT_END,\n help=\"Last Bus Auditor channel for the scan. If not specified, \"\n \"it will scan until channel ({})\".format(DEFAFULT_END),\n )\n\n self.argparser.add_argument(\n \"-v\",\n \"--volts\",\n type=str,\n default=DEFAULT_VOLTS,\n help=\"Target voltage out. \"\n \"Supported target volts are ({}), ({}), and ({}) If not specified, \"\n \"target voltage will be ({}) volts\".format(\n VOLTAGE_RANGE[0],\n VOLTAGE_RANGE[1],\n VOLTAGE_RANGE[2],\n DEFAULT_VOLTS\n ),\n )\n\n def execute(self):\n \"\"\"Execute the test.\"\"\"\n possible_permutations = 0\n\n # Start channel cannot be less than zero or greater than 15\n if self.args.start < CHANNEL_MIN or self.args.start > CHANNEL_MAX:\n self.result.setstatus(\n passed=False,\n reason=\"Invalid start channel.\"\n )\n return\n\n # End channel cannot be less than zero or greater than 15\n if self.args.end < CHANNEL_MIN or self.args.end > CHANNEL_MAX:\n self.result.setstatus(\n passed=False,\n reason=\"Invalid end channel.\"\n )\n return\n\n # Start and End channel cannot be same\n if self.args.start == self.args.end:\n self.result.setstatus(\n passed=False,\n reason=\"Same start and end channel.\"\n )\n return\n\n # Start > End channel\n if self.args.start > self.args.end:\n self.result.setstatus(\n passed=False,\n reason=\"Start channel greater than end channel.\"\n )\n return\n\n # compute possible permutations\n ch_count = len(range(self.args.start, self.args.end + 1))\n if self.args.include_trst:\n if ch_count < 5:\n self.result.setstatus(\n passed=False,\n reason=\"Minimum 5 pins required for jtag scan.\"\n )\n return\n possible_permutations = int(\n factorial(ch_count) / factorial(ch_count - 5)\n )\n else:\n if ch_count < 4:\n self.result.setstatus(\n passed=False,\n reason=\"Minimum 4 pins required for jtag scan.\"\n )\n return\n possible_permutations = int(\n factorial(ch_count) / factorial(ch_count - 4)\n )\n\n if self.args.volts not in VOLTAGE_RANGE:\n self.result.setstatus(\n passed=False,\n reason=\"Unsupported target voltage.\"\n )\n return\n\n TLog.generic(\n \"Start Pin ({}), End Pin ({})\".format(\n self.args.start, self.args.end\n )\n )\n TLog.generic(\"Target Voltage ({})\".format(self.args.volts))\n\n if self.args.include_trst:\n TLog.generic(\"TRST pin included in scan\")\n else:\n TLog.generic(\"TRST pin excluded from scan\")\n\n TLog.generic(\n \"Possible permutations to be tested: ({})\".format(\n possible_permutations\n )\n )\n\n TLog.generic(\"\")\n\n auditor = None\n found = False\n\n try:\n auditor = BusAuditor()\n resp = auditor.jtag_scan(\n self.args.start,\n self.args.end,\n self.args.volts,\n self.args.include_trst\n )\n if resp:\n found = True\n TLog.success(\"JTAG Devices:\")\n for dev in resp:\n self.output_handler(**dev)\n\n except: # noqa: E722\n self.result.exception()\n\n finally:\n if auditor:\n auditor.close()\n\n if found is False:\n TLog.fail(\"Couldn't find jtag pins\")\n","repo_name":"expliot-framework/expliot","sub_path":"expliot/plugins/busauditor/bajtagscan.py","file_name":"bajtagscan.py","file_ext":"py","file_size_in_byte":7102,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"77"}
+{"seq_id":"15984482378","text":"import sys\nimport os\nimport socket\nimport re\nimport hmac\nimport datetime\nimport time\nimport base64\nimport hashlib\nimport string\nimport secrets\nimport methods\n\nSECRET = '928c9bbd3ea5298642cc3e82d3d122e2'\n\ndef main():\n if len(sys.argv) != 2:\n sys.exit(1) \n config_path = sys.argv[1]\n SERVER_PORT, CLIENT_PORT, INBOX_PATH = methods.read_config_file(config_path, True, False, 'inbox_path')\n try:\n sock = methods.setup_server_connection(SERVER_PORT)\n except:\n sys.exit(2)\n\n while True:\n sock.listen()\n conn, addr = sock.accept()\n emails = receive_from_client(conn)\n conn.close()\n for data in emails[0]:\n methods.save_email(data[0], data[1], data[2], data[3], data[4], INBOX_PATH)\n if emails[1]: \n break\n sock.close()\n sys.exit(0)\n\ndef send(conn, string, end=\"\\r\\n\"):\n conn.sendall((string + end).encode('ascii'))\n if '\\r\\n' in string:\n strings = string.split('\\r\\n')\n print(f'S: {strings[0]}\\r\\nS: {strings[1]}\\r', flush=True)\n else:\n print(f'S: {string}\\r', flush=True)\n\ndef receive(conn):\n try:\n data = conn.recv(1024).decode().strip('\\r\\n')\n if data == '':\n raise BrokenPipeError\n print(f'C: {data}\\r', flush=True)\n return data\n except:\n raise BrokenPipeError\n\ndef get_options(state):\n always_options = ['EHLO', 'RSET', 'NOOP', 'QUIT']\n state_and_options = {\n 1 : [],\n 3 : ['AUTH', 'MAIL'], # maybe only auth valid here?\n 5 : [], # valid authentication data\n 7 : [], # do this later, state 7 is what??\n 9 : ['RCPT'],\n 11 : ['RCPT', 'DATA'],\n 13 : ['.']\n }\n return state_and_options[state] + always_options\n\ndef receive_from_client(conn):\n emails = []\n send(conn, \"220 Service ready\")\n state = 1\n all_options = ['EHLO', 'RSET', 'NOOP', 'QUIT',\n 'MAIL', 'AUTH', 'DATA', 'RCPT']\n sender, receivers, date_line, subject, data_lines = methods.reset_values()\n try:\n while True:\n data = receive(conn)\n options = get_options(state)\n # if state == 3:\n # options.append('MAIL')\n if state == 5:\n state = 3\n if data == '*':\n send(conn, \"501 Syntax error in parameters or arguments\")\n continue\n decoded = base64.b64decode(data).split()\n if len(decoded) == 2:\n digest = decoded[1].decode()\n if digest == challenge_response:\n send(conn, \"235 Authentication successful\")\n state = 3\n continue\n send(conn, \"535 Authentication credentials invalid\")\n continue\n if state == 13:\n while data != '.':\n if data.startswith('Subject: '):\n subject = data\n elif data.startswith('Date: '):\n date_line = data\n else:\n data_lines.append(data)\n send(conn, \"354 Start mail input end .\")\n data = receive(conn)\n send(conn, '250 Requested mail action okay completed')\n emails.append((sender, receivers, date_line, subject, data_lines))\n sender, receivers, date_line, subject, data_lines = methods.reset_values()\n state = 3\n continue\n if len(data) < 4:\n send(conn, \"500 Syntax error, command unrecognized\")\n continue\n if data == 'SIGINT':\n send(conn, \"SIGINT received, closing\")\n return (emails, True)\n command = data[:4]\n if command not in all_options:\n send(conn, \"500 Syntax error, command unrecognized\")\n continue\n if command not in options:\n send(conn, \"503 Bad sequence of commands\")\n state = 3\n continue\n\n if command == 'EHLO':\n # checking syntax\n parts = data.split()\n if len(parts) != 2:\n send(conn, \"501 Syntax error in parameters or arguments\")\n continue\n numbers = parts[1].split('.')\n if len(numbers) != 4:\n send(conn, \"501 Syntax error in parameters or arguments\")\n continue\n valid_address = True\n for n in numbers:\n try:\n if int(n) > 255 or int(n) < 0:\n raise ValueError\n except:\n valid_address = False\n break\n if not valid_address:\n send(conn, \"501 Syntax error in parameters or arguments\")\n continue\n \n # syntax is good, send correct reply\n sender, receivers, date_line, subject, data_lines = methods.reset_values()\n send(conn, \"250 127.0.0.1\\r\\n250 AUTH CRAM-MD5\")\n state = 3\n \n elif command == 'MAIL':\n #check page 15, email ABNF syntax\n if not data.startswith('MAIL FROM:'):\n send(conn, \"501 Syntax error in parameters or arguments\")\n continue\n parts = data.split(':')\n if len(parts) > 2:\n send(conn, \"501 Syntax error in parameters or arguments\")\n continue\n if not methods.valid_email(parts[1]):\n send(conn, \"501 Syntax error in parameters or arguments\")\n continue\n sender = data[10:]\n send(conn, '250 Requested mail action okay completed')\n state = 9\n \n elif command == 'RCPT':\n if not data.startswith('RCPT TO:'):\n send(conn, \"501 Syntax error in parameters or arguments\")\n continue\n parts = data.split(':')\n if len(parts) > 2:\n send(conn, \"501 Syntax error in parameters or arguments\")\n continue\n if not methods.valid_email(parts[1]):\n send(conn, \"501 Syntax error in parameters or arguments\")\n continue\n receivers.append(data[8:])\n send(conn, '250 Requested mail action okay completed')\n state = 11\n \n elif command == 'DATA':\n if data != 'DATA':\n send(conn, \"501 Syntax error in parameters or arguments\")\n continue\n send(conn, \"354 Start mail input end .\")\n state = 13\n\n elif command == 'NOOP':\n if data != 'NOOP':\n send(conn, \"501 Syntax error in parameters or arguments\")\n continue\n send(conn, '250 Requested mail action okay completed')\n \n elif command == 'AUTH':\n if data != 'AUTH CRAM-MD5':\n send(conn, '504 Unrecognized authentication type')\n continue\n alphabet = string.ascii_letters + string.digits\n challenge = ''.join(secrets.choice(alphabet) for i in range(32))\n challenge = challenge.encode('ascii')\n send(conn, '334 ' + base64.b64encode(challenge).decode())\n challenge_response = hmac.new(SECRET.encode(), challenge, hashlib.md5).hexdigest()\n state = 5\n\n elif command == 'QUIT':\n if data != 'QUIT':\n send(conn, \"501 Syntax error in parameters or arguments\")\n continue\n send(conn, '221 Service closing transmission channel')\n return (emails, False)\n\n elif command == 'RSET':\n if data != 'RSET':\n send(conn, '501 Syntax error in parameters or arguments')\n continue\n sender, receivers, date_line, subject, data_lines= methods.reset_values()\n send(conn, '250 Requested mail action okay completed')\n state = 3\n except (ConnectionResetError, BrokenPipeError) as e:\n print('S: Connection lost\\r', flush=True)\n return (emails, False)\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"joshuahallam127/SMTP-protocol-Clone-w-MITM-Attacker","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":8654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"41762483310","text":"\"\"\"\nRead file into texts and calls.\nIt's ok if you don't understand how to read files.\n\"\"\"\nimport csv\n\nfrom telecom.cdr_parser import CdrParser\n\nwith open('texts.csv', 'r') as f:\n reader = csv.reader(f)\n texts = list(reader)\n\nwith open('calls.csv', 'r') as f:\n reader = csv.reader(f)\n calls = list(reader)\n\n\"\"\"\nTASK 4:\nThe telephone company want to identify numbers that might be doing\ntelephone marketing. Create a set of possible telemarketers:\nthese are numbers that make outgoing calls but never send texts,\nreceive texts or receive incoming calls.\n\nPrint a message:\n\"These numbers could be telemarketers: \"\n\nThe list of numbers should be print out one per line in lexicographic order with no duplicates.\n\"\"\"\n\nparser = CdrParser()\n\n\"\"\"\nCreate a set of possible telemarketers:\nthese are numbers that make outgoing calls\nbut never\n send texts,\n receive texts\n receive incoming calls\n\"\"\"\n#####################################################################################################################\n\nunique_a_call_numbers = {}\nunique_b_call_numbers = {}\nunique_a_text_numbers = {}\nunique_b_text_numbers = {}\n\nfor call in calls:\n cdr = parser.parse_record(call)\n\n unique_a_call_numbers[cdr.a_number] = \"record\"\n unique_b_call_numbers[cdr.b_number] = \"record\"\n\nfor text in texts:\n tdr = parser.parse_record(text)\n\n unique_a_text_numbers[tdr.a_number] = \"record\"\n unique_b_text_numbers[tdr.b_number] = \"record\"\n\nunique_a_call_numbers = list(unique_a_call_numbers.keys())\nunique_b_call_numbers = list(unique_b_call_numbers.keys())\nunique_a_text_numbers = list(unique_a_text_numbers.keys())\nunique_b_text_numbers = list(unique_b_text_numbers.keys())\n\nmarketing_candidates = []\n\nfor candidate in unique_a_call_numbers:\n\n candidate_flag = True\n\n for unique_b_call_number in unique_b_call_numbers:\n if candidate == unique_b_call_number:\n candidate_flag = False\n break\n\n for unique_a_text_number in unique_a_text_numbers:\n if candidate == unique_a_text_number:\n candidate_flag = False\n break\n\n for unique_b_text_number in unique_b_text_numbers:\n if candidate == unique_b_text_number:\n candidate_flag = False\n break\n\n if candidate_flag:\n marketing_candidates.append(candidate)\n\n\nprint(\"These numbers could be telemarketers: \")\n\nfor candidate in sorted(marketing_candidates):\n print(candidate)\n","repo_name":"miharothl/lab-data-structures-and-alghoritms","sub_path":"p1-intro/Task4.py","file_name":"Task4.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"40644398326","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nfrom scipy.optimize import minimize\nfrom scipy.io import loadmat\nfrom math import sqrt\nfrom sklearn.svm import SVC\nimport pickle\n\ndef preprocess():\n \"\"\" \n Input:\n Although this function doesn't have any input, you are required to load\n the MNIST data set from file 'mnist_all.mat'.\n\n Output:\n train_data: matrix of training set. Each row of train_data contains \n feature vector of a image\n train_label: vector of label corresponding to each image in the training\n set\n validation_data: matrix of training set. Each row of validation_data \n contains feature vector of a image\n validation_label: vector of label corresponding to each image in the \n training set\n test_data: matrix of training set. Each row of test_data contains \n feature vector of a image\n test_label: vector of label corresponding to each image in the testing\n set\n\n Some suggestions for preprocessing step:\n - divide the original data set to training, validation and testing set\n with corresponding labels\n - convert original data set from integer to double by using double()\n function\n - normalize the data to [0, 1]\n - feature selection\n \"\"\"\n \n mat = loadmat('mnist_all.mat'); #loads the MAT object as a Dictionary\n \n n_feature = mat.get(\"train1\").shape[1];\n n_sample = 0;\n for i in range(10):\n n_sample = n_sample + mat.get(\"train\"+str(i)).shape[0];\n n_validation = 1000;\n n_train = n_sample - 10*n_validation;\n \n # Construct validation data\n validation_data = np.zeros((10*n_validation,n_feature));\n for i in range(10):\n validation_data[i*n_validation:(i+1)*n_validation,:] = mat.get(\"train\"+str(i))[0:n_validation,:];\n \n # Construct validation label\n validation_label = np.ones((10*n_validation,1));\n for i in range(10):\n validation_label[i*n_validation:(i+1)*n_validation,:] = i*np.ones((n_validation,1));\n \n # Construct training data and label\n train_data = np.zeros((n_train,n_feature));\n train_label = np.zeros((n_train,1));\n temp = 0;\n for i in range(10):\n size_i = mat.get(\"train\"+str(i)).shape[0];\n train_data[temp:temp+size_i-n_validation,:] = mat.get(\"train\"+str(i))[n_validation:size_i,:];\n train_label[temp:temp+size_i-n_validation,:] = i*np.ones((size_i-n_validation,1));\n temp = temp+size_i-n_validation;\n \n # Construct test data and label\n n_test = 0;\n for i in range(10):\n n_test = n_test + mat.get(\"test\"+str(i)).shape[0];\n test_data = np.zeros((n_test,n_feature));\n test_label = np.zeros((n_test,1));\n temp = 0;\n for i in range(10):\n size_i = mat.get(\"test\"+str(i)).shape[0];\n test_data[temp:temp+size_i,:] = mat.get(\"test\"+str(i));\n test_label[temp:temp+size_i,:] = i*np.ones((size_i,1));\n temp = temp + size_i;\n \n # Delete features which don't provide any useful information for classifiers\n sigma = np.std(train_data, axis = 0);\n index = np.array([]);\n for i in range(n_feature):\n if(sigma[i] > 0.001):\n index = np.append(index, [i]);\n train_data = train_data[:,index.astype(int)];\n validation_data = validation_data[:,index.astype(int)];\n test_data = test_data[:,index.astype(int)];\n\n # Scale data to 0 and 1\n train_data = train_data/255.0;\n validation_data = validation_data/255.0;\n test_data = test_data/255.0;\n \n return train_data, train_label, validation_data, validation_label, test_data, test_label\n\ndef sigmoid(z):\n return 1.0/(1.0 + np.exp(-z));\n \ndef blrObjFunction(params, *args):\n \"\"\"\n blrObjFunction computes 2-class Logistic Regression error function and\n its gradient.\n\n Input:\n initialWeights: the weight vector of size (D + 1) x 1 \n train_data: the data matrix of size N x D\n labeli: the label vector of size N x 1 where each entry can be either 0 or 1\n representing the label of corresponding feature vector\n\n Output: \n error: the scalar value of error function of 2-class logistic regression\n error_grad: the vector of size (D+1) x 1 representing the gradient of\n error function\n \"\"\"\n train_data, labeli = args;\n n_feature = train_data.shape[1];\n Wt = params.reshape(n_feature+1,1);\n error_grad = np.zeros((n_feature+1,1))\n \n #add bias\n X_bias = np.column_stack((np.ones(train_data.shape[0]),train_data))\n X_fin = np.transpose(X_bias)\n W_t = np.transpose(Wt) \n P_C1 = sigmoid(np.dot(W_t,X_fin))\n yn = np.transpose(P_C1)\n oneminuslabeli = np.subtract(1,labeli)\n oneminusyn = np.subtract(1,yn)\n error = -1*np.sum(labeli*np.log(yn)+oneminuslabeli*np.log(oneminusyn))\n ynminuslabeli = np.subtract(yn,labeli)\n error_grad = np.dot(X_fin,ynminuslabeli)\n error_grad = error_grad.reshape(error_grad.shape[0])\n return error, error_grad\n\ndef blrPredict(W, data):\n \"\"\"\n blrObjFunction predicts the label of data given the data and parameter W \n of Logistic Regression\n \n Input:\n W: the matrix of weight of size (D + 1) x 10. Each column is the weight \n vector of a Logistic Regression classifier.\n X: the data matrix of size N x D\n \n Output: \n label: vector of size N x 1 representing the predicted label of \n corresponding feature vector given in data matrix\n\n \"\"\"\n #label = np.zeros((data.shape[0],1));\n x_bias = np.column_stack((np.ones(data.shape[0]),data))\n wt = np.transpose(W)\n x_fin = np.transpose(x_bias)\n label = np.argmax(np.dot(wt,x_fin),0)\n label = label.reshape(label.shape[0],1)\n return label\n\n\n\"\"\"\nScript for Logistic Regression\n\"\"\"\ntrain_data, train_label, validation_data,validation_label, test_data, test_label = preprocess();\n\n# number of classes\nn_class = 10;\n\n# number of training samples\nn_train = train_data.shape[0];\n\n# number of features\nn_feature = train_data.shape[1];\n\nT = np.zeros((n_train, n_class));\nfor i in range(n_class):\n T[:,i] = (train_label == i).astype(int).ravel();\n \n# Logistic Regression with Gradient Descent\nW = np.zeros((n_feature+1, n_class));\ninitialWeights = np.zeros((n_feature+1,1));\nopts = {'maxiter' : 50};\nfor i in range(n_class):\n labeli = T[:,i].reshape(n_train,1);\n args = (train_data, labeli);\n nn_params = minimize(blrObjFunction, initialWeights, jac=True, args=args,method='CG', options=opts)\n W[:,i] = nn_params.x.reshape((n_feature+1,));\n\n# Find the accuracy on Training Dataset\npredicted_label = blrPredict(W, train_data);\nprint('\\n Training set Accuracy:' + str(100*np.mean((predicted_label == train_label).astype(float))) + '%')\n\n# Find the accuracy on Validation Dataset\npredicted_label = blrPredict(W, validation_data);\nprint('\\n Validation set Accuracy:' + str(100*np.mean((predicted_label == validation_label).astype(float))) + '%')\n\n# Find the accuracy on Testing Dataset\npredicted_label = blrPredict(W, test_data);\nprint('\\n Testing set Accuracy:' + str(100*np.mean((predicted_label == test_label).astype(float))) + '%')\n\npickle.dump(W,open('params.pickle','wb'))\n\n\"\"\"\nScript for Support Vector Machine\n\"\"\"\n\nprint('\\n\\n--------------SVM-------------------\\n\\n')\n\ntrain_data, train_label, validation_data, validation_label, test_data, test_label = preprocess()\nacc1 = np.zeros(11)\nacc2 = np.zeros(11)\n\n# Using linear kernel (all other parameters are kept default).\nclf = SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3,\n gamma=0.0, kernel='linear', max_iter=-1, probability=False,\n random_state=None, shrinking=True, tol=0.001, verbose=False)\nclf.fit(train_data, train_label.ravel()) \n\nprint('\\n Using linear kernel (all other parameters are kept default)') \nprint('Validation set Accuracy: '+ str(clf.score(validation_data, validation_label.ravel())*100)+'%') \nprint('Testing set Accuracy: '+ str(clf.score(test_data, test_label.ravel())*100)+'%')\n\n\n#Using radial basis function with value of gamma setting to 1 (all other parameters are kept default).\nclf2 = SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3,\n gamma=1.0, kernel='rbf', max_iter=-1, probability=False,\n random_state=None, shrinking=True, tol=0.001, verbose=False)\nclf2.fit(train_data, train_label.ravel()) \n\nprint('\\n Using radial basis function with value of gamma setting to 1 (all other parameters are kept default)') \nprint('Validation set Accuracy: '+ str(clf2.score(validation_data, validation_label.ravel())*100)+'%') \nprint('Testing set Accuracy: '+ str(clf2.score(test_data, test_label.ravel())*100)+'%')\n\n# Using radial basis function with value of gamma setting to default (all other parameters are kept default).\nclf3 = SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3,\n gamma=0.0, kernel='rbf', max_iter=-1, probability=False,\n random_state=None, shrinking=True, tol=0.001, verbose=False)\nclf3.fit(train_data, train_label.ravel()) \n\nacc1[0] = clf3.score(validation_data, validation_label.ravel())*100\nacc2[0] = clf3.score(test_data, test_label.ravel())*100\nprint('\\n Using radial basis function with value of gamma setting to default (all other parameters are kept default)') \nprint('Validation set Accuracy: '+ str(acc1[0])+'%') \nprint('Testing set Accuracy: '+ str(acc2[0])+'%')\n\n\n#Using radial basis function with value of gamma setting to default and varying value of C (1, 10, 20, 30, · · · , 100)\ncount = 1\nfor i in range(10,101,10):\n clf = SVC(C=float(i), cache_size=200, class_weight=None, coef0=0.0, degree=3,\n gamma=0.0, kernel='rbf', max_iter=-1, probability=False,\n random_state=None, shrinking=True, tol=0.001, verbose=False)\n clf.fit(train_data, train_label.ravel()) \n\n acc1[count] = clf.score(validation_data, validation_label)*100\n acc2[count] = clf.score(test_data, test_label)*100\n count = count + 1\n\nprint('\\n Using radial basis function with value of gamma setting to default and varying value of C (1, 10, 20, 30, · · · , 100)') \nprint('Validation set Accuracy: '+ str(acc1)+'%') \nprint('Testing set Accuracy: '+ str(acc2)+'%')\n","repo_name":"SimplyRamya24/Logistic-Regression-and-Support-Vector-Machine","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":10174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"73629941369","text":"from uuid import uuid4\n\nfrom django.db import models\nfrom django.db.models.deletion import ProtectedError\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.text import capfirst, get_text_list\nfrom datetime import datetime, timedelta\n\nfrom aplicaciones.persona.models.tipo_hobby import TipoHobby\n\nclass Hobby(models.Model):\n id = models.UUIDField(primary_key=True, default=uuid4, editable=False)\n nombre = models.CharField(unique=True, max_length=30,\n blank=False, null=False)\n tipo_hobby = models.CharField(max_length=30,\n blank=False, null=False)\n\n\n class Meta:\n verbose_name = capfirst(_('Hobby'))\n db_table = 'persona_hobby'\n verbose_name_plural = capfirst(_('Hobby'))\n default_permissions = ()\n permissions = (\n ('add_hobby',\n 'Puede agregar Hobby'),\n ('change_hobby',\n 'Puede actualizar Hobby'),\n ('delete_hobby',\n 'Puede eliminar Hobby'),\n ('list_hobby',\n 'Puede listar Hobby'),\n ('get_hobby',\n 'Puede obtener Hobby'),\n ('listform_hobby', \n 'Puede listar Hobby en Formularios'),\n\n )\n\n \n def __str__(self):\n return self.nombre\n\n def delete(self, *args, **kwargs):\n try:\n super(Hobby, self).delete(*args, **kwargs)\n except ProtectedError as e:\n return self.nombre\n","repo_name":"davrv93/miproyecto","sub_path":"aplicaciones/persona/models/hobby.py","file_name":"hobby.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"14991853595","text":"# 983. Minimum Cost For Tickets\n# 🟠Medium\n#\n# https://leetcode.com/problems/minimum-cost-for-tickets/\n#\n# Tags: Array - Dynamic Programming\n\nimport timeit\nfrom typing import List\n\n\n# The brute force solution looks at each day in the days array and, for\n# each, it checks the result of either of the three options, buy a day,\n# week or month ticket.\n#\n# Time complexity: O(n^3) - There are n days and each day the decision\n# tree splits in 3.\n# Space complexity: O(n) - The call stack will reach a height of n.\n#\n# This solution probably fails with TLE.\nclass BruteForce:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n # A function that explores the recursive tree by splitting into\n # the three decisions that we can make.\n def dfs(idx: int, covered_until: int, current_cost: int) -> int:\n # Base case, we covered the entire year.\n if idx == len(days):\n return current_cost\n # If we are covered by the last tickets, skip this index.\n if covered_until >= days[idx]:\n return dfs(idx + 1, covered_until, current_cost)\n return min(\n dfs(idx + 1, days[idx], current_cost + costs[0]),\n dfs(idx + 1, days[idx] + 6, current_cost + costs[1]),\n dfs(idx + 1, days[idx] + 29, current_cost + costs[2]),\n )\n\n return dfs(0, 0, 0)\n\n\n# The minimal cost at any given day when we need to travel will be the\n# best between: the best 30 days past plus the cost of a 30 day ticket,\n# the best 7 days past plus the cost of a 7 day ticket or the best 1 day\n# past plus the cost of a 1 day ticket. If we don't need to travel, we\n# can maintain the same best cost as the day before.\n#\n# Time complexity: O(n) - Where n is the last day we need to travel,\n# days[-1] and it has an upper bound of 365, then O(n) ≈ O(1).\n# Space complexity: O(n) - The dp array goes from 0 to days[-1].\n#\n# Runtime 39 ms Beats 91.51%\n# Memory 13.8 MB Beats 83.75%\nclass DP:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n dp = [0] + [None] * days[-1]\n # The next index on the days array that we need to cover.\n idx = 0\n for i in range(1, len(dp)):\n # We need to travel today.\n if i == days[idx]:\n # Shift the index pointer.\n idx += 1\n dp[i] = min(\n dp[i - 1] + costs[0],\n costs[1] + (dp[i - 7] if i >= 7 else 0),\n costs[2] + (dp[i - 30] if i >= 30 else 0),\n )\n # No need to travel, maintain yesterday's cost.\n else:\n dp[i] = dp[i - 1]\n return dp[-1]\n\n\ndef test():\n executors = [\n BruteForce,\n DP,\n ]\n tests = [\n [[1, 4, 6, 7, 8, 20], [2, 7, 15], 11],\n [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [2, 7, 15], 17],\n ]\n for executor in executors:\n start = timeit.default_timer()\n for _ in range(1):\n for col, t in enumerate(tests):\n sol = executor()\n result = sol.mincostTickets(t[0], t[1])\n exp = t[2]\n assert result == exp, (\n f\"\\033[93m» {result} <> {exp}\\033[91m for\"\n + f\" test {col} using \\033[1m{executor.__name__}\"\n )\n stop = timeit.default_timer()\n used = str(round(stop - start, 5))\n cols = \"{0:20}{1:10}{2:10}\"\n res = cols.format(executor.__name__, used, \"seconds\")\n print(f\"\\033[92m» {res}\\033[0m\")\n\n\ntest()\n","repo_name":"raul-sauco/coding-challenges","sub_path":"leetcode/minimum-cost-for-tickets.py","file_name":"minimum-cost-for-tickets.py","file_ext":"py","file_size_in_byte":3623,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"29357109838","text":"import os\nfrom glob import glob\nimport shutil\n\nimport clip\nimport cv2\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.cuda import amp\nfrom torch.utils.data import DataLoader, Dataset\nfrom tqdm.auto import tqdm\n\nimport wandb\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\nwandb.init(project=\"clip_cls_36\", id=\"gdspqrrh\", resume='must')\nCONFIG = wandb.config\nprint(CONFIG)\n\ndatadir = \"data/rbg_newtest_filtered/\"\nnum_classes = 36\n\nclass ImageData(Dataset):\n def __init__(self, root_dir):\n self.im_paths = glob(os.path.join(root_dir, \"*\"))\n\n def __len__(self):\n return len(self.im_paths)\n\n def __getitem__(self, idx):\n im_path = self.im_paths[idx]\n img = cv2.imread(im_path, cv2.IMREAD_GRAYSCALE)\n img = cv2.resize(img, (224, 224))\n return img, im_path\n\n\ntrain_data = ImageData(datadir)\ndataloader = DataLoader(train_data, batch_size=512, pin_memory=True, drop_last=False, num_workers=8)\n\nnum_classes = 36\n# for i in range(num_classes):\n# os.makedirs(f\"data/newtest_finetune/{i}\", exist_ok=True)\n\ninput_nc = {\"RN50\": 1024, \"ViT-B/32\": 512}[CONFIG[\"clip_type\"]]\n\nclip_model, preprocess = clip.load(CONFIG[\"clip_type\"], device)\nclip_model.eval()\nmean = 255 * torch.tensor([0.485, 0.456, 0.406], dtype=torch.float16, device=device).reshape(1, 3, 1, 1)\nstd = 255 * torch.tensor([0.229, 0.224, 0.225], dtype=torch.float16, device=device).reshape(1, 3, 1, 1)\n\n\nclass QuickGELU(nn.Module):\n def forward(self, x: torch.Tensor):\n return x * torch.sigmoid(1.702 * x)\n\n\nget_activation = {\n 'q_gelu': QuickGELU,\n 'relu': nn.ReLU,\n 'elu': nn.ELU,\n 'leaky_relu': nn.LeakyReLU\n}\n\ncls_head = nn.Sequential(\n # nn.Dropout(CONFIG[\"dropout\"]),\n nn.Linear(input_nc, CONFIG[\"hid_dim\"]),\n get_activation[CONFIG[\"activation\"]](),\n nn.Dropout(CONFIG[\"dropout\"]),\n nn.Linear(CONFIG[\"hid_dim\"], num_classes)\n).to(device).eval()\n\n# cls_head.load_state_dict(torch.load(wandb.restore(\"best_weights_new.pth\").name))\nclass Classifier(nn.Module):\n def __init__(self):\n super().__init__()\n self.mean = 255 * torch.tensor([0.485, 0.456, 0.406], dtype=torch.float16, device=device).reshape(1, 3, 1, 1)\n self.std = 255 * torch.tensor([0.229, 0.224, 0.225], dtype=torch.float16, device=device).reshape(1, 3, 1, 1)\n self.clip_model, preprocess = clip.load(CONFIG[\"clip_type\"], device)\n self.clip_model = self.clip_model.float()\n self.cls_head = nn.Sequential(\n # nn.Dropout(CONFIG[\"dropout\"]),\n nn.LazyLinear(CONFIG[\"hid_dim\"]),\n get_activation[CONFIG[\"activation\"]](),\n nn.Dropout(CONFIG[\"dropout\"]),\n nn.Linear(CONFIG[\"hid_dim\"], num_classes)\n ).to(device).train()\n\n def forward(self, x):\n x = x.unsqueeze(1)\n x = x.repeat(1, 3, 1, 1)\n x = (x - self.mean).div_(self.std)\n x = self.clip_model.visual(x)\n x = self.cls_head(x)\n return x\ncls_head = Classifier()\ncls_head.load_state_dict(torch.load(\"weights/new2.pth\"))\n\nlabels = np.array([0,45,90,135,180,225,270,315])\n# for i in labels:\n# os.makedirs(f\"data/newtest_finetune/{i}\", exist_ok=True)\n# os.makedirs(\"data/newtest_finetune/reject\",exist_ok=True)\nlabeldict = {\n 0:0,\n 1:'reject',\n 2:45,\n 3:45,\n 4:45,\n 5:45,\n 6:'reject',\n 7:90,\n 8:90,\n 9:90,\n 10:'reject',\n 11:135,\n 12:135,\n 13:135,\n 14:135,\n 15:'reject',\n 16:180,\n 17:180,\n 18:180,\n 19:'reject',\n 20:225,\n 21:225,\n 22:225,\n 23:225,\n 24:'reject',\n 25:270,\n 26:270,\n 27:270,\n 28:'reject',\n 29:315,\n 30:315,\n 31:315,\n 32:315,\n 33:'reject',\n 34:0,\n 35:0\n}\ndef get_gt(path):\n labels = {\"1\":45,\"2\":90,\"3\":135,\"4\":180,\"5\":225,\"6\":270,\"7\":315,\"8\":0}\n lb = None\n if 'reshoot' in path:\n lb = path.split(\"_\")[-3]\n else:\n lb = path.split('.')[0][-1]\n if lb in labels.keys():\n return labels[lb]\n else:\n return None\n\ntotal = 0\ncorrect = 0\n\nwith torch.inference_mode(), amp.autocast():\n for images, paths in tqdm(dataloader):\n images = images.to(device, non_blocking=True)\n # images = images.unsqueeze(1)\n # images = images.repeat(1, 3, 1, 1)\n # images = (images - mean).div_(std)\n # features = clip_model.encode_image(images)\n x = cls_head(images)\n x = torch.softmax(x, dim=1)\n top_class = x.argmax(dim=1).cpu().numpy()\n for pred, pth in zip(top_class, paths):\n # print(labeldict[pred],lbl)\n # break\n # try:\n # lbl = labels[pth.split('.')[0][-1]]\n # if abs(lbl-labeldict[pred]) <= 15 or (345<=labeldict[pred]<360 and lbl==0):\n # correct+=1\n # total+=1\n # except Exception as e:\n # print(e)\n p = labeldict[pred]\n if p != 'reject':\n gt = get_gt(pth)\n if p == gt:\n correct+=1\n if gt is not None:\n total+=1\n else:\n total+=1\n # shutil.copy(pth, f\"data/newtest_finetune/{p}\")\n # break\nprint(correct)\nprint(total)\nprint(correct/total)","repo_name":"ShivamShrirao/clip_classifier","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":5248,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"6701216990","text":"import pygame,random,time\r\npygame.init()\r\nblack=(0,0,0)\r\nred=(255,0,0)\r\nwhite=(255,255,255)\r\nyellow=(255,255,0)\r\ngreen=(0,255,0)\r\nyellow=(255,255,0)\r\nblue=(0,0,255)\r\npurple=(255,0,255)\r\nlight_blue=(0,255,255)\r\ndh=512\r\ndw=512\r\npygame.init()\r\npygame.mixer.init()\r\ni=pygame.image.load(\"bicon.png\")\r\ni=pygame.transform.scale(i,[32,32])\r\nicon=pygame.display.set_icon(i)\r\nclass Player(pygame.sprite.Sprite):\r\n def __init__(self,x,y,game):\r\n super().__init__()\r\n self.image=pygame.image.load(\"bfront.png\")\r\n self.image=pygame.transform.scale(self.image,[32,32])\r\n self.i2=pygame.image.load(\"bright.png\")\r\n self.i2=pygame.transform.scale(self.i2,[32,32])\r\n self.i3=pygame.image.load(\"bback.png\")\r\n self.i3=pygame.transform.scale(self.i3,[32,32])\r\n self.i4=pygame.image.load(\"bright.png\")\r\n self.i4=pygame.transform.scale(self.i4,[32,32])\r\n self.i4=pygame.transform.flip(self.i4,1,0)\r\n self.i1=self.image\r\n self.rect=self.image.get_rect()\r\n self.game=game\r\n self.x=x\r\n self.y=y\r\n self.last=pygame.time.get_ticks()\r\n def move(self,dx=0,dy=0,img=None):\r\n if not self.collide(dx,dy) and self.collide1(dx,dy) and self.collide2(dx,dy):\r\n self.image=img\r\n self.x+=dx\r\n self.y+=dy\r\n def collide(self,dx=0,dy=0):\r\n for w in self.game.walls: \r\n if w.x==self.x+dx and w.y==self.y+dy:\r\n return True \r\n return False\r\n def collide1(self,dx=0,dy=0):\r\n for b in self.game.breakables: \r\n if b.x==self.x+dx and b.y==self.y+dy:\r\n return False \r\n return True\r\n def collide2(self,dx=0,dy=0):\r\n for m in self.game.mobs:\r\n if m.x==self.x+dx and m.y==self.y+dy:\r\n return False\r\n return True \r\n def bomber(self):\r\n now=pygame.time.get_ticks()\r\n if now-self.last>500:\r\n bomb=Bomb(self.rect.x,self.rect.y,self,self.game)\r\n self.game.all_sprites.add(bomb)\r\n self.game.bombs.add(bomb)\r\n def update(self):\r\n self.rect.x=self.x*32\r\n self.rect.y=self.y*32\r\n if self.rect.left<=0:\r\n self.rect.left=0\r\n if self.rect.right>=dw:\r\n self.rect.right=dw\r\n if self.rect.top<=0:\r\n self.rect.top=0\r\n if self.rect.bottom>=dh:\r\n self.rect.bottom=dh\r\nclass Wall(pygame.sprite.Sprite):\r\n def __init__(self,x,y):\r\n super().__init__()\r\n self.image=pygame.image.load(\"wall.png\")\r\n self.image=pygame.transform.scale(self.image,[32,32])\r\n self.rect=self.image.get_rect()\r\n self.x=x\r\n self.y=y\r\n self.rect.x=self.x*32\r\n self.rect.y=self.y*32\r\nclass Breakable(pygame.sprite.Sprite):\r\n def __init__(self,x,y):\r\n super().__init__()\r\n self.image=pygame.image.load(\"bwall.png\")\r\n self.image=pygame.transform.scale(self.image,[32,32])\r\n self.rect=self.image.get_rect()\r\n self.x=x\r\n self.y=y\r\n self.rect.x=self.x*32\r\n self.rect.y=self.y*32\r\nclass Fire(pygame.sprite.Sprite):\r\n def __init__(self,x,y,vx,vy,game):\r\n super().__init__()\r\n self.image=pygame.image.load(\"flame.png\")\r\n self.image=pygame.transform.scale(self.image,[32,32])\r\n self.rect=self.image.get_rect()\r\n self.rect.x=x\r\n self.rect.y=y\r\n self.game=game\r\n self.vx=vx\r\n self.vy=vy\r\n self.rect.x+=self.vx\r\n self.rect.y+=self.vy\r\n self.last=pygame.time.get_ticks()\r\n def update(self):\r\n hits=pygame.sprite.groupcollide(self.game.fires,self.game.breakables,1,1)\r\n now=pygame.time.get_ticks()\r\n if now-self.last>500:\r\n self.kill() \r\nclass Bomb(pygame.sprite.Sprite):\r\n def __init__(self,x,y,player,game):\r\n super().__init__()\r\n self.i1=pygame.image.load(\"bomb.png\")\r\n self.i1=pygame.transform.scale(self.i1,[32,32])\r\n self.image=self.i1\r\n self.rect=self.image.get_rect()\r\n self.last=pygame.time.get_ticks()\r\n self.rect.x=x\r\n self.rect.y=y\r\n self.player=player\r\n self.game=game\r\n def update(self):\r\n now=pygame.time.get_ticks()\r\n if now-self.last>500:\r\n self.last=now\r\n self.kill()\r\n fire1=Fire(self.rect.x,self.rect.y,30,0,self.game)\r\n self.game.all_sprites.add(fire1)\r\n self.game.fires.add(fire1)\r\n fire2=Fire(self.rect.x,self.rect.y,-30,0,self.game)\r\n self.game.all_sprites.add(fire2)\r\n self.game.fires.add(fire2)\r\n fire3=Fire(self.rect.x,self.rect.y,0,30,self.game)\r\n self.game.all_sprites.add(fire3)\r\n self.game.fires.add(fire3)\r\n fire4=Fire(self.rect.x,self.rect.y,0,-30,self.game)\r\n self.game.all_sprites.add(fire4)\r\n self.game.fires.add(fire4)\r\n fire5=Fire(self.rect.x,self.rect.y,0,0,self.game)\r\n self.game.all_sprites.add(fire5)\r\n self.game.fires.add(fire5) \r\nclass Level:\r\n def __init__(self,level):\r\n self.data=[]\r\n with open(level,'r+') as f:\r\n for line in f:\r\n self.data.append(line)\r\nclass Mob(pygame.sprite.Sprite):\r\n def __init__(self,x,y):\r\n super().__init__()\r\n self.image=pygame.image.load(\"mob.png\")\r\n self.image=pygame.transform.scale(self.image,[32,32])\r\n self.rect=self.image.get_rect()\r\n self.x=x\r\n self.y=y\r\n self.rect.x=self.x*32\r\n self.rect.y=self.y*32\r\nclass Game:\r\n def __init__(self):\r\n self.screen=pygame.display.set_mode([dw,dh])\r\n pygame.display.set_caption(\"Bomber Man\")\r\n self.clock=pygame.time.Clock()\r\n self.level=1\r\n self.map=Level(\"map2.txt\")\r\n self.hscore=open(\"highscore.txt\",'r')\r\n self.hi_score=int(self.hscore.read())\r\n self.score=0\r\n def new(self): \r\n self.all_sprites=pygame.sprite.Group()\r\n self.mobs=pygame.sprite.Group()\r\n self.bombs=pygame.sprite.Group()\r\n self.walls=pygame.sprite.Group()\r\n self.fires=pygame.sprite.Group()\r\n self.breakables=pygame.sprite.Group() \r\n if self.level==2:\r\n self.map=Level(\"map1.txt\")\r\n for col,tiles in enumerate(self.map.data):\r\n for row,tile in enumerate(tiles):\r\n if tile=='1':\r\n self.wall=Wall(row,col)\r\n self.all_sprites.add(self.wall)\r\n self.walls.add(self.wall)\r\n if tile=='2': \r\n self.bwall=Breakable(row,col)\r\n self.all_sprites.add(self.bwall)\r\n self.breakables.add(self.bwall)\r\n if tile=='p': \r\n self.player=Player(row,col,self)\r\n self.all_sprites.add(self.player)\r\n if tile=='e': \r\n self.mob=Mob(row,col)\r\n self.all_sprites.add(self.mob)\r\n self.mobs.add(self.mob)\r\n def run(self):\r\n self.play=True\r\n while self.play:\r\n self.events()\r\n self.update()\r\n self.draw()\r\n def events(self):\r\n self.clock.tick(60)\r\n for event in pygame.event.get():\r\n if event.type==pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n if event.type==pygame.KEYDOWN:\r\n if event.key==pygame.K_UP:\r\n self.player.move(0,-1,self.player.i3)\r\n elif event.key==pygame.K_DOWN:\r\n self.player.move(0,1,self.player.i1) \r\n elif event.key==pygame.K_RIGHT:\r\n self.player.move(1,0,self.player.i2) \r\n elif event.key==pygame.K_LEFT:\r\n self.player.move(-1,0,self.player.i4) \r\n elif event.key==pygame.K_SPACE:\r\n self.player.bomber()\r\n elif event.key==pygame.K_RETURN:\r\n self.pause() \r\n def update(self):\r\n self.all_sprites.update()\r\n hits=pygame.sprite.spritecollide(self.player,self.fires,False)\r\n if hits: \r\n self.gameover()\r\n self.new()\r\n hits1=pygame.sprite.groupcollide(self.breakables,self.fires,True,True)\r\n if hits1:\r\n self.score+=30\r\n hits2=pygame.sprite.groupcollide(self.mobs,self.fires,True,True)\r\n if hits2:\r\n self.score+=50\r\n if len(self.mobs)<=0 and len(self.breakables)<=0:\r\n self.level+=1\r\n self.new()\r\n if self.hi_scoreSearch\"\n\n @app.route('/search', defaults={'path': \"\"})\n @app.route('/search/', defaults={'path': \"\"})\n @app.route('/search/')\n def search(path):\n print(\"********************\", path)\n print(\"path:\", path)\n print(\"********************\", path)\n return app.send_static_file('search/index.html')\n\n #@app.route('/api/elasticsearch/podcasts_by_language/_search', methods=['GET', 'POST', 'OPTIONS'], defaults={\"es_index\": \"test\"})\n @app.route('/api/elasticsearch//_search', methods=['POST'])\n def elasticsearch_index(es_index):\n print(\"hit our es endpoint\", es_index)\n result = rest_requests.search(es_index, request)\n\n return result\n\n @app.route('/', defaults={'subpath': \"\"})\n @app.route('//')\n def page_data(path, subpath):\n \"\"\"\n For all non-react static files\n catch all to grab whatever else gatsby is throwing. Otherwise need `/page-data/...` `component...` and so on. but let's be liberal about this\n note that gatsby is not namespacing their calls to /search, so we don't here either\n \"\"\"\n full_path = os.path.join(path, subpath) if len(subpath) else path\n file_path = os.path.join(app.static_folder, full_path)\n print(\"###########################\")\n print(\"FULL\", full_path)\n print(\"FILE\", file_path)\n print(\"###########################\")\n return send_from_directory(app.static_folder, full_path)\n\n return app\n\n","repo_name":"RyanQuey/java-podcast-processor","sub_path":"flask_server/app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"77"}
+{"seq_id":"26376853529","text":"from turtle import *\n\ncolor = input(\"Name a color: \") # Ask the user for a color\nshape = input(\"Name a shape (Square, Triangle or Circle): \").lower() # Ask the user for a shape and convert the input to all lowercase calling .lower()\nmeasure = 'size' if ((shape == 'square') or (shape == 'triangle')) else 'radius' \n# one line if / else statement, which tells set the variable measure to size if the user input for shape was square or triangle, else set the variable to radius\n\t\nsize = int(input(\"Define the \" + measure + \" for your \" + shape + \": \" )) # ask the user for the size / radius for their shape then convert to integer (numbers)\n\nspeed(100) # set the speed of the turtle to 100\n\nif(color not in ['blue', 'Blue', 'BLUE']): \n color = 'red';\n #One of many ways to check if the set color is blue or NOT. Remember python is a case sensitive language so all different combinations have been included.\n #If color is not blue, make sure to set color to RED.\n\npencolor(color) # Set the color of the drawing\n# The function accepts string literals such as \"red\", \"yellow\", \"blue\" but also RGB values.\n\nfillcolor(color) # this function is to set the colour that we will fill the shape with. Again we have picked the same user given input\n\nbegin_fill()\t# A function that tells python what to fill in\n\nif shape == 'square': # if user entered square do this\n\tforward(size)\n\tright(90)\n\tforward(size)\n\tright(90)\n\tforward(size)\n\tright(90)\n\tforward(size)\nelif shape == 'triangle': # if user entered triangle then do this\n\tforward(size)\n\tleft(120)\n\tforward(size)\n\tleft(120)\n\tforward(size)\nelif shape == 'circle': # if user entered circle then do this\n\tcircle(size)\nelse: \n\tprint(\"I am sorry but I don't know how to draw a \" + shape + \".\")\n\nend_fill()\t# Once we have finished drawing the shape we tell python to end the fill, such that we dont fill any other drawings after this line \nhideturtle()\n\ndone()\n","repo_name":"miratepuffin/Python-tutorial-for-welcome-week","sub_path":"Ex2-3.py","file_name":"Ex2-3.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"43040343664","text":"from cnn import Cnn\nfrom audio_generator import AudioGenerator\nimport sys\nimport os\n\n\ndef test(metadata_file, dataset_dir, model_file):\n generator = AudioGenerator(metadata_path=metadata_file,\n dataset_path=dataset_dir,\n batch_size=1)\n vggvox_net = Cnn(model_file)\n metrics = vggvox_net.evaluate_generator(test_generator=generator.test(),\n test_steps=generator.get_test_steps())\n print(f\"Loss {metrics[0]}, Top 1 Accuracy {metrics[1]}, Top 5 Accuracy {metrics[2]}\")\n\n\nif __name__ == \"__main__\":\n argc = len(sys.argv)\n if argc != 4:\n print(\"Usage: python vggvox_test.py metadata_path.csv dataset_dir model_path.hdf5\")\n exit(1)\n else:\n if not os.path.exists(sys.argv[1]):\n raise IOError(\"Metadata csv file does not exist\")\n if not os.path.exists(sys.argv[2]):\n raise IOError(\"Dataset directory does not exist\")\n if not os.path.exists(sys.argv[3]):\n raise IOError(\"Model weight file does not exist\")\n test(*sys.argv[1:])\n","repo_name":"KornelZ/vggvox_identification","sub_path":"vggvox_test.py","file_name":"vggvox_test.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"29496357763","text":"import tensorflow as tf\nfrom .. import LOGGER\n\n\nclass GraphSelector:\n def __init__(self, config, embedding):\n self.config = config\n self.embedding = embedding\n\n def _input_layer(self, input, embedding_initializer):\n input_layer = tf.contrib.layers.embed_sequence(\n input['input'],\n self.embedding.vocab_size,\n self.embedding.vector_size,\n initializer=embedding_initializer,\n trainable=False\n )\n return input_layer\n\n def add_graph(self, input, training_mode, embedding_initializer):\n if self.config['model_type'] == 'tf_cnn_simple':\n LOGGER.info(\"create model: cnn_simple\")\n return self._cnn_simple(input, training_mode,\n embedding_initializer)\n elif self.config['model_type'] == 'tf_cnn_multi':\n LOGGER.info(\"create model: cnn_multi\")\n return self._cnn_multi_layer(input, training_mode,\n embedding_initializer)\n elif self.config['model_type'] == 'tf_lstm_simple':\n LOGGER.info(\"create model: lstm_simple\")\n return self._lstm_simple(input, training_mode,\n embedding_initializer)\n elif self.config['model_type'] == 'tf_lstm_multi':\n LOGGER.info(\"create model: lstm_multi\")\n return self._lstm_multi_layer(input, training_mode,\n embedding_initializer)\n\n def _cnn_simple(self, input, training_mode, embedding_initializer):\n input_layer = self._input_layer(input, embedding_initializer)\n dropout_emb = tf.layers.dropout(inputs=input_layer,\n rate=self.config['dropout_rate'],\n training=training_mode)\n\n conv = tf.layers.conv1d(\n inputs=dropout_emb,\n filters=self.config['cnn']['filter_size'],\n kernel_size=self.config['cnn']['kernel_size'],\n padding='same',\n activation=tf.nn.relu)\n\n pool = tf.reduce_max(input_tensor=conv, axis=1)\n hidden = tf.layers.dense(inputs=pool, units=256, activation=tf.nn.relu)\n dropout_hidden = tf.layers.dropout(inputs=hidden,\n rate=self.config['dropout_rate'],\n training=training_mode)\n logits = tf.layers.dense(inputs=dropout_hidden, units=2)\n return logits\n\n def _cnn_multi_layer(self, input, training_mode, embedding_initializer):\n input_layer = self._input_layer(input, embedding_initializer)\n\n next_input = tf.layers.dropout(inputs=input_layer,\n rate=self.config['dropout_rate'],\n training=training_mode)\n\n for i in range(self.config['cnn']['nr_layers']):\n conv = tf.layers.conv1d(\n inputs=next_input,\n filters=self.config['cnn']['filter_size'],\n kernel_size=self.config['cnn']['kernel_size'],\n padding='same',\n activation=tf.nn.relu)\n\n next_input = tf.layers.max_pooling1d(\n inputs=conv,\n pool_size=2,\n strides=2,\n padding='same')\n\n flat = tf.contrib.layers.flatten(next_input)\n dropout_flat = tf.layers.dropout(inputs=flat,\n rate=self.config['dropout_rate'],\n training=training_mode)\n\n logits = tf.layers.dense(inputs=dropout_flat, units=2)\n return logits\n\n def _lstm_simple(self, input, training_mode, embedding_initializer):\n input_layer = self._input_layer(input, embedding_initializer)\n cell = tf.nn.rnn_cell.LSTMCell(self.config['lstm']['hidden_size'])\n cell = tf.nn.rnn_cell.DropoutWrapper(\n cell,\n # input_keep_prob=self.config['dropout_keep_rate'],\n output_keep_prob=self.config['dropout_keep_rate'],\n state_keep_prob=self.config['dropout_keep_rate'],\n variational_recurrent=True,\n input_size=input_layer.get_shape()[-1],\n dtype=tf.float32\n )\n _, final_state = tf.compat.v1.nn.dynamic_rnn(\n cell, input_layer, sequence_length=input['len'], dtype=tf.float32)\n\n outputs = final_state.h\n logits = tf.layers.dense(inputs=outputs, units=2)\n return logits\n\n def _lstm_multi_layer(self, input, training_mode, embedding_initializer):\n input_layer = self._input_layer(input, embedding_initializer)\n cell = tf.nn.rnn_cell.LSTMCell(self.config['lstm']['hidden_size'])\n cell = tf.nn.rnn_cell.DropoutWrapper(\n cell,\n # input_keep_prob=self.config['dropout_keep_rate'],\n output_keep_prob=self.config['dropout_keep_rate'],\n state_keep_prob=self.config['dropout_keep_rate'],\n variational_recurrent=True,\n # note that if the lstm hidden state is different with then\n # input embedding size\n # the input_size need to be adjusted\n input_size=input_layer.get_shape()[-1],\n dtype=tf.float32)\n multi_rnn_cell = tf.contrib.rnn.MultiRNNCell(\n [cell] * self.config['lstm']['nr_layers'])\n outputs, final_state = tf.compat.v1.nn.dynamic_rnn(\n cell=multi_rnn_cell,\n inputs=input_layer,\n sequence_length=input['len'],\n dtype=tf.float32\n )\n\n # final_outputs = tf.transpose(outputs, [1,0,2])[-1]\n final_outputs = final_state[-1].h\n logits = tf.layers.dense(inputs=final_outputs, units=2)\n return logits\n","repo_name":"tilaboy/tk-nn-classifier","sub_path":"tk_nn_classifier/classifiers/graph_selector.py","file_name":"graph_selector.py","file_ext":"py","file_size_in_byte":5871,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"20332366974","text":"import pika\n\nurl = \"amqps://rwgvqgbl:viLu0chz5vJSpcto-ePPogpzl_xtrRqr@test-tall-gold-lark.rmq3.cloudamqp.com/rwgvqgbl\"\nparams = pika.URLParameters(url)\nconnection = pika.BlockingConnection(params)\nchannel = connection.channel() # start a channel\n\nmain_queue = 'main_q'\nmain_exchange = 'main_x'\n\ndl_queue = 'dlq'\ndl_exchange = 'dlx'\n\nchannel.exchange_declare(main_exchange, 'direct')\nchannel.queue_declare(\n queue=main_queue, \n durable=True, \n exclusive=False, \n auto_delete=False, \n arguments={\n 'x-dead-letter-exchange': dl_exchange\n }\n)\nchannel.queue_bind(\n main_queue, main_exchange, 'main_q'\n)\n\nchannel.exchange_declare(dl_exchange, 'topic')\nchannel.queue_declare(\n queue=dl_queue, \n durable=True, \n exclusive=False, \n auto_delete=False, \n arguments={\n 'x-queue-type':'quorum',\n 'x-message-ttl':30000, \n 'x-dead-letter-exchange':main_exchange,\n 'x-dead-letter-routing-key':'main_q'\n }\n)\nchannel.queue_bind(dl_queue, dl_exchange, \"#\") \n\n# Publish to main queue\nmsg = 'Hello CloudAMQP!'\nchannel.basic_publish(\n exchange=main_exchange,\n routing_key='main_q',\n body=msg\n)\n\nprint(f\"[📥] Message sent to queue: #{msg}\")\nconnection.close()","repo_name":"cloudamqp/lavinmq-tutorials","sub_path":"misc/rabbit.py","file_name":"rabbit.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"71873337530","text":"#!/usr/bin/python\n\nfrom pprint import pprint\nimport datetime\nimport socket\nimport threading\nimport time\n\ndef probeHostList(hosts):\n\n while True:\n changes = []\n threads = []\n for host in hosts:\n t = threading.Thread(target=parseHost, args=(host,))\n threads.append(t)\n for thread in threads:\n thread.start()\n for thread in threads:\n thread.join()\n if len(changes) > 0:\n sendMessage()\n del changes[:]\n del threads[:]\n\n # it's all over\n pprint(hostlist)\n break\n\ndef printD(string, indent):\n strindent = \"\"\n for x in range(0, indent):\n strindent = strindent + \" \"\n print(\n \"[\" + datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\") + \"]\" + strindent + \" \" + string\n )\n\n\ndef tcpCheck(ip, port):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(timeout)\n try:\n s.connect((ip, int(port)))\n s.shutdown(socket.SHUT_RDWR)\n return True\n except:\n return False\n finally:\n s.close()\n\n\ndef checkHost(host):\n\n ipup = False\n for i in range(retry):\n if tcpCheck(host[\"ip\"], host[\"port\"]):\n ipup = True\n break\n else:\n printD(\n \"No response from \"\n + host[\"ip\"]\n + \":\"\n + str(host[\"port\"])\n + \":\"\n + host[\"conntype\"]\n + \", retrying in \"\n + str(delay)\n + \"s...\",\n 0,\n )\n time.sleep(delay)\n return ipup\n\n\ndef parseHost(host):\n\n prestatus = host[\"status\"]\n printD(\"Checking \" + host[\"ip\"] + \":\" + str(host[\"port\"]) + \":\" + host[\"conntype\"] + \"...\", 0)\n if checkHost(host):\n host[\"status\"] = \"up\"\n if prestatus == \"down\":\n changes.append(\n host[\"ip\"]\n + \":\"\n + str(host[\"port\"])\n + \":\"\n + host[\"conntype\"]\n + \" is \"\n + host[\"status\"]\n )\n else:\n host[\"status\"] = \"down\"\n if prestatus == \"up\":\n changes.append(\n host[\"ip\"]\n + \":\"\n + str(host[\"port\"])\n + \":\"\n + host[\"conntype\"]\n + \" is \"\n + host[\"status\"]\n )\n printD(\n \"Status of \"\n + host[\"ip\"]\n + \":\"\n + str(host[\"port\"])\n + \":\"\n + host[\"conntype\"]\n + \": \"\n + host[\"status\"],\n 0,\n )\n\n\nretry = 1\ndelay = 2\ntimeout = 3 # Socket initialization timeout, used in tcpCheck()\ninterval = 3 # Will wait this long before retrying checks\n\nhosts = []\nhostlist = [\"172.30.30.5\", \"172.30.30.30\"]\nhostlist = [\"172.30.30.5\", \"172.30.30.9\", \"172.30.30.30\"]\nport = 22\n\nfor ip in hostlist:\n conntype = \"tcp\"\n hosts.append({\"ip\": ip, \"port\": port, \"conntype\": \"tcp\", \"status\": \"unknown\"})\n\npprint(hosts)\nprobeHostList(hosts)\n","repo_name":"DamienOConnell/probe_hostfile_entries","sub_path":"tcp_probe_host_list.py","file_name":"tcp_probe_host_list.py","file_ext":"py","file_size_in_byte":3065,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"6946001608","text":"# Program to sum digits of a number for a number string.\n\ndef main():\n numbers = input(\"Enter number: \")\n\n total = 0\n\n try:\n for digit in numbers:\n total += int(digit)\n \n print(total)\n except:\n print('Invalid Inputs.')\n\nmain()","repo_name":"sairamprogramming/python_book1","sub_path":"chapter8/programming_exercises/exercise2.py","file_name":"exercise2.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"18525730806","text":"import unittest\nimport sys\nimport numpy as np\nimport time\n\nsys.path.append(\"../..\")\nfrom hsds.util.storUtil import _shuffle, _unshuffle, BIT_SHUFFLE, BYTE_SHUFFLE\n\n\nclass ShuffleUtilTest(unittest.TestCase):\n def __init__(self, *args, **kwargs):\n super(ShuffleUtilTest, self).__init__(*args, **kwargs)\n # main\n\n def testByteShuffle(self):\n arr = np.zeros((3,), dtype=\"= rmin and bucket <= rmax)\n ]\n buckets = {bucket: 0 for bucket in rbuckets}\n for pmin, pmax in pay_data:\n for bucket in rbuckets:\n if bucket >= pmin and bucket <= pmax:\n buckets[bucket] += 1\n data = sorted(buckets.items())\n if len(data) in (0, 1):\n return\n\n xlen = len(data)\n xpoints = 5\n xaxis = (\n [data[0][0]]\n + [data[c * xlen // xpoints][0] for c in range(1, xpoints)]\n + [data[-1][0]]\n )\n\n # pruned_data = [data[0]] + [\n # data[c] for c in range(1, len(data)) if not (data[c][1] == data[c - 1][1] and data[c][1] == data[c + 1][1])\n # ] + [data[-1]]\n return {'currency': currency, 'data': data, 'xaxis': xaxis}\n\n\n@rq.job('hasjob')\ndef save_jobview(event_session_id, jobpost_id, bgroup, viewed_time):\n \"\"\"\n Save a jobpost view as a background job to ensure this doesn't fire *before* the\n associated save_impressions job. Queue order is important for the cointoss flag\n in A/B testing.\n \"\"\"\n jvs = JobViewSession.get_by_ids(\n event_session_id=event_session_id, jobpost_id=jobpost_id\n )\n if jvs is None:\n jvs = JobViewSession(\n event_session_id=event_session_id,\n jobpost_id=jobpost_id,\n datetime=viewed_time,\n bgroup=bgroup,\n )\n jvs = failsafe_add(\n db.session, jvs, event_session_id=event_session_id, jobpost_id=jobpost_id\n )\n\n # Since this is a new view, is there an existing job impression in the same session\n # which has a bgroup defined? If yes, this view has an associated coin toss.\n ji = JobImpression.get_by_ids(\n jobpost_id=jobpost_id, event_session_id=event_session_id\n )\n if ji:\n jvs.cointoss = True\n if ji.bgroup != jvs.bgroup and jvs.bgroup is not None:\n jvs.crosstoss = True\n else:\n jvs.cointoss = False\n\n db.session.commit()\n\n\ndef mark_dirty_impression_counts(jobpost_ids):\n if jobpost_ids:\n redis_store.sadd('hasjob/dirty_impression_counts', *jobpost_ids)\n\n\ndef remove_dirty_impression_counts(jobpost_ids):\n if jobpost_ids:\n redis_store.srem('hasjob/dirty_impression_counts', *jobpost_ids)\n\n\ndef list_dirty_impression_counts():\n return [int(x) for x in redis_store.smembers('hasjob/dirty_impression_counts')]\n\n\ndef update_impression_counts(jobpost_ids):\n for jobpost_id in jobpost_ids:\n redis_store.hset(\n JobPost.viewcounts_key(jobpost_id),\n 'impressions',\n get_jobpost_impressions(jobpost_id),\n )\n\n\ndef update_dirty_impression_counts():\n jobpost_ids = list_dirty_impression_counts()\n update_impression_counts(jobpost_ids)\n remove_dirty_impression_counts(jobpost_ids)\n\n\n@rq.job('hasjob')\ndef save_impressions(session_id, impressions, viewed_time):\n \"\"\"\n Save impressions against each job and session.\n \"\"\"\n with app.test_request_context():\n for pinned, postid, bgroup in impressions:\n ji = JobImpression.get_by_ids(\n jobpost_id=postid, event_session_id=session_id\n )\n if ji is None:\n ji = JobImpression(\n jobpost_id=postid,\n event_session_id=session_id,\n datetime=viewed_time,\n pinned=False,\n bgroup=bgroup,\n )\n db.session.add(ji)\n # Never set pinned=False on an existing JobImpression instance. The pinned status\n # could change during a session. We are only interested in knowing if it was\n # rendered as pinned at least once during a session.\n if pinned:\n ji.pinned = True\n if bgroup is not None:\n ji.bgroup = bgroup\n # We commit once per impression (typically 32+ impressions per request)\n # This is inefficient, but is the only way to handle integrity errors per item\n # from race conditions in the absence of a database-provided UPSERT. This\n # is why this function runs as a background job instead of in-process.\n try:\n db.session.commit()\n except IntegrityError: # Parallel request, skip this and move on\n db.session.rollback()\n mark_dirty_impression_counts([postid for pinned, postid, bgroup in impressions])\n\n\n@rq.job('hasjob')\ndef campaign_view_count_update(campaign_id, user_id=None, anon_user_id=None):\n if not user_id and not anon_user_id:\n return\n if user_id:\n cv = CampaignView.get_by_ids(campaign_id=campaign_id, user_id=user_id)\n if not cv:\n # Could be missing because of begin_nested introduced in 36070d9e without outer commit\n cv = CampaignView(campaign_id=campaign_id, user_id=user_id)\n db.session.add(cv)\n elif anon_user_id:\n cv = CampaignAnonView.get_by_ids(\n campaign_id=campaign_id, anon_user_id=anon_user_id\n )\n if not cv:\n # Could be missing because of begin_nested introduced in 36070d9e without outer commit\n cv = CampaignAnonView(campaign_id=campaign_id, anon_user_id=anon_user_id)\n db.session.add(cv)\n query = (\n db.session.query(sa.func.count(campaign_event_session_table.c.event_session_id))\n .filter(campaign_event_session_table.c.campaign_id == campaign_id)\n .join(EventSession)\n .filter(EventSession.active_at >= (cv.reset_at or utcnow()))\n )\n\n # FIXME: Run this in a cron job and de-link from post-request processing\n # query = query.filter(\n # sa.or_(\n # # Is this event session closed? Criteria: it's been half an hour or the\n # # session's explicitly closed\n # EventSession.ended_at.isnot(None),\n # EventSession.active_at < utcnow() - timedelta(minutes=30)))\n\n if user_id:\n query = query.filter(EventSession.user_id == user_id)\n else:\n query = query.filter(EventSession.anon_user_id == anon_user_id)\n\n cv.session_count = query.first()[0]\n cv.last_viewed_at = sa.func.utcnow()\n db.session.commit()\n\n\ndef reset_campaign_views(): # Periodic job\n live_campaigns = Campaign.query.filter(Campaign.state.LIVE).options(\n sa.orm.load_only(Campaign.id)\n )\n\n CampaignView.query.filter(\n CampaignView.campaign_id.in_(live_campaigns),\n CampaignView.last_viewed_at < utcnow() - timedelta(days=30),\n ).update(\n {'dismissed': False, 'session_count': 0, 'reset_at': sa.func.utcnow()},\n synchronize_session=False,\n )\n\n CampaignAnonView.query.filter(\n CampaignAnonView.campaign_id.in_(live_campaigns),\n CampaignAnonView.last_viewed_at < utcnow() - timedelta(days=30),\n ).update(\n {'dismissed': False, 'session_count': 0, 'reset_at': sa.func.utcnow()},\n synchronize_session=False,\n )\n\n db.session.commit()\n\n\ndef jobpost_location_hierarchy(self):\n locations = []\n for loc in self.geonameids:\n # Call one at a time for better cache performance\n locations.append(location_geodata(loc))\n parts = {\n 'city': set(),\n 'area': set(),\n 'state': set(),\n 'country': set(),\n 'continent': set(),\n }\n for row in locations:\n if row and 'fcode' in row:\n if row['fcode'] in ('PPL', 'PPLA'):\n parts['city'].add(row['use_title'])\n elif row['fcode'] == 'ADM2':\n parts['area'].add(row['use_title'])\n elif row['fcode'] == 'ADM1':\n parts['state'].add(row['use_title'])\n elif row['fcode'] == 'CONT':\n parts['continent'].add(row['use_title'])\n if 'country' in row and row['country']:\n parts['country'].add(row['country']) # Use 2 letter ISO code, not name\n\n return {k: tuple(parts[k]) for k in parts}\n\n\nJobPost.location_hierarchy = property(jobpost_location_hierarchy)\n\n\n@app.template_filter('urlquote')\ndef urlquote(data):\n return quote(data)\n\n\n@app.template_filter('urlquoteplus')\ndef urlquoteplus(data):\n return quote_plus(data)\n\n\n@app.template_filter('scrubemail')\ndef scrubemail_filter(data, css_junk=''):\n return Markup(\n scrubemail(\n str(bleach.linkify(bleach.clean(data))), rot13=True, css_junk=css_junk\n )\n )\n\n\n@app.template_filter('hideemail')\ndef hideemail_filter(data, message='[redacted]'):\n return redactemail(data, message)\n\n\n@app.template_filter('usessl')\ndef usessl(url):\n \"\"\"\n Convert a URL to https:// if SSL is enabled in site config\n \"\"\"\n if not app.config.get('USE_SSL'):\n return url\n if url.startswith('//'): # //www.example.com/path\n return 'https:' + url\n if url.startswith('/'): # /path\n url = path.join(request.url_root, url[1:])\n if url.startswith('http:'): # http://www.example.com\n url = 'https:' + url[5:]\n return url\n\n\ndef filter_basequery(basequery, filters, exclude_list=()):\n \"\"\"\n - Accepts a query of type sqlalchemy.Query, and returns a modified query\n based on the keys in the `filters` object.\n - The keys accepted in the `filters` object are: `locations`, `anywhere`, `categories`, `types,\n `pay_min`, `pay_max`, `currency`, `equity` and `query`.\n - exclude_list is an array of keys that need to be ignored in the `filters` object\n \"\"\"\n filter_by_location = filters.get('locations') and 'locations' not in exclude_list\n filter_by_anywhere = filters.get('anywhere') and 'anywhere' not in exclude_list\n if filter_by_location:\n job_location_jobpost_ids = db.session.query(JobLocation.jobpost_id).filter(\n JobLocation.geonameid.in_(filters['locations'])\n )\n\n if filter_by_location and filter_by_anywhere:\n basequery = basequery.filter(\n sa.or_(\n JobPost.id.in_(job_location_jobpost_ids),\n JobPost.remote_location.is_(True),\n )\n )\n elif filter_by_location:\n basequery = basequery.filter(JobPost.id.in_(job_location_jobpost_ids))\n elif filter_by_anywhere:\n basequery = basequery.filter(JobPost.remote_location.is_(True))\n\n if filters.get('categories') and 'categories' not in exclude_list:\n job_categoryids_query = db.session.query(JobCategory.id).filter(\n JobCategory.name.in_(filters['categories'])\n )\n basequery = basequery.filter(JobPost.category_id.in_(job_categoryids_query))\n if filters.get('types') and 'types' not in exclude_list:\n job_typeids_query = db.session.query(JobType.id).filter(\n JobType.name.in_(filters['types'])\n )\n basequery = basequery.filter(JobPost.type_id.in_(job_typeids_query))\n if (\n filters.get('pay_min')\n and filters.get('pay_max')\n and 'pay_min' not in exclude_list\n ):\n basequery = basequery.filter(\n JobPost.pay_cash_min < filters['pay_max'],\n JobPost.pay_cash_max >= filters['pay_min'],\n )\n if filters.get('currency'):\n basequery = basequery.filter(JobPost.pay_currency == filters.get('currency'))\n if filters.get('equity') and 'equity' not in exclude_list:\n basequery = basequery.filter(JobPost.pay_equity_min.isnot(None))\n if filters.get('search_tsquery') and 'search_tsquery' not in exclude_list:\n basequery = basequery.filter(\n JobPost.search_vector.bool_op('@@')(\n sa.func.to_tsquery(filters['search_tsquery'])\n )\n )\n\n return basequery\n\n\ndef filter_locations(board, filters):\n basequery = (\n db.session.query(\n JobLocation.geonameid, sa.func.count(JobLocation.geonameid).label('count')\n )\n .join(JobPost)\n .filter(JobPost.state.LISTED, JobLocation.primary.is_(True))\n .group_by(JobLocation.geonameid)\n .order_by(sa.text('count DESC'))\n )\n if board:\n basequery = basequery.join(BoardJobPost).filter(BoardJobPost.board == board)\n\n geonameids = [jobpost_location.geonameid for jobpost_location in basequery]\n filtered_basequery = filter_basequery(\n basequery, filters, exclude_list=['locations', 'anywhere']\n )\n filtered_geonameids = [\n jobpost_location.geonameid for jobpost_location in filtered_basequery\n ]\n remote_location_available = (\n filtered_basequery.filter(JobPost.remote_location.is_(True)).count() > 0\n )\n data = location_geodata(geonameids)\n return [\n {\n 'name': 'anywhere',\n 'title': _(\"Anywhere\"),\n 'available': remote_location_available,\n }\n ] + [\n {\n 'name': data.get(geonameid, {}).get('name', ''),\n 'title': data.get(geonameid, {}).get('picker_title', ''),\n 'available': False\n if not filtered_geonameids\n else geonameid in filtered_geonameids,\n }\n for geonameid in geonameids\n ]\n\n\ndef filter_types(basequery, board, filters):\n basequery = filter_basequery(basequery, filters, exclude_list=['types'])\n filtered_typeids = [\n post.type_id\n for post in basequery.options(sa.orm.load_only(JobPost.type_id))\n .distinct(JobPost.type_id)\n .all()\n ]\n\n def format_job_type(job_type):\n return {\n 'name': job_type.name,\n 'title': job_type.title,\n 'available': False\n if not filtered_typeids\n else job_type.id in filtered_typeids,\n }\n\n if board:\n return [\n format_job_type(job_type)\n for job_type in board.types\n if not job_type.private\n ]\n else:\n return [\n format_job_type(job_type)\n for job_type in JobType.query.filter_by(\n private=False, public=True\n ).order_by(JobType.seq)\n ]\n\n\ndef filter_categories(basequery, board, filters):\n basequery = filter_basequery(basequery, filters, exclude_list=['categories'])\n filtered_categoryids = [\n post.category_id\n for post in basequery.options(sa.orm.load_only(JobPost.category_id))\n .distinct(JobPost.category_id)\n .all()\n ]\n\n def format_job_category(job_category):\n return {\n 'name': job_category.name,\n 'title': job_category.title,\n 'available': False\n if not filtered_categoryids\n else job_category.id in filtered_categoryids,\n }\n\n if board:\n return [\n format_job_category(job_category)\n for job_category in board.categories\n if not job_category.private\n ]\n else:\n return [\n format_job_category(job_category)\n for job_category in JobCategory.query.filter_by(\n private=False, public=True\n ).order_by(JobCategory.seq)\n ]\n\n\n@app.context_processor\ndef inject_filter_options():\n def get_job_filters():\n filters = g.get('event_data', {}).get('filters', {})\n cache_key = (\n 'jobfilters/'\n + (g.board.name + '/' if g.board else '')\n + hashlib.blake2b(repr(filters).encode('utf-8'), digest_size=16).hexdigest()\n )\n result = cache.get(cache_key)\n if not result:\n basequery = getposts(showall=True, order=False, limit=False)\n result = {\n 'job_location_filters': filter_locations(g.board, filters),\n 'job_type_filters': filter_types(\n basequery, board=g.board, filters=filters\n ),\n 'job_category_filters': filter_categories(\n basequery, board=g.board, filters=filters\n ),\n }\n cache.set(cache_key, result, timeout=3600)\n return result\n\n return {'job_filters': get_job_filters}\n","repo_name":"hasgeek/hasjob","sub_path":"hasjob/views/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":39190,"program_lang":"python","lang":"en","doc_type":"code","stars":236,"dataset":"github-code","pt":"77"}
+{"seq_id":"39756854399","text":"\ndef insert(intervals, newInterval):\n intervals.append(newInterval)\n intervals = sorted(intervals)\n output = [intervals[0]]\n for i in intervals:\n if i[0] <= output[-1][1]:\n output[-1][1] = max(output[-1][1],i[1])\n else:\n output.append(i)\n return output\n\n# Add the new interval into the array and sort based off the start time.\n# Add the new interval if the start time does not match the old start time\n# otherwise compare the start and end time of the new and oldest interval in\n# the updated array and change it to the maximum. O(nlogn), O(n) space\nintervals = [[1,3],[6,9]]\nnewInterval = [2,5]\nupdatedInterval = insert(intervals,newInterval)\nprint(updatedInterval)\n","repo_name":"patchangg/LeetCode","sub_path":"Python/Medium/57.py","file_name":"57.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"5880600215","text":"import flask\nfrom flask import request, render_template, url_for\nfrom flask_cors import CORS\nfrom flask import request\nimport numpy as np\n\nfrom Ecals import *\nfrom Staticcals import *\n\napp = flask.Flask(__name__, template_folder='templates')\napp.config[\"DEBUG\"] = True\ncors = CORS(app)\napp.config['CORS_HEADERS'] = 'Content-Type'\n\n@app.route('/')\ndef index():\n # return '''API homepage \n # API for all operations.
'''\n return render_template(\"index.html\")\n\n@app.route('/log', methods=['POST'])\ndef logs():\n return render_template(\"logarithm.html\")\n\n@app.route('/GLC', methods=['POST'])\ndef glcs():\n return render_template(\"GLC.html\")\n\n@app.route('/stdv', methods=['POST'])\ndef stdvs():\n return render_template(\"std.html\")\n\n@app.route('/trig', methods=['POST'])\ndef trigs():\n return render_template(\"Trigonomentry.html\")\n\n@app.route('/rootes', methods=['POST'])\ndef rootess():\n return render_template(\"roots.html\")\n\n@app.route('/electronics', methods=['POST'])\ndef electronicss():\n return render_template(\"electronic.html\")\n\n@app.route('/linearreg', methods=['POST'])\ndef lers():\n return render_template(\"linearregression.html\")\n\n\n\n@app.route('/PVR', methods=['POST'])\n# @cross_origin(origin='*', headers=['Content-Type', 'Authorization'])\ndef find_missing():\n print('at start')\n select = request.form.get(\"tofind\")\n if select == 'watts':\n I = float(request.form.get(\"ampere\"))\n V = float(request.form.get(\"volts\"))\n P = cal_watts(I, V)\n kW = cal_kiloWatt(P)\n SkVA = cal_kiloVoltamps(I, V)\n # return (\"The Ampere: \" + str(I) + \" The watts :\" + str(P) + \" The Volts: \" + str(V))\n result = (\"The Ampere: \" + str(I) + \"The Volts: \" + str(V) + \"The watts :\" + str(P) + \" KiloWatt(kW): \" + str(kW) + \" KiloVoltAmps(kVA): \" + str(SkVA))\n elif select == 'ampere':\n P = float(request.form.get(\"watts\"))\n V = float(request.form.get(\"volts\"))\n I = cal_amperes(P, V)\n kW = cal_kiloWatt(P)\n SkVA = cal_kiloVoltamps(I, V)\n # return (\"The Ampere: \" + str(I) + \" The watts :\" + str(P) + \" The Volts: \" + str(V))\n result = (\"The Ampere: \" + str(I) + \"The Volts: \" + str(V) + \"The watts :\" + str(P) + \" KiloWatt(kW): \" + str(kW) + \" KiloVoltAmps(kVA): \" + str(SkVA))\n elif select == 'volts':\n P = float(request.form.get(\"watts\"))\n I = float(request.form.get(\"ampere\"))\n V = cal_volts(P, I)\n kW = cal_kiloWatt(P)\n SkVA = cal_kiloVoltamps(I, V)\n # return (\"The Ampere: \" + str(I) + \" The watts :\" + str(P) + \" The Volts: \" + str(V))\n result = (\"The Ampere: \" + str(I) + \"The Volts: \" + str(V) + \"The watts :\" + str(P) + \" KiloWatt(kW): \" + str(kW) + \" KiloVoltAmps(kVA): \" + str(SkVA))\n else:\n result = select\n return render_template('electronic.html', message=result)\n\n@app.route('/coverstion', methods=['POST'])\ndef convertion_api():\n print('at start')\n\n select = request.form.get(\"tofind\")\n phase = request.form.get(\"tophase\")\n if phase == 'single':\n Op = 'single'\n if select == 'VA':\n I = float(request.form.get(\"amps\"))\n V = float(request.form.get(\"volt\"))\n VA = cal_vaone(I, V)\n # print (\"The Ampere: \" + str(I) + \" The watts :\" + str(P) + \" The Volts: \" + str(V))\n result = (\"The VA for single phase: \"+ str(VA))\n\n\n elif select == 'Amps':\n VA = float(request.form.get(\"va\"))\n V = float(request.form.get(\"volt\"))\n amps = cal_vaampone(VA, V, Op)\n result = (\"The Amps for single phase: \" + str(amps))\n return render_template('electronic.html', coutput=result)\n elif select == 'kvaAmps':\n kVA = float(request.form.get(\"kva\"))\n V = float(request.form.get(\"volt\"))\n amps = cal_kvaampone(kVA, V, Op)\n result = (\"The Ampere for single phase: \" + str(amps))\n return render_template('electronic.html', coutput=result)\n elif select == 'Ampskva':\n I = float(request.form.get(\"amps\"))\n V = float(request.form.get(\"volt\"))\n kVA = cal_ampkvaone(I, V, Op)\n result = (\"The kVA for single phase: \" + str(kVA))\n return render_template('electronic.html', coutput=result)\n elif phase == 'three':\n Op = 'three'\n if select == 'VA':\n I = float(request.form.get(\"amps\"))\n V = float(request.form.get(\"volt\"))\n VA = cal_vathree(I, V)\n # print (\"The Ampere: \" + str(I) + \" The watts :\" + str(P) + \" The Volts: \" + str(V))\n result = (\"The VA for Three phase: \" + str(VA))\n return render_template('electronic.html', coutput=result)\n elif select == 'Amps':\n VA = float(request.form.get(\"va\"))\n V = float(request.form.get(\"volt\"))\n amps = cal_vaampone(VA, V, Op)\n result = (\"The Amps for Three phase: \" + str(amps))\n return render_template('electronic.html', coutput=result)\n elif select == 'kvaAmps':\n kVA = float(request.form.get(\"kva\"))\n V = float(request.form.get(\"volt\"))\n amps = cal_kvaampone(kVA, V, Op)\n result = (\"The Ampere for three phase: \" + str(amps))\n return render_template('electronic.html', coutput=result)\n elif select == 'Ampskva':\n I = float(request.form.get(\"amps\"))\n V = float(request.form.get(\"volt\"))\n kVA = cal_ampkvaone(I, V, Op)\n result = (\"The kVA for Three phase: \" + str(kVA))\n return render_template('electronic.html', coutput=result)\n elif phase == 'none':\n P = float(request.form.get(\"jwatts\"))\n S = float(request.form.get(\"jsec\"))\n J = cal_wjoule(P, S)\n result = (\"The Watts :\"+str(P)+\" The Seconds :\"+str(S)+\" The Joule: \" + str(J))\n return render_template('electronic.html', coutput=result)\n\n\n@app.route('/staticcalc', methods=['POST'])\ndef staticcalc_api():\n print('static calc')\n String = request.form.get(\"lists\")\n print(String)\n li = list(String.split(','))\n for i in range(0, len(li)):\n li[i] = int(li[i])\n # print(li)\n # li = [1,5,4,2,0]\n sd = standard_calculus(li)\n var = variance(li)\n return render_template('std.html',arrayentd=String, sd=sd, var=var)\n\n@app.route('/mathlog2', methods=['POST'])\ndef mathlogic2_api():\n print(\"mathlogic api\")\n select = request.form.get(\"mathlog2list\")\n # print(select)\n if select == \"gcdlist\":\n nm = str(request.form.get(\"gcdlists\"))\n # print(nm)\n nm = list(nm.split(','))\n for i in range(0, len(nm)):\n nm[i] = int(nm[i])\n # print(nm)\n # nm = [21, 3, 71]\n res = nm[0]\n # print(res)\n for i in range (len(nm)):\n res = gcd_function(res,nm[i])\n i = i+1\n gcd = res\n lcm = lcm_function(nm)\n return render_template('GLC.html',arrayented=nm, gcd=gcd, lcm =lcm)\n elif select == \"sqlist\":\n sqnumber = request.form.get(\"sqnum\")\n # print(sqnumber)\n sqroot = find_sqroot(sqnumber)\n return render_template('index.html', sqroot=sqroot)\n elif select == \"nsqlist\":\n sqnumber = request.form.get(\"sqnum\")\n rootsq = request.form.get(\"ntimes\")\n # print(sqnumber)\n sqroot = find_sqroot(sqnumber)\n curoot = find_nsqroot(sqnumber, 3)\n nsqroot = find_nsqroot(sqnumber, rootsq)\n return render_template('roots.html',sqvalue=sqnumber, nthtime=rootsq, nsqroot=nsqroot, sqroot = sqroot, curoot = curoot)\n # elif select == \"lcmlist\":\n # numbers = request.form.get(\"lcmnumber\")\n # print(numbers)\n # arr = [2, 7, 3, 9, 4]\n # lcmresult = lcm_function(arr)\n # return render_template('index.html', lcmresult=lcmresult)\n@app.route('/mathlog3', methods=['POST'])\ndef mathlogic3_api():\n print(\"trignomentry api\")\n select = request.form.get(\"mathlog3list\")\n if select == \"alllist\":\n theta = float(request.form.get(\"tdegree\"))\n print(theta)\n sin = my_sin(theta)\n cos = my_cos(theta)\n tan = my_tan(theta)\n cosec = my_cosec(theta)\n sec = my_sec(theta)\n cot = my_cot(theta)\n if tan >= 1000 or (tan <= -10792.951559972442):\n tan = \"-\"\n if (cosec >= 1000) or (cosec <= -10792.951559972442):\n cosec = \"-\"\n if sec >= 1000 or (sec <= -10792.951559972442):\n sec = \"-\"\n if cos >= 1000 or (cos <= -10792.951559972442):\n cos = \"-\"\n if cot >= 1000 or (cot <= -10792.951559972442):\n cot = \"-\"\n\n return render_template('trigonomentry.html',degree=theta, sin=sin, cos=cos, tan=tan, cot=cot, sec=sec, cosec=cosec)\n # print(sin)\n\n@app.route('/invmathlog3', methods=['POST'])\ndef invmathlogic3_api():\n select = request.form.get(\"opChoice\")\n x = float(request.form.get(\"xaxis\"))\n if select == \"0\":\n val = \"arc sin\"\n y = np.arcsin(x)\n y= y *(180/math.pi)\n if select == \"1\":\n val = \"arc cos\"\n y = np.arccos(x)\n y = y * (180 / math.pi)\n if select == \"2\":\n val = \"arc tan\"\n y = math.atan(x)\n y = y * (180 / math.pi)\n\n return render_template('trigonomentry.html', val=val, x=x, y=y)\n\n@app.route('/mathlog1', methods=['POST'])\ndef logcalc():\n opChoice = int(request.form.get('opChoice'))\n\n if (opChoice == 0 and not request.form.get('num3') and not request.form.get('base')):\n output = 'Enter the required data'\n return render_template('logarithm.html', data=output)\n elif (opChoice == 1 and not request.form.get('num')):\n output = 'Enter the required data'\n return render_template('logarithm.html', data=output)\n elif (opChoice == 2 and not request.form.get('data') and not request.form.get('pow')):\n output = 'Enter the required data'\n return render_template('logarithm.html', data=output)\n\n vOpName = data = pow = num = num3 = 0\n\n if (opChoice == 0):\n data = int(request.form.get('numb'))\n base = int(request.form.get('base'))\n\n vOpName = \"Log \"\n vresult = log(data, base)\n output = \"The number : \" + str(data) + \" The base : \" + str(base) + \" The function : \" + str(vOpName) + \" The result : \" + str(vresult)\n elif (opChoice == 1):\n data = int(request.form.get('numn'))\n\n vresult = nLog(data)\n vOpName = \"Natural Log \"\n output = \"The number : \" + str(data) + \" The function : \" + str(vOpName) + \" The result : \" + str(vresult)\n\n elif (opChoice == 2):\n data = int(request.form.get('numa'))\n pow = int(request.form.get('pow'))\n vresult = antiLog(data, pow)\n vOpName = \"AntiLog \"\n output = \"The number : \" + str(data) + \" The power : \" + str(pow) + \" The function : \" + str(vOpName) + \" The result : \" + str(vresult)\n\n # print(pow)\n # print(data)\n # print(vresult)\n # print(vOpName)\n\n\n # return home(str(data), str(vresult), str(vOpName), str(pow), str(data), str(data))\n return render_template('logarithm.html', data=output)\n\n@app.route('/linearregression', methods=['POST'])\ndef lerrs():\n param_xList = request.form['xList']\n param_yList = request.form['yList']\n\n param_xList = list(param_xList.split(','))\n for i in range(0, len(param_xList)):\n param_xList[i] = float(param_xList[i])\n\n param_yList = list(param_yList.split(','))\n for i in range(0, len(param_yList)):\n param_yList[i] = float(param_yList[i])\n\n if len(getNumberList(param_xList)) == len(getNumberList(param_yList)):\n print(1)\n xList = getNumberList(param_xList)\n yList = getNumberList(param_yList)\n sum_xlist = 0\n sum_ylist = 0\n sum_xSquare = 0\n sum_xy = 0\n n = len(xList)\n for i in range(n):\n sum_xlist = sum_xlist + xList[i]\n sum_ylist = sum_ylist + yList[i]\n sum_xSquare = sum_xSquare + (xList[i] * xList[i])\n sum_xy = sum_xy + (xList[i] * yList[i])\n\n slope = (n * sum_xy - sum_xlist * sum_ylist) / (n * sum_xSquare - sum_xlist * sum_xlist);\n intercept = (sum_ylist - slope * sum_xlist) / n\n equartion = \"y = \" + str(slope) + \" x = \" + str(intercept)\n res = [str(equartion)]\n\n else:\n res = \"OOPS ! Some internal error\"\n return render_template(\"linearregression.html\", Xarrayented=param_xList, Yarrayented=param_yList, res=res)\n\napp.run(host='127.0.0.1', port=5012)","repo_name":"arjithchandru/WebServices-and-SOA","sub_path":"SOA2/Python/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12600,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"31394316898","text":"import logging\nimport os\nfrom datetime import datetime\n\nfrom tqdm import tqdm\n\nfrom data_handler.mongo import MongoDataHandler\nfrom fmp import financial_data\n\nlogging.basicConfig(filename='{}/logs/load_income_statements.log'.format(os.path.dirname(os.getcwd())),\n level=logging.INFO,\n format='%(asctime)s %(levelname)s %(name)s %(message)s')\nlogger = logging.getLogger(__name__)\n\n\ndef main():\n now = datetime.now()\n current_year = now.year\n logger.info(\"Company income statement loading script started.\")\n data_client = MongoDataHandler()\n tickers = data_client.get_ticker_list()\n income_filed_companies = data_client.get_income_filed_companies(str(current_year))\n income_unfiled_companies = (set(tickers) - set(income_filed_companies))\n logger.info(\"{} unfiled companies to process\".format(len(income_unfiled_companies)))\n [get_and_load_income_statements(company, data_client) for company in tqdm(income_unfiled_companies)]\n data_client.close_client()\n\n\ndef get_and_load_income_statements(company: str, data_client: MongoDataHandler) -> None:\n try:\n income_statements = financial_data.get_income_statements(company)\n if income_statements:\n data_client.update_income_statements(company, income_statements)\n logger.info(\"No income statements found for: {}.\".format(company))\n except Exception as err:\n logger.info(\"Loading income statements failed for: {} Error: {}\".format(company, err))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"dinushawiki/fundamental_data_loader","sub_path":"load/load_income_statements.py","file_name":"load_income_statements.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"23598656499","text":"\"\"\"\nEvent-driven framework of VeighNa framework.\n\"\"\"\n\nfrom collections import defaultdict\nfrom queue import Empty, Queue\nfrom threading import Thread\nfrom time import sleep\nfrom typing import Any, Callable, List\n\nEVENT_TIMER = \"eTimer\"\n\n\nclass Event:\n \"\"\"\n Event object consists of a type string which is used\n by event engine for distributing event, and a data\n object which contains the real data.\n \"\"\"\n\n def __init__(self, type: str, data: Any = None) -> None:\n \"\"\"\"\"\"\n self.type: str = type\n self.data: Any = data\n\n\n# Defines handler function to be used in event engine.\nHandlerType: callable = Callable[[Event], None]\n\n\nclass EventEngine:\n \"\"\"\n Event engine distributes event object based on its type\n to those handlers registered.\n\n It also generates timer event by every interval seconds,\n which can be used for timing purpose.\n \"\"\"\n\n def __init__(self, interval: int = 1) -> None:\n \"\"\"\n Timer event is generated every 1 second by default, if\n interval not specified.\n \"\"\"\n self._interval: int = interval\n self._queue: Queue = Queue()\n self._active: bool = False\n self._thread: Thread = Thread(target=self._run)\n self._timer: Thread = Thread(target=self._run_timer)\n self._handlers: defaultdict = defaultdict(list)\n self._general_handlers: List = []\n\n def _run(self) -> None:\n \"\"\"\n Get event from queue and then process it.\n \"\"\"\n while self._active:\n try:\n event: Event = self._queue.get(block=True, timeout=1)\n self._process(event)\n except Empty:\n pass\n\n def _process(self, event: Event) -> None:\n \"\"\"\n First distribute event to those handlers registered listening\n to this type.\n\n Then distribute event to those general handlers which listens\n to all types.\n \"\"\"\n if event.type in self._handlers:\n [handler(event) for handler in self._handlers[event.type]]\n\n if self._general_handlers:\n [handler(event) for handler in self._general_handlers]\n\n def _run_timer(self) -> None:\n \"\"\"\n Sleep by interval second(s) and then generate a timer event.\n \"\"\"\n while self._active:\n sleep(self._interval)\n event: Event = Event(EVENT_TIMER)\n self.put(event)\n\n def start(self) -> None:\n \"\"\"\n Start event engine to process events and generate timer events.\n \"\"\"\n self._active = True\n self._thread.start()\n self._timer.start()\n\n def stop(self) -> None:\n \"\"\"\n Stop event engine.\n \"\"\"\n self._active = False\n self._timer.join()\n self._thread.join()\n\n def put(self, event: Event) -> None:\n \"\"\"\n Put an event object into event queue.\n \"\"\"\n self._queue.put(event)\n\n def register(self, type: str, handler: HandlerType) -> None:\n \"\"\"\n Register a new handler function for a specific event type. Every\n function can only be registered once for each event type.\n \"\"\"\n handler_list: list = self._handlers[type]\n if handler not in handler_list:\n handler_list.append(handler)\n\n def unregister(self, type: str, handler: HandlerType) -> None:\n \"\"\"\n Unregister an existing handler function from event engine.\n \"\"\"\n handler_list: list = self._handlers[type]\n\n if handler in handler_list:\n handler_list.remove(handler)\n\n if not handler_list:\n self._handlers.pop(type)\n\n def register_general(self, handler: HandlerType) -> None:\n \"\"\"\n Register a new handler function for all event types. Every\n function can only be registered once for each event type.\n \"\"\"\n if handler not in self._general_handlers:\n self._general_handlers.append(handler)\n\n def unregister_general(self, handler: HandlerType) -> None:\n \"\"\"\n Unregister an existing general handler function.\n \"\"\"\n if handler in self._general_handlers:\n self._general_handlers.remove(handler)\n","repo_name":"vnpy/vnpy","sub_path":"vnpy/event/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":4227,"program_lang":"python","lang":"en","doc_type":"code","stars":22169,"dataset":"github-code","pt":"77"}
+{"seq_id":"22615119868","text":"import numpy as np\n\nfrom autoencoder.helpers import create_autoencoder_model, train_autoencoder, \\\n predict_autoencoder, calculate_threshold, plot_prediction, plot_mae_histogram, plot_anomalies\nfrom common.helpers import clean_dataframes, read_data_from_directory, normalize_dataframes, create_sequences, SAMPLE_1\n\n# Data Reading\nanomaly, normal = read_data_from_directory(SAMPLE_1)\n\n# Data Cleaning\nWINDOW_SIZE = 64\nKEY_ATTRIBUTES = [\"Z-location\", \"Z-Velocity\", \"AnalogInVoltage\", \"AverageFeedRate\"]\nSMA_ATTRIBUTES = [\"Z-Velocity\", \"AnalogInVoltage\"]\ncleaned_anomalies = clean_dataframes(anomaly, KEY_ATTRIBUTES, WINDOW_SIZE, SMA_ATTRIBUTES)\ncleaned_normals = clean_dataframes(normal, KEY_ATTRIBUTES, WINDOW_SIZE, SMA_ATTRIBUTES)\n\n# Data Preparation\nnormalized_anomalies, anomalies_means, anomalies_stds = normalize_dataframes(cleaned_anomalies)\nnormalized_normals, normals_means, normals_stds = normalize_dataframes(cleaned_normals)\nsequences_anomalies = create_sequences(normalized_anomalies, WINDOW_SIZE)\nsequences_normals = create_sequences(normalized_normals, WINDOW_SIZE)\n\n# Data dividing into training and test sets\ntraining_set = sequences_normals[:-1]\ntest_normal = sequences_normals[-1]\ntest_anomalies = sequences_anomalies\n\n# Defining the Autoencoder Model\ninput_shape = sequences_anomalies[0].shape\nautoencoder = create_autoencoder_model(input_shape)\nautoencoder.summary()\n\n# Training\ntrain_autoencoder(autoencoder, training_set)\ntraining_predicted_seqs, training_avg_mae_loss = predict_autoencoder(autoencoder, training_set)\ntest_predicted_seqs, test_avg_mae_loss = predict_autoencoder(autoencoder, test_anomalies)\n\n# Training Visualisation\nSAMPLE = -1\nSEQ = 10\nplot_prediction(training_set[SAMPLE][SEQ], training_predicted_seqs[SAMPLE][SEQ])\n\n# Testing: Setting threshold\nthreshold = calculate_threshold(training_avg_mae_loss)\ntest_threshold = calculate_threshold(test_avg_mae_loss)\n\n# Predicting anomalies\nfor test_predicted, test_original, original_df, raw_df in zip(test_predicted_seqs, test_anomalies, cleaned_anomalies,\n anomaly):\n individual_mae_loss = np.mean(np.abs(test_predicted - test_original), axis=1)\n plot_mae_histogram(individual_mae_loss, KEY_ATTRIBUTES)\n anomalies = individual_mae_loss > threshold\n\n anomalous_data_indices = []\n df_test_value = original_df.values\n for data_idx in range(WINDOW_SIZE - 1, len(df_test_value) - WINDOW_SIZE + 1):\n if np.any(anomalies[data_idx - WINDOW_SIZE + 1: data_idx]):\n anomalous_data_indices.append(data_idx)\n\n plot_anomalies(original_df, anomalous_data_indices)\n","repo_name":"dawikrol/TimeSeries-Anomaly-Detector","sub_path":"autoencoder/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"20737306233","text":"import numpy as np\nimport itertools\nimport pandas as pd\n\ndef get_all_drivers():\n return np.loadtxt('../data/drivers.txt', dtype=np.uint)\n\n\nif __name__ == '__main__':\n\t# Settings here\n\tinput_file = '../data/subshifthead.csv'\n\toutput_file = '../data/subshifthead5.csv'\n\tdenominator = 5.0\n\n\tall_drivers = get_all_drivers()\n\tind = [str(driver)+'_'+str(trip) for driver, trip in itertools.product(all_drivers, np.arange(1,201))]\n\toriginal_df = pd.read_csv(input_file, header=0, index_col=0)\n\n\tdf = pd.DataFrame(index=ind)\n\tfor n, driver in enumerate(all_drivers):\n\t\t#print('Driver no. %5u (%5u/%5u)' % (driver, n, len(all_drivers)))\n\t\t\n\t\t# Load matrix\n\t\tm = np.loadtxt('../data/mats2/'+str(driver)+'_similarityMatrixNew.csv', dtype=np.float, delimiter=',')\n\n\t\t# Create the index for the trips\n\t\tind = []\n\t\tfor i in np.arange(1,201):\n\t\t\tind.append(str(driver)+'_'+str(i))\n\n\t\t# compute probabilities\n\t\tp = original_probs = original_df.ix[ind, 'prob'].values\n\t\trepeated = np.sum(m, 1)[1:]; # array of repetitions\n\t\tp = 1 - (1-p)**(1+repeated/denominator);\n\n\t\t# Add the new probas\n\t\tdf.ix[ind,'prob'] = p\n\n\tdf.to_csv(output_file, index_label='driver_trip')\n","repo_name":"Plantaquatix/Driver-analysis","sub_path":"code/Rescale.py","file_name":"Rescale.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"41200273425","text":"#Function to add any number of inputs in range of 1-5\nprint(\"Enter the number of inputs to add\\n\")\na=int(input(\">\"))\nno=1 \nsum_=0\nwhile(no<=a):\n print(\"Enter Input \",no,\"\\n\")\n input_=int(input(\">\"))\n if(input_<1 or input_>5):\n print(\"Limit exceeded\")\n continue\n sum_+=input_\n no+=1\n \nprint(sum_) \n \n","repo_name":"MarkTLite/BackEnd_Coding","sub_path":"Python---Practice/add0.py","file_name":"add0.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"27102658498","text":"\n\ndef collectMoney(m, n):\n ts = 0\n nts = 0\n mat = False\n for a in range(1, m + 1):\n if ts != n:\n ts += a\n mat = True\n if mat:\n for a in range(2, m + 1):\n if nts != n:\n nts += a\n if ts > nts:\n print(ts)\n else:\n print(nts)\n print(ts, nts)\n\n\ncollectMoney(6, 15)\n","repo_name":"bipulcn/python_problem","sub_path":"quiz_10_doller.py","file_name":"quiz_10_doller.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"17525941192","text":"\n\ndef maxHeight(wallPositions, wallHeights):\n arr = [0] * (wallPositions[-1])\n\n for x,y in zip(wallPositions, wallHeights):\n arr[x-1] = y\n\n max_height = 0\n for i in range(0, len(arr)):\n if arr[i] == 0:\n max_index, next_non_zero_at_right = next_non_zero(arr[i+1:])\n new_height = min(next_non_zero_at_right+2, arr[i-1]+1)\n if new_height - (next_non_zero_at_right + max_index )> 1:\n new_height = next_non_zero_at_right + 1\n arr[i] = new_height\n if new_height > max_height:\n max_height = new_height\n\n return max_height\n\n\ndef next_non_zero(arr):\n for i, elem in enumerate(arr):\n if elem > 0:\n return (i, elem)\n\n\nif __name__ == '__main__':\n print(maxHeight([1,3,7], [4,3,3]))\n print(maxHeight([1,10], [1,5]))\n","repo_name":"kashifusmani/interview_prep","sub_path":"fathom/maxHeight.py","file_name":"maxHeight.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"305376217","text":"from django.urls import path\nfrom .views import home_view, detail_view, create_view, update_view, delete_view, login_view, logout_view, register_view\n\nurlpatterns = [\n path('', home_view, name='home'),\n path('login/', login_view, name='login'),\n path('logout/', logout_view, name='logout'),\n path('register/', register_view, name='register'),\n\n path('task/', detail_view, name='detail'),\n path('add-task/', create_view, name='create'),\n path('update-task/', update_view, name='update'),\n path('delete-task/', delete_view, name='delete'),\n]","repo_name":"pleasejelpme/fbv-todo-app","sub_path":"src/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"26633498356","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\n@Time : 2022/04/27 16:54:20\n@Author : pengyuan.li\n@File : 0x06-geniusacm.py\n@Software: VSCode\n'''\n\n# here put the import lib\nfrom typing import List\n\n\ndef geniusAcm(A: List[int], M: int, T: int) -> int:\n \"\"\"\n 我们要把 A 分成若干段,M对数(2*M),使得每一段的“校验值”都不超过 T。\n 求最少需要分成几段。\n \"\"\"\n res = 0\n start = 0\n n = len(A)\n\n def getSqrt(l, r):\n tmpList = []\n for i in range(l, r + 1):\n tmpList.append(A[i])\n tmpList.sort()\n k = len(tmpList)\n s = 0\n for i in range(min(M, k)):\n s += (tmpList[k - 1] - tmpList[i]) * (tmpList[k - 1] - tmpList[i])\n k -= 1\n return s\n\n while start < n:\n l = start\n r = n\n while l < r:\n mid = (l + r) >> 1\n if getSqrt(start, mid) > T:\n r = mid\n else:\n l = mid + 1\n start = r\n res += 1\n return res\n\n\ndef geniusAcm2(A: List[int], M: int, T: int) -> int:\n \"\"\"\n 我们要把 A 分成若干段,M对数(2*M),使得每一段的“校验值”都不超过 T。\n 求最少需要分成几段。\n \"\"\"\n res = 0\n n = len(A)\n\n def getSqrt(l, r):\n tmpList = []\n for i in range(l, r):\n tmpList.append(A[i])\n tmpList.sort()\n k = len(tmpList)\n s = 0\n for i in range(min(M, k)):\n s += (tmpList[k - 1] - tmpList[i]) * (tmpList[k - 1] - tmpList[i])\n k -= 1\n return s\n\n l, r = 0, 0\n while r < n:\n p = 1\n while p > 0:\n # [l,r+p)\n if r + p <= n and getSqrt(l, r + p) <= T:\n r += p\n p <<= 1\n else:\n p >>= 1\n l = r\n res += 1\n return res\n\n\nif __name__ == \"__main__\":\n A = [8, 2, 1, 7, 9]\n M = 1\n T = 49\n print(geniusAcm(A, M, T))\n print(geniusAcm2(A, M, T))\n\n A = [8, 2, 1, 7, 9]\n M = 1\n T = 64\n print(geniusAcm(A, M, T))\n print(geniusAcm2(A, M, T))\n","repo_name":"whitepaper2/algoDiary","sub_path":"algo-improve/0x06-geniusacm.py","file_name":"0x06-geniusacm.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"41568402497","text":"number_int = int(input(\"Enter an integer: \")) #Forritið biður notandan um input\n\nthe_sum = 0 #Breyta sem verður notið til þess að summa tölur\nodd_number = 0 #Breyta sem verður notuð til þess að finna oddatölur\neven_number = 0 #Breyta sem verður notuð til þess að finna sléttar tölur\nlargest_int = 0 #Breyta sem verður notið til þess að finna stærstu töluna\n\ncumlative_total = the_sum + number_int #Breyta sem verður notuð til að summa tölur\n\nwhile number_int > 0: #Lykkjan heldur áfram svo lengi sem að talan er stærri en 0\n if number_int % 2 == 1: #Ef remainder af inputi er 1 þá er talan oddatala\n odd_number += 1 #Counter sem er notaður til þess að telja allar oddatölur\n if number_int % 2 == 0: #Ef remainder af inputi er 0 þá er talan slétt tala\n even_number += 1 #Counter sem er notaður til þses að telja allara sléttar tölur\n if number_int > largest_int: #Ef inputið er hærra en stærsta talan þá breytist þá verður stærsta talan \"largest_int\" að inputin eða \"number_int\"\n largest_int = number_int\n print (\"Cumulative total:\", cumlative_total) #Prentar út summuna á hverri tölu fyrir sig\n number_int = int(input(\"Enter an integer: \")) #Biður notandan um input svo lengi sem að talan er ekki 0\n the_sum += number_int #Þetta er counter sem að bætir alltaf inputinu við sjálfan sig\n cumlative_total += number_int #Þetta er counter sem bætir inputinu við cumlative_total\n\n\nif cumlative_total != 0: # ef að summan er ekki 0 þá prentast \"largest_int\" \"even_number\" og \"odd_number\"\n print (\"Largest number:\",(largest_int))\n print (\"Count of even numbers:\", even_number)\n print (\"Count of odd numbers:\", odd_number)\n\n\n \n","repo_name":"bituser1337/Skoli-Ru","sub_path":"Skilaverkefni/int_seq.py","file_name":"int_seq.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"is","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"40966060454","text":"from flask_app.models import user, item, category\n\ncategory1 = {\n \"name\": \"clothing\"\n}\n\ncategory2 = {\n \"name\": \"electronics\"\n}\n\ncategory3 = {\n \"name\": \"outdoors\"\n}\n\n# category.Category.createCategory(category1)\n# category.Category.createCategory(category2)\n# category.Category.createCategory(category3)\n\n\nitem1 = {\n \"item_name\" : \"shoes\",\n \"cost\" : \"10\",\n \"location\" : \"Seattle\",\n \"image\" : \"image.png\",\n \"brief_desc\" : \"used Nike size 9\",\n \"details\" : \"Nikes red and black, size 9, bought in 2019, only worn twice\",\n \"user_id\" : \"1\",\n \"category_id\" : \"1\",\n}\n\nitem2 = {\n \"item_name\" : \"headphones\",\n \"cost\" : \"30\",\n \"location\" : \"Bellevue\",\n \"image\" : \"image.png\",\n \"brief_desc\" : \"new Bose headphones\",\n \"details\" : \"black 2020 Bose headphones, brand new in box\",\n \"user_id\" : \"2\",\n \"category_id\" : \"2\",\n}\n\nitem3 = {\n \"item_name\" : \"kayak\",\n \"cost\" : \"250\",\n \"location\" : \"issaquah\",\n \"image\" : \"image.png\",\n \"brief_desc\" : \"inflatable kayak\",\n \"details\" : \"2003 NRS inflatable kayak, 2 patched holes, a few scuff marks\",\n \"user_id\" : \"2\",\n \"category_id\" : \"3\",\n}\n\nitem3a = {\n 'id': 3,\n \"item_name\" : \"NRS kayak\",\n \"cost\" : \"250\",\n \"location\" : \"Issaquah\",\n \"image\" : \"image.png\",\n \"brief_desc\" : \"inflatable kayak\",\n \"details\" : \"2003 NRS inflatable kayak, 2 patched holes, a few scuff marks\",\n \"user_id\" : \"2\",\n \"category_id\" : \"3\",\n}\n\n# item.Item.save(item1)\n# item.Item.save(item2)\n# item.Item.save(item3)\n\n# print(item.Item.get_all())\n\n# print(item.Item.get_one(1))\n\n# item.Item.update(item3a)\n\n# item.Item.delete(2)","repo_name":"SecondHandSourcing/SecondHandSourcing","sub_path":"itemTest.py","file_name":"itemTest.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"5396626235","text":"import requests\nimport pandas as pd\nfrom pandas import json_normalize \nfrom datetime import datetime\nfrom time import sleep\nimport json\nimport pytz\n\ndef call_nhl(startSeason, endSeason=None):\n\n # Possible to call API for multiple seasons, \n # but if no end season is provided, set end season = start season.\n if not endSeason:\n endSeason = startSeason\n\n # Headers in the API call authenticate the requests\n headers = {\n 'authority': 'api.nhle.com',\n # Could cycle through different user agents using the fake-useragent module \n # if the API appears to be blocking repeated calls\n 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36',\n 'accept': '*/*',\n 'origin': 'http://www.nhl.com',\n 'sec-fetch-site': 'cross-site',\n 'sec-fetch-mode': 'cors',\n 'sec-fetch-dest': 'empty',\n 'referer': 'http://www.nhl.com/',\n 'accept-language': 'en-US,en;q=0.9',\n }\n\n params = (\n ('isAggregate', 'false'),\n ('isGame', 'true'),\n ('sort', '[{\"property\":\"gameDate\",\"direction\":\"DESC\"}]'),\n ('start', '0'),\n # Setting limit = 0 returns all games for given season\n ('limit', '0'),\n ('factCayenneExp', 'gamesPlayed>=1'),\n # Through trial and error, gameTypeId=2 corresponds to regular season games\n # The f-string inserts endSeason and startSeason into the parameters\n ('cayenneExp', f'gameTypeId=2 and seasonId<={endSeason} and seasonId>={startSeason}'),\n )\n \n # Call API with given headers and parameters\n response = requests.get('https://api.nhle.com/stats/rest/en/team/summary', headers=headers, params=params)\n\n return response\n\ndef get_gameData(startYear, numSeasons):\n\n seasons = [f\"{startYear+i}{startYear+i+1}\" for i in range(numSeasons)]\n\n rows=0\n res = {}\n\n for s in seasons:\n response = call_nhl(s)\n\n # Try except is probably more appropriate,\n # but if it ain't broke...\n if response:\n response = response.json()\n rows+=len(response['data'])\n df = pd.json_normalize(response['data'])\n res[s] = df\n print(f\"Number of games grabbed for {s} = {len(response['data'])}. Total = {rows}\")\n else:\n print(\"ERROR: unable to connect to NHL API\")\n return None\n\n return res\n\ndef get_teamLU(df):\n return dict(zip(df['teamId'], df['teamFullName']))\n\ndef home_road(df, teamLU):\n res = {}\n res['home'] = df[df['homeRoad']=='H']['teamId'].values[0]\n res['road'] = df[df['homeRoad']=='R']['teamId'].values[0]\n\n res['homeName'] = teamLU[res['home']]\n res['roadName'] = teamLU[res['road']]\n\n return pd.Series(res, index=res.keys())\n\n# def get_schedule(df, teamLU):\n# return df.groupby(['gameId', 'gameDate']).apply(home_road, teamLU)\n\ndef get_schedule(season_start = None):\n if season_start == None:\n if datetime.now().month < 10:\n season_start = datetime.now().year - 1\n else:\n season_start = datetime.now().year\n\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0',\n 'Accept': '*/*',\n 'Accept-Language': 'en-CA,en-US;q=0.7,en;q=0.3',\n 'Origin': 'https://www.nhl.com',\n 'DNT': '1',\n 'Connection': 'keep-alive',\n 'Referer': 'https://www.nhl.com/',\n }\n\n params = (\n #('startDate', f'{season_start}-10-1'),\n #('endDate', f'{season_start+1}-05-15'),\n ('season', f'{season_start}{season_start+1}'),\n ('hydrate', 'team,linescore'),\n ('site', 'en_nhlCA'),\n ('teamId', ''),\n ('gameType', 'R'),\n ('timecode', ''),\n )\n\n response = requests.get('https://statsapi.web.nhl.com/api/v1/schedule', headers=headers, params=params)\n \n data = json.loads(response.text)\n df = pd.json_normalize(data['dates'], record_path = ['games'])\n \n eastern = pytz.timezone('US/Eastern')\n\n sched_df = df.loc[:,[\n 'gameDate', \n 'teams.home.team.abbreviation', \n 'teams.away.team.abbreviation',\n 'teams.home.score',\n 'teams.away.score'\n ]]\n\n\n sched_df['gameDate'] = (pd.to_datetime(sched_df['gameDate'])\n .dt.tz_convert(eastern)\n .dt.strftime('%Y%m%d'))\n sched_df.columns = ['gameDate', 'homeTeam', 'awayTeam', 'homeScore', 'awayScore']\n \n return sched_df\n","repo_name":"maddran/lordstanleyscup","sub_path":"code/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":4318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"13719319395","text":"from datetime import datetime\n\nfrom server.response import Response\n\n\ndef test_to_json() -> None:\n timestamp = datetime.fromisoformat(\"2021-09-27 21:00:00\")\n response = Response(stream=\"default\", content=1, timestamp=timestamp)\n\n assert response.stream == \"default\"\n assert response.content == 1\n assert response.timestamp == timestamp\n","repo_name":"marciorasf/websocket-test","sub_path":"tests/test_response.py","file_name":"test_response.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"14637951772","text":"from django.urls import path,include\nfrom blog import views\n\nurlpatterns = [\n path('hello/',views.hello),\n path('show/',views.show_detail),\n path('show_article/',views.show_article),\n path('show_article2/',views.show_article2),\n path('show_articles/',views.show_articles),\n path('index/',views.index),\n path('detail/',views.detail2),\n path('image/',views.show_image),\n # path('detail2/',views.detail2)\n]","repo_name":"megetzz/django_xcx_t","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"44133140071","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.contrib.auth import login, authenticate\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import render, redirect\n\nfrom recommendations.forms import SignUpForm, UserSurveyForm\n\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\nfrom django.shortcuts import render_to_response, get_object_or_404\n#import models, forms\nfrom .models import UserSurvey\nimport numpy as np\n\n\n\nfrom .models import Restaurant\nfrom recommendations.restaurant.forms import CuisineForm\n\nfrom recommendations.restaurant.nearby import find_nearby\nfrom recommendations.restaurant.rating_algo import find_rating\nfrom recommendations.restaurant.price_algo import find_price\nfrom recommendations.restaurant.user_personalized import find_personalized\nfrom recommendations.restaurant.timing_algo import find_timing\nimport pandas as pd\n\n\ndef signup(request):\n if request.method == 'POST':\n form = SignUpForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n raw_password = form.cleaned_data.get('password1')\n user = authenticate(username=username, password=raw_password)\n login(request, user)\n return redirect('add_survey', user_id=user.id)\n else:\n form = SignUpForm()\n return render(request, 'signup.html', {'form': form})\n\n\ndef add_survey(request, user_id):\n user = get_object_or_404(User, pk=user_id)\n #print(np.array(list(user)))\n form = UserSurveyForm()\n return render(request, 'add_survey.html', {'user': user, 'form': form})\n\ndef explore(request, user_id):\n print(user_id)\n user = get_object_or_404(User, pk=user_id)\n form = UserSurveyForm(request.POST)\n if form.is_valid():\n #user_name = form.cleaned_data['username']\n home_delivery = form.cleaned_data['home_delivery']\n smoking = form.cleaned_data['smoking']\n alcohol = form.cleaned_data['alcohol']\n wifi = form.cleaned_data['wifi']\n valetparking = form.cleaned_data['valetparking']\n rooftop = form.cleaned_data['rooftop']\n usersurvey = UserSurvey()\n #sersurvey = UserSurvey.save(commit=False)\n #usersurvey.user = request.user\n #usersurvey = f.save(commit=False)\n #usersurvey.user = user_id\n #usersurvey.user_name = user_name\n usersurvey.user = user\n usersurvey.home_delivery = home_delivery\n usersurvey.smoking = smoking\n usersurvey.alcohol = alcohol\n usersurvey.wifi = wifi\n usersurvey.valetparking = valetparking\n usersurvey.rooftop = rooftop\n usersurvey.save()\n return render(request, 'explore.html', {'user': user})\n #return HttpResponseRedirect(reverse('lastpage.html', args=(user.id,)))\n #return render(request, 'add_survey.html', {'user': user, 'usersurvey' : usersurvey})\n #return redirect('lastpage', user_id=user.id)\n\n else:\n form = UserSurveyForm()\n return render(request, 'add_survey.html', {'user': user, 'form': form})\n \n\n ##############################################################\n\n # Takes input from user about the cuisine they want to have\ndef input_cuisine(request, algo_type):\n if algo_type == 'timing':\n print(\"####### IN timing\")\n return redirect(reverse('recommendations/timing_list'))\n else:\n print(\"####### NOT IN timing\")\n form = CuisineForm()\n return render(request, 'restaurant/input_cuisine.html', {'form': form, 'algo_type': algo_type})\n\n# Displays list of restaurants to be recommended based on what type of recommedation user wants\ndef recommendation_list(request, algo_type):\n # Get form which was submitted in input_cuisine.html\n form = CuisineForm(request.POST)\n if form.is_valid():\n cuisine = request.POST['cuisine']\n \n # Call find_nearby() function for recommending near by restaurants\n if algo_type == 'nearby':\n nearby_rid = find_nearby()\n # recommend_rid = np.delete(nearby_rid, 883)\n recommend_rid = nearby_rid\n\n \n # First call find_nearby() function to find near by restaurants\n # Second call find_rating() for recommending rating wise recommendation\n if algo_type == 'rating':\n nearby_rid = find_nearby()\n rating_based = find_rating(nearby_rid, cuisine)\n recommend_rid = rating_based\n\n\n if algo_type == 'price':\n nearby_rid = find_nearby()\n price_based = find_price(nearby_rid, cuisine)\n recommend_rid = price_based\n\n\n if algo_type == 'personalized':\n nearby_rid = find_nearby()\n user_personalized_based = find_personalized(nearby_rid, cuisine)\n recommend_rid = user_personalized_based\n\n\n # Above recommend_rid stores id of restaurnts that has to be display\n # Below code gets Restaurant objects for that all ids stored in recommend_rid\n # We store all those Restaurant objects in restaurant_list\n restaurants = Restaurant.objects.filter(id__in=recommend_rid)\n restaurants = dict([(obj.id, obj) for obj in restaurants])\n restaurant_list = [restaurants.get(ids, 0) for ids in recommend_rid]\n restaurant_list = filter(lambda a: a != 0, restaurant_list)\n #print restaurant_list\n\n # Send recommended restaurant list to recommendation_list.html template for displaying\n return render(request, 'restaurant/recommendation_list.html', {'cuisine' : cuisine, 'restaurant_list' : restaurant_list})\n else:\n # if form is not valid render same page\n form = CuisineForm()\n return render(request, 'restaurant/input_cuisine.html', {'form': form})\n\n\ndef timing_list(request):\n nearby_rid = find_nearby()\n timing_based = find_timing(nearby_rid)\n recommend_rid = timing_based\n\n restaurants = Restaurant.objects.filter(id__in=recommend_rid)\n restaurants = dict([(obj.id, obj) for obj in restaurants])\n restaurant_list = [restaurants.get(ids, 0) for ids in recommend_rid]\n restaurant_list = filter(lambda a: a != 0, restaurant_list)\n #print restaurant_list\n\n # Send recommended restaurant list to recommendation_list.html template for displaying\n return render(request, 'restaurant/timing_list.html', {'restaurant_list' : restaurant_list})\n\n\n# when clicks on any restaurant from list it shows detail of that restaurant\ndef restaurant_detail(request, resataurant_id):\n restaurant = get_object_or_404(Restaurant, pk=resataurant_id)\n return render(request, 'restaurant/restaurant_detail.html', {'restaurant': restaurant})\n\n\n\n\n\n ","repo_name":"shr1911/Tourism-Recommendation","sub_path":"Tourism/recommendations/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6746,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"77"}
+{"seq_id":"14493283573","text":"# -*- coding: utf-8 -*-\n# @Author: yirui\n# @Date: 2021-09-01 17:39:28\n# @Last Modified by: yirui\n# @Last Modified time: 2021-09-01 17:40:40\nimport cv2\nimport numpy as np\n\nimport argparse\nimport os\nimport sys\nimport json\nimport time\nimport torch\nimport imageio\nimport scipy.io\nimport torch.utils.data\nfrom vision.ssd.config.fd_config import define_img_size\nfrom core import model as mfn\nfrom core.utils import *\nfrom landmark_detector import Detector as landmark_detector\nfrom mask_predictor import Detector as mask_detector\nfrom config import *\nimport pickle\n\nclass FaceAligner:\n def __init__(self, desiredLeftEye=(0.35, 0.35),\n desiredFaceWidth=256, desiredFaceHeight=None):\n # store the facial landmark predictor, desired output left\n # eye position, and desired output face width + height\n self.desiredLeftEye = desiredLeftEye\n self.desiredFaceWidth = desiredFaceWidth\n self.desiredFaceHeight = desiredFaceHeight\n # if the desired face height is None, set it to be the\n # desired face width (normal behavior)\n if self.desiredFaceHeight is None:\n self.desiredFaceHeight = self.desiredFaceWidth\n\n def align(self, image, landmarks):\n rightEyePts = landmarks[36:42]\n leftEyePts = landmarks[42:48]\n # compute the center of mass for each eye\n leftEyeCenter = leftEyePts.mean(axis=0).astype(\"int\")\n rightEyeCenter = rightEyePts.mean(axis=0).astype(\"int\")\n # compute the angle between the eye centroids\n dY = rightEyeCenter[1] - leftEyeCenter[1]\n dX = rightEyeCenter[0] - leftEyeCenter[0]\n angle = np.degrees(np.arctan2(dY, dX)) - 180\n # compute the desired right eye x-coordinate based on the\n # desired x-coordinate of the left eye\n desiredRightEyeX = 1.0 - self.desiredLeftEye[0]\n # determine the scale of the new resulting image by taking\n # the ratio of the distance between eyes in the *current*\n # image to the ratio of distance between eyes in the\n # *desired* image\n dist = np.sqrt((dX ** 2) + (dY ** 2))\n desiredDist = (desiredRightEyeX - self.desiredLeftEye[0])\n desiredDist *= self.desiredFaceWidth\n scale = desiredDist / dist\n\n # compute center (x, y)-coordinates (i.e., the median point)\n # between the two eyes in the input image\n eyesCenter = ((leftEyeCenter[0] + rightEyeCenter[0]) // 2,\n (leftEyeCenter[1] + rightEyeCenter[1]) // 2)\n # grab the rotation matrix for rotating and scaling the face\n M = cv2.getRotationMatrix2D(eyesCenter, angle, scale)\n # update the translation component of the matrix\n tX = self.desiredFaceWidth * 0.5\n tY = self.desiredFaceHeight * self.desiredLeftEye[1]\n M[0, 2] += (tX - eyesCenter[0])\n M[1, 2] += (tY - eyesCenter[1])\n\n # apply the affine transformation\n (w, h) = (self.desiredFaceWidth, self.desiredFaceHeight)\n output = cv2.warpAffine(image, M, (w, h),\n flags=cv2.INTER_CUBIC)\n # return the aligned face\n return output\n\nif __name__ == '__main__':\n device = torch.device(\"cpu\")\n define_img_size(DETECTION_INPUT_SIZE)\n from vision.ssd.mb_tiny_fd import create_mb_tiny_fd, create_mb_tiny_fd_predictor\n from vision.ssd.mb_tiny_RFB_fd import create_Mb_Tiny_RFB_fd, create_Mb_Tiny_RFB_fd_predictor\n class_names = [name.strip() for name in open(DETECTION_LABEL).readlines()]\n num_classes = len(class_names)\n model_path = DETECTION_FAST_MODEL_PATH\n det_net = create_Mb_Tiny_RFB_fd(len(class_names), is_test=True, device=TEST_DEVICE)\n det_predictor = create_Mb_Tiny_RFB_fd_predictor(det_net, candidate_size=DETECTION_CANDIDATE_SIZE, device=device)\n det_net.load(model_path)\n landmark_predictor = landmark_detector(test_device=device)\n\n fa = FaceAligner(desiredLeftEye=(0.30,0.30), desiredFaceWidth=112)\n\n cap = cv2.VideoCapture(0)\n while True:\n ret, orig_image = cap.read()\n\n if orig_image is None:\n print(\"end\")\n break\n\n image = cv2.cvtColor(orig_image, cv2.COLOR_BGR2RGB)\n image_height, image_width, _ = image.shape\n\n boxes, labels, probs = det_predictor.predict(image, DETECTION_CANDIDATE_SIZE / 2, DETECTION_THRESHOLD)\n\n for i in range(boxes.size(0)):\n box = boxes[i, :]\n # cv2.rectangle(orig_image, pos_tuple((int(box[0]), int(box[1]))), pos_tuple((int(box[2]), int(box[3]))), (255, 255, 255), 2)\n\n landmark, angle = landmark_predictor.detect(orig_image, box.numpy())\n # print(angle)\n t0 = time.time()\n aligned = fa.align(orig_image, landmark)\n print(f\"time used - {time.time() - t0}\")\n cv2.imshow(f'aligned', aligned)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n cap.release()\n cv2.destroyAllWindows()\n","repo_name":"tradle/KYCDeepFace","sub_path":"alignment.py","file_name":"alignment.py","file_ext":"py","file_size_in_byte":4918,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"77"}
+{"seq_id":"23507750568","text":"from cbc_sdk.errors import ApiError\nfrom cbc_sdk.base import (UnrefreshableModel, BaseQuery, CriteriaBuilderSupportMixin,\n IterableQueryMixin, AsyncQueryMixin)\n\nimport logging\nimport json\n\nlog = logging.getLogger(__name__)\n\n_GET_SENSOR_KIT_TRANS_TABLE = {'sensor_url_request': {'filename': 'sensor.json', 'type': 'application/json'},\n 'configParams': {'filename': 'config.ini', 'type': 'text/plain'}}\n_SENSOR_INSTALL_TRANS_TABLE = {'action_type': {},\n 'install_request': {'filename': 'request.json', 'type': 'application/json'},\n 'file': {'filename': 'config.ini', 'type': 'text/plain'}}\n\n\nclass SensorKit(UnrefreshableModel):\n \"\"\"Represents the information about a sensor, including installation file URLs.\"\"\"\n swagger_meta_file = \"workload/models/sensorKit.yaml\"\n\n VALID_DEVICE_TYPES = [\"WINDOWS\", \"LINUX\", \"MAC\"]\n VALID_ARCHITECTURES = [\"32\", \"64\", \"OTHER\"]\n VALID_TYPES = [\"WINDOWS\", \"MAC\", \"RHEL\", \"UBUNTU\", \"SUSE\", \"AMAZON_LINUX\"]\n COMPUTE_RESOURCE_MAP = {'SLES': 'SUSE', 'CENTOS': 'RHEL', 'ORACLE': 'RHEL'}\n\n def __init__(self, cb, initial_data=None):\n \"\"\"\n Initialize the SensorKit object.\n\n Args:\n cb (BaseAPI): Reference to API object used to communicate with the server.\n initial_data (dict): Initial data used to populate the sensor kit data.\n \"\"\"\n super(SensorKit, self).__init__(cb, None, initial_data)\n self._full_init = (initial_data is not None and not initial_data.get('_pseudo', False))\n\n @classmethod\n def from_type(cls, cb, device_type, architecture, sensor_type, version):\n \"\"\"\n Helper method used to create a temporary SensorKit object from its four components.\n\n This method CANNOT be used to create an object that will be persisted to the server.\n\n Args:\n cb (BaseAPI): Reference to API object used to communicate with the server.\n device_type (str): Device type to be used. Valid values are \"WINDOWS\", \"LINUX\", and \"MAC\".\n architecture (str): Architecture to be used. Valid values are \"32\", \"64\", and \"OTHER\".\n sensor_type (str): Sensor type to be used. Valid values are \"WINDOWS\", \"MAC\", \"RHEL\", \"UBUNTU\", \"SUSE\",\n and \"AMAZON_LINUX\".\n version (str): Sensor version number to be used.\n\n Returns:\n SensorType: A SensorType object with those specified values.\n\n Raises:\n ApiError: If an invalid value was used for one of the three limited values.\n \"\"\"\n sensor_type_data = {}\n if device_type is not None:\n if device_type not in SensorKit.VALID_DEVICE_TYPES:\n raise ApiError(\"invalid device_type specified for SensorKit\")\n sensor_type_data['device_type'] = device_type\n if architecture is not None:\n if architecture not in SensorKit.VALID_ARCHITECTURES:\n raise ApiError(\"invalid architecture specified for SensorKit\")\n sensor_type_data['architecture'] = architecture\n if sensor_type is not None:\n if sensor_type not in SensorKit.VALID_TYPES:\n raise ApiError(\"invalid type specified for SensorKit\")\n sensor_type_data['type'] = sensor_type\n if version is not None:\n sensor_type_data['version'] = version\n return SensorKit(cb, {'sensor_type': sensor_type_data, '_pseudo': True})\n\n @classmethod\n def get_config_template(cls, cb):\n \"\"\"\n Retrieve the sample config.ini file with the properties populated from the server.\n\n Args:\n cb (BaseAPI): Reference to API object used to communicate with the server.\n\n Returns:\n str: Text of the sample configuration file.\n \"\"\"\n url = \"/lcm/v1/orgs/{0}/sensor/config_template\".format(cb.credentials.org_key)\n return cb.get_raw_data(url)\n\n @classmethod\n def _query_implementation(cls, cb, **kwargs):\n \"\"\"\n Returns the appropriate query object for this object type.\n\n Args:\n cb (BaseAPI): Reference to API object used to communicate with the server.\n **kwargs (dict): Not used, retained for compatibility.\n\n Returns:\n USBDeviceQuery: The query object for this alert type.\n \"\"\"\n return SensorKitQuery(cls, cb)\n\n\nclass SensorKitQuery(BaseQuery, CriteriaBuilderSupportMixin, IterableQueryMixin, AsyncQueryMixin):\n \"\"\"Query class used to read in SensorKit objects.\"\"\"\n\n def __init__(self, doc_class, cb):\n \"\"\"\n Initialize the SensorKitQuery.\n\n Args:\n doc_class (class): The model class that will be returned by this query.\n cb (BaseAPI): Reference to API object used to communicate with the server.\n \"\"\"\n self._doc_class = doc_class\n self._cb = cb\n self._count_valid = False\n super(BaseQuery, self).__init__()\n self._criteria = {}\n self._expires = None\n self._config_params = None\n self._total_results = 0\n\n def add_sensor_kit_type(self, skit=None, **kwargs):\n \"\"\"\n Add a sensor kit type to the request.\n\n Args:\n skit (SensorKit): The sensor kit type to be added to the request.\n **kwargs (dict): If skit is None, the keyword arguments 'device_type', 'architecture', 'sensor_type',\n and 'version' are used to create the sensor kit type to be added.\n\n Returns:\n SensorKitQuery: Reference to this object.\n \"\"\"\n my_skit = skit\n if my_skit is None:\n my_skit = SensorKit.from_type(self._cb, kwargs.pop('device_type', None), kwargs.pop('architecture', None),\n kwargs.pop('sensor_type', None), kwargs.pop('version', None))\n self._update_criteria('sensor_types', [my_skit.sensor_type])\n return self\n\n def expires(self, expiration_date_time):\n \"\"\"\n Sets the expiration date and time for the sensor kit query request.\n\n Args:\n expiration_date_time (str): The time at which the sensor download link will expire, expressed\n as ISO 8601 UTC.\n\n Returns:\n SensorKitQuery: Reference to this object.\n \"\"\"\n self._expires = expiration_date_time\n return self\n\n def config_params(self, params):\n \"\"\"\n Sets the configuration parameters for the sensor kit query request.\n\n Args:\n params (str): The text of a config.ini file with a list of sensor properties to configure\n on installation.\n\n Returns:\n SensorKitQuery: Reference to this object.\n \"\"\"\n self._config_params = params\n return self\n\n def _submit_query(self):\n \"\"\"\n Submits the current query to the server and returns the list of sensor kits.\n\n Returns:\n list: The list of sensor kits, each one expressed as a dict.\n \"\"\"\n url = \"/lcm/v1/orgs/{0}/sensor/_download\".format(self._cb.credentials.org_key)\n request = {'sensor_types': self._criteria['sensor_types'], 'expires_at': self._expires}\n resp = self._cb.post_multipart(url, _GET_SENSOR_KIT_TRANS_TABLE, sensor_url_request=json.dumps(request),\n configParams=self._config_params)\n result = resp.json()\n return result.get('sensor_infos', [])\n\n def _count(self):\n \"\"\"\n Returns the number of results from the run of this query.\n\n Returns:\n int: The number of results from the run of this query.\n \"\"\"\n if self._count_valid:\n return self._total_results\n\n self._total_results = len(self._submit_query())\n self._count_valid = True\n\n return self._total_results\n\n def _perform_query(self, from_row=0, max_rows=-1):\n \"\"\"\n Performs the query and returns the results of the query in an iterable fashion.\n\n Args:\n from_row (int): Not used; retained for compatibility.\n max_rows (int): Not used; retained for compatibility.\n\n Returns:\n Iterable: The iterated query.\n \"\"\"\n items_list = self._submit_query()\n self._total_results = len(items_list)\n self._count_valid = True\n for item in items_list:\n yield self._doc_class(self._cb, item)\n\n def _run_async_query(self, context):\n \"\"\"\n Executed in the background to run an asynchronous query.\n\n Args:\n context (object): Not used, always None.\n\n Returns:\n list: Result of the async query, which is then returned by the future.\n \"\"\"\n items_list = self._submit_query()\n self._total_results = len(items_list)\n self._count_valid = True\n return [self._doc_class(self._cb, item) for item in items_list]\n\n\ndef _do_sensor_install_request(cb, compute_resources, sensor_kits, config_file):\n \"\"\"\n Internal helper function that performs a sensor installation request.\n\n Not to be called directly by user code; use methods on the ComputeResource object to access this functionality.\n\n Args:\n cb (BaseAPI): Reference to API object used to communicate with the server.\n compute_resources (list): A list of dicts containing the keys 'resource_manager_id' and 'compute_resource_id',\n used to specify the compute resources to install on.\n sensor_kits (list): A list of SensorKit objects used to specify sensor types to choose from in installation.\n config_file (str): The text of a config.ini file with a list of sensor properties to configure on installation.\n\n Returns:\n dict: A dict with two members, 'type' and 'code', indicating the status of the installation.\n \"\"\"\n request = {\n 'compute_resources': compute_resources,\n 'sensor_types': [kit.sensor_type for kit in sensor_kits]\n }\n\n url = \"/lcm/v1/orgs/{0}/workloads/actions\".format(cb.credentials.org_key)\n return_data = cb.post_multipart(url,\n _SENSOR_INSTALL_TRANS_TABLE,\n action_type='INSTALL',\n install_request=json.dumps(request),\n file=config_file)\n return return_data.json()\n","repo_name":"carbonblack/carbon-black-cloud-sdk-python","sub_path":"src/cbc_sdk/workload/sensor_lifecycle.py","file_name":"sensor_lifecycle.py","file_ext":"py","file_size_in_byte":10522,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"77"}
+{"seq_id":"28257558956","text":"import torch\nimport torchvision\nimport torch.nn as nn\n\nclass VGG19(torch.nn.Module):\n def __init__(self, requires_grad=False):\n super().__init__()\n vgg_pretrained_features = torchvision.models.vgg19(pretrained=True).features\n self.slice1 = torch.nn.Sequential()\n self.slice2 = torch.nn.Sequential()\n self.slice3 = torch.nn.Sequential()\n self.slice4 = torch.nn.Sequential()\n self.slice5 = torch.nn.Sequential()\n for x in range(2):\n self.slice1.add_module(str(x), vgg_pretrained_features[x])\n for x in range(2, 7):\n self.slice2.add_module(str(x), vgg_pretrained_features[x])\n for x in range(7, 12):\n self.slice3.add_module(str(x), vgg_pretrained_features[x])\n for x in range(12, 21):\n self.slice4.add_module(str(x), vgg_pretrained_features[x])\n for x in range(21, 30):\n self.slice5.add_module(str(x), vgg_pretrained_features[x])\n if not requires_grad:\n for param in self.parameters():\n param.requires_grad = False\n\n def forward(self, X):\n h_relu1 = self.slice1(X)\n h_relu2 = self.slice2(h_relu1)\n h_relu3 = self.slice3(h_relu2)\n h_relu4 = self.slice4(h_relu3)\n h_relu5 = self.slice5(h_relu4)\n out = [h_relu1, h_relu2, h_relu3, h_relu4, h_relu5]\n return out\n\n\n# Perceptual loss that uses a pretrained VGG network\nclass VGGLoss(nn.Module):\n def __init__(self):\n super(VGGLoss, self).__init__()\n self.vgg = VGG19().cuda()\n self.criterion = nn.L1Loss()\n self.weights = [1.0 / 32, 1.0 / 16, 1.0 / 8, 1.0 / 4, 1.0]\n\n def forward(self, x, y):\n x_vgg, y_vgg = self.vgg(x), self.vgg(y)\n loss = 0\n for i in range(len(x_vgg)):\n loss += self.weights[i] * self.criterion(x_vgg[i], y_vgg[i].detach())\n return loss\n \n# You can append as many input and embedded images as you want \n# and calculate the VGG Loss using the code below\nimport os\nfrom PIL import Image\nimport torchvision.transforms as transforms\n\ninput_images = []\nblended_images = []\nfor im_path in os.listdir('img/input/'):\n im_path = f'img/input/{im_path}'\n print('analyzing: ', im_path)\n inp_img = Image.open(im_path)\n inp_tens = transforms.ToTensor()(inp_img).unsqueeze(0)\n input_images.append(inp_tens[:, :3, :, :])\n\nfor im_path in os.listdir('output__/'):\n img_name = im_path\n im_path = f'output__/{im_path}'\n if not img_name.startswith('vis_mask') and '.' in img_name:\n print('analyzing: ', im_path)\n \n bld_img2 = Image.open(im_path)\n bld_img2 = transforms.ToTensor()(bld_img2).unsqueeze(0)\n blended_images.append(bld_img2)\nreal_imgs = torch.cat(input_images, dim=0)\nbld_imags = torch.cat(blended_images, dim=0)\n\nprint(real_imgs.shape)\nprint(bld_imags.shape)\ndevice='cuda'\nbatch_size = len(real_imgs)\nprint('batch_size', batch_size)\nvgg_l = VGGLoss()\nscore = vgg_l(real_imgs.to(device), bld_imags.to(device))\nprint(score)","repo_name":"abbasmammadov/Artificial-Barber","sub_path":"metrics/VGG.py","file_name":"VGG.py","file_ext":"py","file_size_in_byte":3035,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"10738425598","text":"from setuptools import setup, find_packages\n\nwith open(\"README.md\", \"r\") as file:\n long_description = file.read()\n\nlink = 'https://github.com/xXxCLOTIxXx/ClashOfClans.py/archive/refs/heads/main.zip'\nver = '1.0'\n\nsetup(\n name = \"ClashOfClans.py\",\n version = ver,\n url = \"https://github.com/xXxCLOTIxXx/ClashOfClans.py\",\n download_url = link,\n license = \"MIT\",\n author = \"Xsarz\",\n author_email = \"xsarzy@gmail.com\",\n description = \"Library for creating ClashOfClans bots and scripts.\",\n long_description = long_description,\n long_description_content_type = \"text/markdown\",\n keywords = [\n \"ClashOfClans\",\n \"ClashOfClansApi\",\n \"api\",\n \"ClashOfClans-bot\",\n \"supercell\",\n \"python\",\n \"python3\",\n \"python3.x\",\n \"xsarz\",\n \"official\"\n ],\n install_requires = [\n \"requests\"\n ],\n packages = find_packages()\n)\n","repo_name":"xXxCLOTIxXx/ClashOfClans.py","sub_path":"setup/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"46611627953","text":"from cProfile import label\n# from turtle import down\nimport numpy as __np\nimport pandas\nfrom collections import Counter\nimport matplotlib.pyplot as __plt\nimport mpl_toolkits\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import colors\n\n\nimport sys as __sys\nimport os as __os\n# from sklearn.preprocessing import scale\n\n# from sqlalchemy import false, true\n\n\n\n# __nanNum = list()\n# __datalist = list()\n\n\n# __npydir = \"/home/suchoi/KOMAC/analysis/npy/threshold_each\"\n# __newnpydir = \"/home/suchoi/KOMAC/analysis/npy\"\n# # __plotdir = \"/Users/hipex/KOMAC/result/plot/\"\n# __filelist=__os.listdir(__npydir)\n# __filelist.sort()\n\n\n# totalnpy = __np.load(\"./npy/total_data.npy\")\n# for i in range(0,9):\n# __datalist.append(totalnpy[i])\n\n### ---------------------------------------------------------------------- \n### count val\ndef __CountValue(mynpy,val):\n count=0\n if __np.isnan(val):\n for i in range(0,512):\n for j in range(0,1024):\n if __np.isnan(mynpy[i][j]) :\n count = count + 1\n print('number of \"nan\" : %d'%(count)) \n \n else:\n for i in range(0,512):\n for j in range(0,1024):\n if mynpy[i][j] == val:\n count = count + 1 \n print('number of \"%d\" : %d'%(val,count))\n return count \n\n\n### ----------------------------------------------------------------------\n### opem all numpy\ndef open_all():\n for __np_file in __filelist:\n if __np_file[len(__np_file)-1] =='y':\n print('file %s is open'%(__np_file))\n __data = __np.load(__npydir + '/' + __np_file)\n __datalist.append(__data)\n \n __count = __CountValue(__data,__np.nan)\n __nanNum.append(__count)\n\n### ----------------------------------------------------------------------\n### save total numpy\ndef save_total_numpy():\n total_np_list = []\n \n __npydir = \"./temp\"\n __filelist=__os.listdir(__npydir)\n __filelist.sort()\n __newnpydir = \"/home/suchoi/KOMAC/analysis/npy\"\n\n i=0\n for __np_file in __filelist:\n if __np_file[len(__np_file)-1] =='y':\n __data = __np.load(__npydir + '/' +__np_file)\n total_np_list.append(__data)\n total_np = __np.array(total_np_list)\n filename=\"total_data_rev2.npy\"\n __np.save(\"%s/%s\"%(__newnpydir,filename),total_np)\n\n\n### ---------------------------------------------------------------------- \n### count num of nan on whole maps\ndef __HistNpy(totalnp, targetnpy):\n for i in range(0,512):\n for j in range(0,1024):\n if not(__np.isnan(targetnpy[i][j])):\n totalnp[i][j] = totalnp[i][j] + 1 \n\n### ---------------------------------------------------------------------- \n### Draw all each maps\ndef DrawAllMaps_old():\n i=0\n for data in __datalist: \n __plt.figure(1,figsize=(8,12),facecolor='white')\n if i==0:\n __plt.figure(1).add_subplot(5,2,i+1)\n i=i+2\n else:\n __plt.figure(1).add_subplot(5,2,i)\n i=i+1\n __plt.imshow(data*10,cmap='viridis',interpolation='none',vmin=0.1)\n __plt.clim(0,200)\n __plt.colorbar()\n __plt.xlabel('column')\n __plt.ylabel('row')\n __plt.subplots_adjust(left=0.125, bottom=0.1, right=0.9, top=0.9, wspace=0.2, hspace=0.1)\n\n### ---------------------------------------------------------------------- \n### Draw all each thresholdhisto\ndef DrawAllThrsHisto():\n i=0\n \n __datadir = \"/home/suchoi/KOMAC/data/exp1/data_exp1\"\n __plt.figure(1,figsize=(4,7),facecolor='white')\n for data in __os.listdir(__datadir):\n if data[0] != '.':\n mydir = __datadir + '/' + data + '/thrscan'\n for mydata in __os.listdir(mydir):\n if mydata.endswith(\"threshold.png\"):\n if i==0:\n __plt.figure(1).add_subplot(5,2,i+1)\n i=i+2\n else:\n __plt.figure(1).add_subplot(5,2,i)\n i=i+1\n \n mypic = __plt.imread(mydir+'/'+mydata)\n __plt.axis('off')\n __plt.imshow(mypic)\n \n \n __plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=0., hspace=0.)\n \n### ---------------------------------------------------------------------- \n### Draw all each noisehisto\ndef DrawAllNoiseHisto():\n i=0\n \n __datadir = \"/home/suchoi/KOMAC/data/exp1/data_exp1\"\n __plt.figure(1,figsize=(4,7),facecolor='white')\n for data in __os.listdir(__datadir):\n if data[0] != '.':\n mydir = __datadir + '/' + data + '/thrscan'\n for mydata in __os.listdir(mydir):\n if mydata.endswith(\"noise.png\"):\n if i==0:\n __plt.figure(1).add_subplot(5,2,i+1)\n i=i+2\n else:\n __plt.figure(1).add_subplot(5,2,i)\n i=i+1\n \n mypic = __plt.imread(mydir+'/'+mydata)\n __plt.axis('off')\n __plt.imshow(mypic)\n \n \n __plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=0., hspace=0.)\n\n\n#-------------revision line------------------------------------------\n\n### ---------------------------------------------------------------------- \n### Hisotgram of nulled pixels\ndef NullHisto():\n __plt.figure(3,facecolor='white')\n __plt.title('Histogram of NULL pixels')\n __plt.xlabel('dose(krad)')\n __plt.ylabel('# of null pixels')\n __plt.xlim(-5,50)\n __plt.yscale('log')\n # KOMACdir = \"/Users/hipex/KOMAC/\"\n filename = \"dose.txt\"\n dosefile = open(filename,'r')\n totaldose = 0\n i = 0\n \n for line in dosefile:\n dose = line.split()\n totaldose = totaldose + float(dose[1])\n __plt.plot(totaldose,__nanNum[i],'ob')\n i=i+1\n\n### ---------------------------------------------------------------------- \n### projection to X of thresholds \ndef ThrsProjectionX():\n i=0\n \n for data in __datalist:\n if i==0:\n __plt.figure(8,facecolor='white')\n __plt.title('Threshold Projection to X')\n else:\n __plt.figure(9,figsize=(10,8),facecolor='white')\n __plt.figure(9).add_subplot(4,2,i)\n \n\n __plt.ylim(80,120)\n __plt.xlabel('column')\n __plt.ylabel('threshold')\n\n meanthrs = list()\n for j in range(0,1024):\n meanthrs.append(__np.nanmean(data[:,j])*10)\n __plt.plot(range(0,1024),meanthrs)\n i=i+1\n \n \n### ----------------------------------------------------------------------\n### projection to Y of thresholds \ndef ThrsProjectionY():\n i=0\n for data in __datalist:\n if i==0:\n __plt.figure(10,facecolor='white')\n __plt.title('Threshold Projection to Y')\n\n else:\n __plt.figure(11,figsize=(10,8),facecolor='white')\n __plt.figure(11).add_subplot(4,2,i)\n \n __plt.ylim(80,120)\n __plt.xlabel('row')\n __plt.ylabel('threshold')\n \n meanthrs = list()\n for j in range(0,512):\n meanthrs.append(__np.nanmean(data[j])*10)\n __plt.plot(range(0,512),meanthrs)\n\n i=i+1\n \n### ----------------------------------------------------------------------\n### make firedtime.npy\ndef MakeFiredTime():\n newnpydir = \"/home/suchoi/KOMAC/analysis/npy\"\n __os.system(\"rm %s*npy\"%newnpydir)\n \n totalnp = __np.zeros((512,1024))\n \n i=0\n for data in __datalist:\n __HistNpy(totalnp, data)\n \n __np.save(\"%sHitNum.npy\"%newnpydir,totalnp)\n \ndef ShowPLT():\n # __plt.show()\n # __plt.savefig(\"./temp.png\")\n __plt.savefig(\"./temp.png\",dpi=300)\n\n### ----------------------------------------------------------------------\n### Thrs projection to X\ndef SubThrsProj_X():\n origin_thrs = list()\n \n comp_thrs = list()\n i=0\n for data in __datalist:\n temp_thrs = list()\n if i==0:\n for j in range(0,1024):\n origin_thrs.append(__np.nanmean(data[:,j])*10)\n else:\n for j2 in range(0,1024):\n temp_thrs.append(__np.nanmean(data[:,j2])*10-origin_thrs[j2])\n comp_thrs.append(temp_thrs)\n i=i+1\n print(__np.shape(comp_thrs))\n __plt.figure(12,figsize=(10,8),facecolor='white')\n \n for k in range(1,9):\n __plt.figure(12).add_subplot(4,2,k)\n __plt.plot(range(0,1024),comp_thrs[k-1])\n \n __plt.ylim(-5,20)\n __plt.xlabel('column')\n __plt.ylabel('threshold')\n \n### ----------------------------------------------------------------------\n### Thrs projection to Y\ndef SubThrsProj_Y():\n origin_thrs = list()\n comp_thrs = list()\n i=0\n for data in __datalist:\n temp_thrs = list()\n if i==0:\n for j in range(0,512):\n origin_thrs.append(__np.nanmean(data[j])*10)\n else:\n for j2 in range(0,512):\n temp_thrs.append(__np.nanmean(data[j2])*10-origin_thrs[j2])\n comp_thrs.append(temp_thrs)\n i=i+1\n print(__np.shape(comp_thrs))\n __plt.figure(13,figsize=(10,8),facecolor='white')\n \n for k in range(1,9):\n __plt.figure(13).add_subplot(4,2,k)\n __plt.plot(range(0,512),comp_thrs[k-1])\n \n __plt.ylim(-5,20)\n __plt.xlabel('row')\n __plt.ylabel('threshold')\n \n### ----------------------------------------------------------------------\n### Map subtract\ndef SubMap():\n __plt.figure(14,figsize=(10,8),facecolor='white')\n for i in range(1,9):\n __plt.figure(14).add_subplot(4,2,i)\n resnp = __np.subtract(totalnpy[i],totalnpy[0])\n resnp = resnp*10\n __plt.imshow(resnp,interpolation='none')\n __plt.clim(-30,70)\n __plt.colorbar()\n print(\"%dth maximum is %f\"%(i,__np.nanmax(resnp)))\n print(\"%dth minimum is %f\"%(i,__np.nanmin(resnp)))\n\n### ----------------------------------------------------------------------\n### Origin thrs of each pixels\ndef ThresholdNOM():\n __plt.figure(15,figsize=(10,8),facecolor='white')\n __plt.xlim(-10,210)\n mybin=[]\n for i in range(0,30):\n mybin.append(i*10)\n \n nomnpy = __np.load(\"./npy/HitNum.npy\")\n for i in range(0,10):\n count = []\n for x in range(0,512):\n for y in range(0,1024):\n if nomnpy[x][y] == i :\n if __np.isnan(totalnpy[0][x][y]):\n count.append(0)\n else:\n count.append(totalnpy[0][x][y]*10)\n mycolor = {0:'black',1:'red', 2:'darkorange', 3:'yellow',4:'greenyellow',5:'green',6:'cyan',7:'deepskyblue',8:'blue', 9:'blueviolet'}\n __plt.hist(count,bins=mybin,histtype='step',label='NOM = %d'%i,color=mycolor[i])\n \n __plt.legend()\n __plt.yscale('symlog')\n __plt.xlabel(\"Thresholds of each pixel\")\n __plt.title(\"Threshold and NOM(Number of Measurement)\")\n\n\n\n### ----------------------------------------------------------------------\n### Threshold histogram of each pixels\ndef ThresholdHisto():\n __plt.figure(16,figsize=(10,8),facecolor='white')\n __plt.figure(17,figsize=(10,8),facecolor='white')\n __plt.figure(18,figsize=(10,8),facecolor='white')\n \n __plt.figure(16)\n __plt.xlim(-10,210)\n __plt.figure(17)\n __plt.xlim(-10,210)\n __plt.figure(18)\n __plt.xlim(-10,210)\n\n mybin=[]\n for i in range(0,100):\n mybin.append(i*3)\n\n mycolor = {0:(0,0,0),1:(1,0,0,0.9), 2:(1,0,0,0.6), 3:(1,0,0,0.3),4:(0,0,1,1.0),5:(0,0,1,0.8),6:(0,0,1,0.6),7:(0,0,1,0.4),8:(0,0,1,0.2)}\n\n for i in range(0,9):\n count = []\n for x in range(0,512):\n for y in range(0,1024):\n \n \n if __np.isnan(totalnpy[i][x][y]):\n count.append(0)\n else:\n count.append(totalnpy[i][x][y]*10)\n \n if i==0:\n __plt.figure(16)\n __plt.hist(count,bins=mybin,histtype='step',label='%d'%i,color=mycolor[i])\n __plt.figure(17)\n __plt.hist(count,bins=mybin,histtype='step',label='%d'%i,color=mycolor[i])\n __plt.figure(18)\n __plt.hist(count,bins=mybin,histtype='step',label='%d'%i,color=mycolor[i])\n if i>=1 and i<=3:\n __plt.figure(16)\n __plt.hist(count,bins=mybin,histtype='step',label='%d'%i,color=mycolor[i])\n __plt.figure(17)\n __plt.hist(count,bins=mybin,histtype='step',label='%d'%i,color=mycolor[i])\n if i>=4 and i<=8:\n __plt.figure(16)\n __plt.hist(count,bins=mybin,histtype='step',label='%d'%i,color=mycolor[i])\n __plt.figure(18)\n __plt.hist(count,bins=mybin,histtype='step',label='%d'%i,color=mycolor[i])\n \n __plt.figure(16)\n __plt.legend()\n __plt.yscale('symlog')\n __plt.xlabel(\"Thresholds of each pixel\")\n __plt.title(\"Thresholds Histogram of each Map\")\n \n __plt.figure(17)\n __plt.legend()\n __plt.yscale('symlog')\n __plt.xlabel(\"Thresholds of each pixel\")\n __plt.title(\"Thresholds Histogram of each Map\")\n \n __plt.figure(18)\n __plt.legend()\n __plt.yscale('symlog')\n __plt.xlabel(\"Thresholds of each pixel\")\n __plt.title(\"Thresholds Histogram of each Map\")\n \n### ----------------------------------------------------------------------\n### Subtract threshold Map Histogram\ndef SubThrsDist():\n mybin=[]\n for i in range(0,200):\n mybin.append(-50+i*1)\n \n mycolor = {0:(0,0,0),1:(1,0,0,0.9), 2:(1,0,0,0.6), 3:(1,0,0,0.3),4:(0,0,1,1.0),5:(0,0,1,0.8),6:(0,0,1,0.6),7:(0,0,1,0.4),8:(0,0,1,0.2)}\n __plt.figure(19,figsize=(10,8),facecolor='white')\n __plt.xlim(-70,70)\n \n for i in range(1,9):\n resnp = __np.subtract(totalnpy[i],totalnpy[0])\n resnp = resnp*10\n __plt.hist(__np.ravel(resnp),bins=mybin,histtype='step',label='%d'%i,color=mycolor[i])\n \n __plt.legend()\n __plt.yscale('symlog')\n __plt.xlabel(\"Thresholds Gap\")\n __plt.title(\"Thresholds Subtract with at 0krad of Each Pixel\")\n \n \n### ----------------------------------------------------------------------\n### Check Each thrs-dose plot of pixels\ndef __CheckThrsDose(mythrs):\n IsFirstMax = False\n IsFirstMin = False\n \n nancount = 0\n predata = 0\n IsDecrease = False\n for i in range(0,9):\n if __np.isnan(mythrs[i]):\n nancount = nancount+1\n if i>=1:\n if mythrs[i] < predata:\n IsDecrease = True\n predata=mythrs[i]\n \n if nancount==9:\n return \"f\" # bad pixel\n if (__np.isnan(mythrs[0])) and not(nancount==9) :\n return \"g\" # alive after irradiation \n \n if __np.nanmax(mythrs)==mythrs[0]:\n IsFirstMax = True\n if __np.nanmin(mythrs)==mythrs[0]:\n IsFirstMin = True\n \n \n \n if (not IsFirstMax) and (not IsFirstMin) :\n return \"a\" # typical curve decrease\n if (not IsFirstMax) and IsFirstMin:\n if IsDecrease:\n return \"b\" # typical curve before recover\n else :\n return \"c\" # typical curve without decrease\n if IsFirstMax and (not IsFirstMin):\n return \"d\" # just decrease\n if IsFirstMax and IsFirstMin:\n return \"e\" # all die after irradiation\n \n return \"what\"\n \n### ----------------------------------------------------------------------\n### All Pixel Thrs-dose curve type\ndef AllPixelThresholdDose():\n # __plt.figure(20,figsize=(10,8),facecolor='white')\n # fig = __plt.figure()\n \n KOMACdir = \"/Users/hipex/KOMAC/result/exp1/\"\n filename = \"dose.txt\"\n dosefile = open(KOMACdir+filename,'r')\n totaldose = 0\n \n dose = []\n totaldose = 0\n for line in dosefile:\n mydose = line.split()\n totaldose = totaldose + float(mydose[1])\n dose.append(round(totaldose,2))\n \n ### Draw 3D\n # ax = fig.add_subplot(111, projection='3d')\n # pixelnum = 0\n # for x in range(0,512):\n # for y in range(0,1024):\n # mythrs = []\n # for i in range(0,9):\n # mythrs.append(totalnpy[i][x][y])\n # __plt.plot(dose,__np.ones(9)*pixelnum,mythrs)\n # pixelnum = pixelnum + 1\n # break\n \n \n \n typecount = []\n \n \n for x in range(0,512):\n for y in range(0,1024): \n mythrs = []\n for j in range(0,9):\n mythrs.append(totalnpy[j][x][y])\n typecount.append(__CheckThrsDose(mythrs))\n \n __np.save(\"%s/CurveType.npy\"%(\"/Users/hipex/KOMAC/analysis/npy\"),typecount)\n letter_counts = Counter(list(__np.sort(typecount)))\n df = pandas.DataFrame.from_dict(letter_counts, orient='index')\n df.plot(kind='bar',logy=True, legend=None)\n\n### ----------------------------------------------------------------------\n### Check the tjreshold-dose curve type for die pixels\ndef CheckCurve():\n nomnpy = __np.load(\"./npy/HitNum.npy\")\n Curvenpy = __np.load(\"./npy/CurveType.npy\")\n Curvenpy = Curvenpy.reshape(512,1024)\n\n \n typecount = __np.zeros((10,7))\n\n typedict = {\"a\":0, \"b\":1, \"c\":2, \"d\":3, \"e\":4, \"f\":5, \"g\":6}\n for x in range(0,512):\n for y in range(0,1024):\n x_nom = nomnpy[x][y]\n y_type = typedict[Curvenpy[x][y]]\n typecount[int(x_nom)][int(y_type)] = typecount[int(x_nom)][int(y_type)] + 1\n \n typecount = typecount.astype(int)\n # print(typecount)\n \n __plt.figure(20,figsize=(10,8),facecolor='white')\n for i in range(0,7):\n __plt.plot(typecount.T[:][i], marker='o', label=\"type %d\"%i)\n if i==3 : break\n __plt.legend()\n __plt.xlabel(\"Number of measurement\")\n __plt.title(\"Number of Measuremenst for each type\")\n __plt.yscale('symlog')\n\n __plt.figure(21,figsize=(10,8),facecolor='white')\n cutmatrix = __np.zeros((4,10))\n for x in range(0,4):\n for y in range(0,10):\n cutmatrix[x][y] = typecount[y][x]\n __plt.imshow(cutmatrix, norm=colors.LogNorm(),extent=[0,9,0,3])\n ax=__plt.gca()\n __plt.colorbar()\n \n### ----------------------------------------------------------------------\n### Check the thrs before pixels die\ndef ThrsBeforeDie():\n mybin=[]\n for i in range(0,20):\n mybin.append(i*10)\n \n # __plt.figure(22,figsize=(10,8),facecolor='white')\n # __plt.title(\"Histogram of Threshold before Null Pixel\")\n \n DiePixelThrs=[]\n AllPixelThgrs=[]\n \n for i in range(0,8):\n \n for x in range(0,512):\n for y in range(0,1024):\n if __np.isnan(totalnpy[i+1][x][y]):\n if __np.isnan(totalnpy[i][x][y]):\n DiePixelThrs.append(0)\n else :\n DiePixelThrs.append(totalnpy[i][x][y]*10)\n else:\n if __np.isnan(totalnpy[i][x][y]):\n AllPixelThgrs.append(0)\n else :\n AllPixelThgrs.append(totalnpy[i][x][y]*10)\n \n if not i==8:\n __plt.figure(22).add_subplot(4,2,i+1)\n __plt.hist(AllPixelThgrs,histtype='step',label=\"All pixels\",bins=mybin)\n __plt.hist(DiePixelThrs,histtype='step',label=\"Die pixels\",bins=mybin)\n __plt.yscale('symlog')\n # if i==0:\n # __plt.legend() \n \n \n \n DiePixelThrs=[]\n AllPixelThgrs=[]\n \n \n### ----------------------------------------------------------------------\n### Check the high thrs outside 1 sigma\ndef HighThrs():\n \n \n for i in range(0,9):\n __plt.figure(23,figsize=(10,9),facecolor='white') \n if i==0:\n __plt.figure(23).add_subplot(5,2,1)\n else :\n __plt.figure(23).add_subplot(5,2,i+2)\n # thrsCut = __np.nanmean(totalnpy[i])+__np.nanstd(totalnpy[i])\n mymean = __np.nanmean(totalnpy[i])\n mystd = __np.nanstd(totalnpy[i])\n out_count = []\n up_count = []\n down_count = []\n in_count = []\n for x in range(0,512):\n out_count_row = 0\n up_count_row = 0\n down_count_row = 0\n in_count_row = 0\n for y in range(0,1024):\n mygap = totalnpy[i][x][y]-mymean\n \n if abs(mygap) >= mystd: out_count_row = out_count_row +1\n if mygap >= mystd: up_count_row = up_count_row +1\n if mygap < -1 * mystd: down_count_row = down_count_row + 1\n if abs(mygap) < mystd: in_count_row = in_count_row +1\n out_count.append(out_count_row)\n up_count.append(up_count_row)\n down_count.append(down_count_row)\n in_count.append(in_count_row)\n\n \n sum_out = 0\n sum_up = 0\n sum_down= 0\n sum_in = 0\n new_out_count = []\n new_up_count = []\n new_down_count = []\n new_in_count = []\n xbin = []\n for row_bin in range(0,64):\n count_sum = 0\n for j in range(0,8):\n sum_out = sum_out + out_count[row_bin*8+j]\n sum_up = sum_up + up_count[row_bin*8+j]\n sum_down = sum_down + down_count[row_bin*8+j]\n sum_in = sum_in + in_count[row_bin*8+j]\n for j in range(0,8):\n xbin.append(row_bin*8+j)\n new_out_count.append(sum_out/8)\n new_up_count.append(sum_up/8)\n new_down_count.append(sum_down/8)\n new_in_count.append(sum_in/8)\n sum_out = 0\n sum_up = 0\n sum_down= 0\n sum_in = 0\n __plt.plot(xbin,new_out_count,label=\"outside 1 sigma\")\n __plt.plot(xbin,new_up_count,label=\"higher than 1 sigma\")\n __plt.plot(xbin,new_down_count,label=\"lower than 1 sigma\")\n __plt.plot(xbin,new_in_count,label=\"inside 1 sigma\")\n __plt.legend(fontsize=5,loc='center left') \n # __plt.ylim(100,350)\n # __plt.ylim(50,250)\n # __plt.ylim(000,200)\n # __plt.ylim(300,800)\n __plt.ylim(0,800)\n # __plt.figure(23).add_subplot(5,2,2)\n \n # y=__np.zeros(512)\n \n \n\n # __plt.plot(up_count,label=\"up\")\n # __plt.plot(down_count,label=\"down\")\n \n### ----------------------------------------------------------------------\n### Draw All Thresholds Histo\ndef AllTHrsHisto():\n __plt.figure(24,figsize=(10,8),facecolor='white')\n dvmax=20\n # totalnpy=totalnpy*10\n totalnpy[totalnpy==0]=__np.nan\n for i in range(0,9):\n print('Threshold: %.2f +/- %.2f DAC (based on %d pixels)'%(__np.nanmean(totalnpy[i]),__np.nanstd(totalnpy[i]),__np.sum(~__np.isnan(totalnpy[i]))))\n thresholds_draw = totalnpy[i].ravel()\n mylabel = 'Threshold of data%d: $\\mu=%.2f,\\ \\sigma=%.2f$'%(i,__np.nanmean(totalnpy[i]),__np.nanstd(totalnpy[i]))\n mycolor = {0:'black',1:'red', 2:'darkorange', 3:'yellow',4:'greenyellow',5:'green',6:'cyan',7:'deepskyblue',8:'blue', 9:'blueviolet'}\n n, bins, patches = __plt.hist(thresholds_draw,bins=5*dvmax,range=(0,dvmax), histtype='step', label=mylabel, color=mycolor[i])\n __plt.xlim(0,dvmax)\n # __plt.title('Threshold: $\\mu=%.2f,\\ \\sigma=%.2f$'%(__np.nanmean(totalnpy[i]),__np.nanstd(totalnpy[i])))\n __plt.xlabel('Threshold(DAC)')\n __plt.ylabel('Pixels')\n __plt.legend()\n\n\n### ----------------------------------------------------------------------\n### Read NPY\ndef ReadNPY(inpy):\n __np.set_printoptions(threshold=__sys.maxsize)\n # print(totalnpy[inpy][0][0])\n \n npyfiledir = \"./npy/RawHits\"\n for file in os.listdir():\n __np.load(\"%s/\"%(npyfiledir))\n\n\n### ----------------------------------------------------------------------\n### Count number of NULL\ndef CountNull(somenpy):\n count=0\n for i in range(0,512):\n for j in range(0,1024):\n if __np.isnan(somenpy[i][j]) :\n count = count + 1\n return count\n\n### ----------------------------------------------------------------------\n### Count number of zero\ndef CountZero(somenpy):\n count=0\n for i in range(0,512):\n for j in range(0,1024):\n if somenpy[i][j]==0. :\n count = count + 1\n return count\n\n\n### ----------------------------------------------------------------------\n### Compare number of Null(old, new)\ndef CompareNull():\n totalnpy_old = __np.load(\"./npy/total_data_old.npy\")\n totalnpy_fit = __np.load(\"./npy/total_data_fit.npy\")\n \n __plt.figure(3,facecolor='white')\n __plt.title('Number of NULL pixels')\n __plt.xlabel('dose(krad)')\n __plt.ylabel('# of null pixels')\n __plt.xlim(-5,50)\n __plt.yscale('log')\n filename = \"dose.txt\"\n dosefile = open(filename,'r')\n \n totaldose=0\n i=0\n doseval=[]\n nullval=[]\n nullval_fit=[]\n nullval_old=[]\n for line in dosefile:\n dose = line.split()\n totaldose = totaldose + float(dose[1])\n doseval.append(totaldose)\n nullval.append(CountNull(totalnpy[i]))\n nullval_fit.append(CountNull(totalnpy_fit[i]))\n nullval_old.append(CountNull(totalnpy_old[i]))\n # nullval.append(CountZero(totalnpy[i]))\n # nullval_old.append(CountZero(totalnpy_old[i]))\n # nullval_fit.append(CountZero(totalnpy_fit[i]))\n i=i+1\n\n print(nullval_old)\n __plt.plot(doseval,nullval_old,'or',label=\"Origin\")\n __plt.plot(doseval,nullval_fit,'og',label=\"Fitted\")\n # __plt.plot(doseval,nullval,'ob',label=\"Revision of Origin\")\n __plt.legend()\n\ndef DrawAllMaps(mynpy):\n __plt.figure(1,figsize=(10,8),facecolor='white')\n for idata in range(0,9): \n __plt.figure(1).add_subplot(5,2,idata+1)\n __plt.imshow(mynpy[idata]*10,cmap='viridis',interpolation='none',vmin=0.1)\n __plt.clim(0,200)\n __plt.colorbar()\n __plt.xlabel('column')\n __plt.ylabel('row')\n __plt.subplots_adjust(left=0.125, bottom=0.1, right=0.9, top=0.9, wspace=0.2, hspace=0.25)","repo_name":"nebula-c/KOMAC_Analysis","sub_path":"src/npys.py","file_name":"npys.py","file_ext":"py","file_size_in_byte":26551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"66329300","text":"import numpy as np\n\nJOINT_NAMES = [\n \"pelvis\",\n \"left_hip\",\n \"right_hip\",\n \"spine1\",\n \"left_knee\",\n \"right_knee\",\n \"spine2\",\n \"left_ankle\",\n \"right_ankle\",\n \"spine3\",\n \"left_foot\",\n \"right_foot\",\n \"neck\",\n \"left_collar\",\n \"right_collar\",\n \"head\",\n \"left_shoulder\",\n \"right_shoulder\",\n \"left_elbow\",\n \"right_elbow\",\n \"left_wrist\",\n \"right_wrist\",\n \"jaw\",\n \"left_eye_smplhf\",\n \"right_eye_smplhf\",\n \"left_index1\",\n \"left_index2\",\n \"left_index3\",\n \"left_middle1\",\n \"left_middle2\",\n \"left_middle3\",\n \"left_pinky1\",\n \"left_pinky2\",\n \"left_pinky3\",\n \"left_ring1\",\n \"left_ring2\",\n \"left_ring3\",\n \"left_thumb1\",\n \"left_thumb2\",\n \"left_thumb3\",\n \"right_index1\",\n \"right_index2\",\n \"right_index3\",\n \"right_middle1\",\n \"right_middle2\",\n \"right_middle3\",\n \"right_pinky1\",\n \"right_pinky2\",\n \"right_pinky3\",\n \"right_ring1\",\n \"right_ring2\",\n \"right_ring3\",\n \"right_thumb1\",\n \"right_thumb2\",\n \"right_thumb3\",\n \"nose\",\n \"right_eye\",\n \"left_eye\",\n \"right_ear\",\n \"left_ear\",\n \"left_big_toe\",\n \"left_small_toe\",\n \"left_heel\",\n \"right_big_toe\",\n \"right_small_toe\",\n \"right_heel\",\n \"left_thumb\",\n \"left_index\",\n \"left_middle\",\n \"left_ring\",\n \"left_pinky\",\n \"right_thumb\",\n \"right_index\",\n \"right_middle\",\n \"right_ring\",\n \"right_pinky\",\n \"right_eye_brow1\",\n \"right_eye_brow2\",\n \"right_eye_brow3\",\n \"right_eye_brow4\",\n \"right_eye_brow5\",\n \"left_eye_brow5\",\n \"left_eye_brow4\",\n \"left_eye_brow3\",\n \"left_eye_brow2\",\n \"left_eye_brow1\",\n \"nose1\",\n \"nose2\",\n \"nose3\",\n \"nose4\",\n \"right_nose_2\",\n \"right_nose_1\",\n \"nose_middle\",\n \"left_nose_1\",\n \"left_nose_2\",\n \"right_eye1\",\n \"right_eye2\",\n \"right_eye3\",\n \"right_eye4\",\n \"right_eye5\",\n \"right_eye6\",\n \"left_eye4\",\n \"left_eye3\",\n \"left_eye2\",\n \"left_eye1\",\n \"left_eye6\",\n \"left_eye5\",\n \"right_mouth_1\",\n \"right_mouth_2\",\n \"right_mouth_3\",\n \"mouth_top\",\n \"left_mouth_3\",\n \"left_mouth_2\",\n \"left_mouth_1\",\n \"left_mouth_5\", # 59 in OpenPose output\n \"left_mouth_4\", # 58 in OpenPose output\n \"mouth_bottom\",\n \"right_mouth_4\",\n \"right_mouth_5\",\n \"right_lip_1\",\n \"right_lip_2\",\n \"lip_top\",\n \"left_lip_2\",\n \"left_lip_1\",\n \"left_lip_3\",\n \"lip_bottom\",\n \"right_lip_3\",\n # Face contour\n \"right_contour_1\",\n \"right_contour_2\",\n \"right_contour_3\",\n \"right_contour_4\",\n \"right_contour_5\",\n \"right_contour_6\",\n \"right_contour_7\",\n \"right_contour_8\",\n \"contour_middle\",\n \"left_contour_8\",\n \"left_contour_7\",\n \"left_contour_6\",\n \"left_contour_5\",\n \"left_contour_4\",\n \"left_contour_3\",\n \"left_contour_2\",\n \"left_contour_1\",\n]\n\n\nSMPLH_JOINT_NAMES = [\n \"pelvis\",\n \"left_hip\",\n \"right_hip\",\n \"spine1\",\n \"left_knee\",\n \"right_knee\",\n \"spine2\",\n \"left_ankle\",\n \"right_ankle\",\n \"spine3\",\n \"left_foot\",\n \"right_foot\",\n \"neck\",\n \"left_collar\",\n \"right_collar\",\n \"head\",\n \"left_shoulder\",\n \"right_shoulder\",\n \"left_elbow\",\n \"right_elbow\",\n \"left_wrist\",\n \"right_wrist\",\n \"left_index1\",\n \"left_index2\",\n \"left_index3\",\n \"left_middle1\",\n \"left_middle2\",\n \"left_middle3\",\n \"left_pinky1\",\n \"left_pinky2\",\n \"left_pinky3\",\n \"left_ring1\",\n \"left_ring2\",\n \"left_ring3\",\n \"left_thumb1\",\n \"left_thumb2\",\n \"left_thumb3\",\n \"right_index1\",\n \"right_index2\",\n \"right_index3\",\n \"right_middle1\",\n \"right_middle2\",\n \"right_middle3\",\n \"right_pinky1\",\n \"right_pinky2\",\n \"right_pinky3\",\n \"right_ring1\",\n \"right_ring2\",\n \"right_ring3\",\n \"right_thumb1\",\n \"right_thumb2\",\n \"right_thumb3\",\n \"nose\",\n \"right_eye\",\n \"left_eye\",\n \"right_ear\",\n \"left_ear\",\n \"left_big_toe\",\n \"left_small_toe\",\n \"left_heel\",\n \"right_big_toe\",\n \"right_small_toe\",\n \"right_heel\",\n \"left_thumb\",\n \"left_index\",\n \"left_middle\",\n \"left_ring\",\n \"left_pinky\",\n \"right_thumb\",\n \"right_index\",\n \"right_middle\",\n \"right_ring\",\n \"right_pinky\",\n]\n\nSMPL_JOINT_NAMES = [\n \"pelvis\",\n \"left_hip\",\n \"right_hip\",\n \"spine1\",\n \"left_knee\",\n \"right_knee\",\n \"spine2\",\n \"left_ankle\",\n \"right_ankle\",\n \"spine3\",\n \"left_foot\",\n \"right_foot\",\n \"neck\",\n \"left_collar\",\n \"right_collar\",\n \"head\",\n \"left_shoulder\",\n \"right_shoulder\",\n \"left_elbow\",\n \"right_elbow\",\n \"left_wrist\",\n \"right_wrist\",\n \"left_hand\",\n \"right_hand\",\n]\n\n\nclass Body:\n \"\"\"\n Class for storing a single body pose.\n \"\"\"\n\n def __init__(self, joints, joint_names):\n assert joints.ndim > 1\n assert joints.shape[0] == len(joint_names)\n self.joints = {}\n for i, j in enumerate(joint_names):\n self.joints[j] = joints[i]\n\n @staticmethod\n def from_smpl(joints):\n \"\"\"\n Create a Body object from SMPL joints.\n \"\"\"\n return Body(joints, SMPL_JOINT_NAMES)\n\n @staticmethod\n def from_smplh(joints):\n \"\"\"\n Create a Body object from SMPLH joints.\n \"\"\"\n return Body(joints, SMPLH_JOINT_NAMES)\n\n def _as(self, joint_names):\n \"\"\"\n Return a Body object with the specified joint names.\n \"\"\"\n joint_list = []\n for j in joint_names:\n if j not in self.joints:\n joint_list.append(np.zeros_like(self.joints[\"spine1\"]))\n else:\n joint_list.append(self.joints[j])\n return np.stack(joint_list, axis=0)\n\n def as_smpl(self):\n \"\"\"\n Convert the body to SMPL joints.\n \"\"\"\n return self._as(SMPL_JOINT_NAMES)\n\n def as_smplh(self):\n \"\"\"\n Convert the body to SMPLH joints.\n \"\"\"\n return self._as(SMPLH_JOINT_NAMES)\n","repo_name":"vchoutas/smplx","sub_path":"smplx/joint_names.py","file_name":"joint_names.py","file_ext":"py","file_size_in_byte":5963,"program_lang":"python","lang":"en","doc_type":"code","stars":1407,"dataset":"github-code","pt":"77"}
+{"seq_id":"7525489596","text":"import sys\nfrom UnbinnedAnalysis import *\nfrom UpperLimits import UpperLimits\n\nfilename, par_srcname, par_irfs = sys.argv[1: 4]\npar_emin = float(sys.argv[4])\npar_emax = float(sys.argv[5])\nfile_eventFile, file_scFile, file_expMap, file_expCube, file_srcModel = sys.argv[6: 11]\n\n\nobs = UnbinnedObs(eventFile=file_eventFile, scFile=file_scFile,\n expMap=file_expMap, expCube=file_expCube, irfs=par_irfs)\nlike = UnbinnedAnalysis(obs, srcModel=file_srcModel, optimizer='NewMinuit')\n\nlike.fit(verbosity=0, covar=True)\nlike.Ts(par_srcname)\n\nul = UpperLimits(like)\n\nul[par_srcname].compute(emin=par_emin, emax=par_emax)\nf = open(filename, 'w')\nprint >> f, ul[par_srcname].results\nf.close()\n","repo_name":"lx9507/DampeSS2014forBeginners","sub_path":"lc/ul.py","file_name":"ul.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"4862561709","text":"import json\nfrom django.db.models import Sum\nfrom rest_framework.generics import RetrieveAPIView, UpdateAPIView\nfrom rest_framework import status\nfrom rest_framework.response import Response\n\nfrom api.models import Demande, Detaildemande, Modele, Tournee, Typedechet, Ville\n# Create your views here.\n\nclass WasteList(RetrieveAPIView):\n \n def get(self, request):\n data = dict(request.GET)\n demandes = Demande.objects.filter(datedemande__range = [data['datedemande'][0], data['dateenlevement'][0]])\n listeDemande = []\n for demande in demandes:\n listeDemande.append(Detaildemande.objects.filter(nodemande=demande.nodemande,noville=Ville.objects.get(noville=data['ville'][0]), notypedechet=Typedechet.objects.get(notypedechet=data['notypedechet'][0])).aggregate(Sum('quantiteenlevee')))\n somme = 0\n for data in listeDemande:\n if(data['quantiteenlevee__sum']):\n somme += data['quantiteenlevee__sum']\n return Response(data=somme,status=status.HTTP_200_OK)\n\nclass WasteNational(RetrieveAPIView):\n def get(self,request):\n data = dict(request.GET)\n demandes = Demande.objects.filter(datedemande__range = [data['datedemande'][0], data['dateenlevement'][0]])\n listeDemande = []\n for demande in demandes:\n listeDemande.append(Detaildemande.objects.filter(nodemande=demande.nodemande, notypedechet=Typedechet.objects.get(notypedechet=data['notypedechet'][0])).aggregate(Sum('quantiteenlevee')))\n\n somme = 0\n for data in listeDemande:\n if(data['quantiteenlevee__sum']):\n somme += data['quantiteenlevee__sum']\n\n return Response(data=somme,status=status.HTTP_200_OK)\n \n\nclass MakeDemandInTrip(UpdateAPIView):\n def put(self, request):\n data = json.loads(request.body) \n demands_to_make_in_trip = Demande.objects.filter(notournee=None)\n demands = []\n for item in demands_to_make_in_trip:\n demands.append(item.nodemande)\n count = len(Tournee.objects.filter(noimmatric=Tournee.objects.get(pk=data['tournee']).noimmatric))\n modele = Modele.objects.filter(camion=Tournee.objects.get(pk=data['tournee']).noimmatric).first()\n if count > modele.maxenlevement:\n return Response(data={\"message\":\"Le tournee ne peux pas accepter plus de demande: le camion ne peut plus assurer d'enlevement de plus\", \"journal\":json.dumps(demands)},status=status.HTTP_400_BAD_REQUEST)\n for demand in demands_to_make_in_trip:\n d = Demande.objects.get(pk=demand.nodemande)\n d.notournee = Tournee.objects.get(pk=data[\"tournee\"])\n d.save()\n return Response(status=status.HTTP_200_OK)\n","repo_name":"Silvdans/MSPR3-API","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"25810780737","text":"# Challenge 11:\n\n# In this challenge, you are to demonstrate asyncio's ability to execute I/O-bound tasks more efficiently through concurrency.\n\n# Write a program that fetches several URLs, using aiohttp to make the requests concurrently. However, you should limit the number of requests that are made at the same time, so you don't exhaust resources or get blocked by the server. You can use the asyncio.Semaphore for this purpose.\n\n# Your main coroutine should create an aiohttp.ClientSession, and use it to fetch the URLs. Each URL fetch will be a coroutine that waits for a semaphore before making the request.\n\n# You can use any URLs you like for this challenge, but make sure they're suitable for large-scale testing (i.e., not small sites that could be disrupted, or sites that may block you for making too many requests).\n\n# Use the provided fetch_url coroutine to implement your solution.\nimport asyncio\n\nimport aiohttp\n\n\nURLS = [\n \"https://chat.openai.com/\",\n \"https://app.coderpad.io/\",\n \"https://drive.google.com/\",\n \"https://music.youtube.com/\",\n \"https://mail.google.com/\",\n]\n\n\nasync def fetch_url(url: str, semaphore: asyncio.Semaphore):\n async with semaphore:\n async with aiohttp.ClientSession() as session:\n async with session.get(url) as response:\n text = await response.text()\n print(f\"Got {url}: {text[:20]}\")\n await asyncio.sleep(3)\n return text\n\nasync def main(max_in_flight):\n semaphore = asyncio.Semaphore(max_in_flight)\n await asyncio.gather(*(fetch_url(url, semaphore) for url in URLS))\n\nasyncio.run(main(max_in_flight=3))\n","repo_name":"dandavison/misc-python","sub_path":"gpt_asyncio_challenge_11.py","file_name":"gpt_asyncio_challenge_11.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"40989514498","text":"import PyPDF2 \n\ndef pdf_reader():\n\tfile = open('example.pdf','rb')\n\tpdfReader = PyPDF2.PdfFileReader(file) \n\t \n\tpages = pdfReader.numPages\n\tprint('Page count is:',pages)\n\n\t#loop for multiple page pdf\n\tfor i in range(pdfReader.getNumPages()):\n\t\tpageObj = pdfReader.getPage(i)\n\n\t\tprint(\"Page №\", pdfReader.getPageNumber(pageObj) + 1)\n\t\tprint(pageObj.extractText()) #type str\n\npdf_reader()","repo_name":"takhmina0907/ExamTest","sub_path":"task2/read_from_pdf.py","file_name":"read_from_pdf.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"28893133257","text":"import os\nimport sys\nimport glob\nfrom optparse import OptionParser\nfrom collections import defaultdict\n\nfrom ..models import load_model\nfrom ..util import file_handling as fh\n\ndef main():\n usage = \"%prog model_dir \"\n parser = OptionParser(usage=usage)\n parser.add_option('-n', dest='n_terms', default=10,\n help='Number of terms to display: default=%default')\n #parser.add_option('--model_type', dest='model_type', default=None,\n # help='Model type [LR|MLP|ensemble]; None=auto-detect: default=%default')\n #parser.add_option('--values', action=\"store_true\", dest=\"values\", default=False,\n # help='Print values: default=%default')\n\n (options, args) = parser.parse_args()\n model_dir = args[0]\n\n n_terms = int(options.n_terms)\n\n top_features = get_top_features(model_dir, n_terms)\n for feature, weight in top_features:\n print('%s\\t%0.4f' % (feature, weight))\n\n\ndef get_top_features(model_dir, n_terms, default_model_type=None):\n\n basename = os.path.split(model_dir)[-1]\n model_files = glob.glob(os.path.join(model_dir, basename + '*_metadata.json'))\n\n if len(model_files) == 0:\n sys.exit(\"No model files found in %s\" % os.path.join(model_dir))\n\n totals = defaultdict(float)\n\n for file_i, file in enumerate(model_files):\n print(\"Loading %s\" % file)\n model_name = os.path.split(file)[-1][:-14]\n print(model_name)\n model = load_model.load_model(model_dir, model_name, default_model_type)\n model_type = model.get_model_type()\n print(\"Found: \", model_type)\n\n if model_type == 'LR':\n classes = model.get_active_classes()\n if len(classes) == 2:\n coefs = model.get_coefs(target_class=0)\n for coef, value in coefs:\n totals[coef] += value\n\n coef_totals = [(coef, value) for coef, value in totals.items()]\n coef_totals = sorted(coef_totals, key=lambda x: x[1])\n coef_totals.reverse()\n\n return coef_totals[:n_terms]\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"dallascard/textile","sub_path":"core/models/get_top_features.py","file_name":"get_top_features.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"70562038650","text":"import imutils\nimport time\nimport json\nfrom threading import Thread\nfrom imutils.video import VideoStream\nfrom pyzbar.pyzbar import ZBarSymbol\nfrom pyzbar import pyzbar\nfrom cv2 import cv2\nfrom kolonial import Kolonial\n\nUSERNAME = 'your@email'\nPASSWORD = 'yourPassword'\nUSER_AGENT = 'yourUserAgent'\nTOKEN = 'yourToken'\n\napi = Kolonial(USERNAME, PASSWORD, USER_AGENT, TOKEN)\n\ndef set_reset():\n\t# Prevent multiple rapid scans of the product\n\twhile True:\n\t\tif len(detected):\n\t\t\ttime.sleep(2)\n\t\t\tdetected.clear()\n\t\t\ntimer = Thread(target=set_reset)\ntimer.daemon = True\ndetected = set()\nDEBUG = False # Prints detected barcodes if True\n\nprint('Starting video stream...')\nvs = VideoStream(usePiCamera=True).start()\ntime.sleep(2)\nprint('Video stream started')\n\ntimer.start()\n\nwhile True:\n\tframe = vs.read()\n\tframe = imutils.resize(frame, width=480)\n\tbarcodes = pyzbar.decode(frame, symbols=[ZBarSymbol.EAN13])\n\n\tfor barcode in barcodes:\n\t\t(x, y, w, h) = barcode.rect\n\t\tcv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)\n\t\tbarcodeData = barcode.data.decode(\"utf-8\")\n\t\tbarcodeType = barcode.type\n\t\ttext = \"{} ({})\".format(barcodeData, barcodeType)\n\t\tcv2.putText(frame, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,\n\t\t\t0.5, (0, 0, 255), 2)\n\n\t\tif DEBUG:\n\t\t\tprint('Barcode detected: {}'.format(barcodeData))\n\n\t\tif barcodeData not in detected:\n\t\t\t# Search Kolonial for barcode\n\t\t\tsearch = api.search(barcodeData)\n\t\t\tprint('\\n----------------------------------------')\n\n\t\t\tif len(search['products']) != 0:\n\t\t\t\tproduct_id = search['products'][0]['id']\n\t\t\t\tproduct_name = search['products'][0]['full_name']\n\t\t\t\tprint('Found product: ' + product_name)\n\t\t\t\t\n\t\t\t\t# Cart item\n\t\t\t\titem = {\"items\": [{'product_id' : product_id, 'quantity' : '1'}]}\n\n\t\t\t\t# Add item to cart\n\t\t\t\tpost_cart = api.modify_cart(json.dumps(item))\n\t\t\t\tprint('DING! Product added to cart :D')\n\t\t\t\tprint('----------------------------------------\\n')\n\t\t\telse:\n\t\t\t\tprint('Product not found @ Kolonial.no')\n\t\t\t\tprint('----------------------------------------\\n')\n\t\t\t\n\t\t\tdetected.add(barcodeData)\n\n # Show the video frame\n\tcv2.imshow('Barcode Scanner', frame)\n\tkey = cv2.waitKey(1) & 0xFF\n\t\n\tif key == ord('q'):\n\t\tbreak\n\ncv2.destroyAllWindows()\nvs.stop()\n","repo_name":"frefrik/rpi-kolonial-barcode-scanner","sub_path":"scanner.py","file_name":"scanner.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"30257218808","text":"import os\nimport csv\nimport json\nimport requests\nimport boto3\n\n\ndef getHolidayCsv():\n '''祝日 csv データ内閣府より取得する\n '''\n try:\n res = requests.get('http://www8.cao.go.jp/chosei/shukujitsu/syukujitsu_kyujitsu.csv', timeout=3)\n res.raise_for_status()\n except requests.exceptions.HTTPError as err:\n print(err)\n sys.exit(1)\n\n return res.content\n\n\ndef decodeContent(content):\n '''取得した csv データをデコードする\n '''\n decoded_content = content.decode('shift_jis')\n return decoded_content\n\n\ndef convertDict(decoded_content):\n '''デコードした csv データを辞書型に変更する\n '''\n reader = csv.reader(decoded_content.splitlines(), delimiter=',')\n header = next(reader)\n data = {}\n for line in reader:\n if line[1] == '休日':\n line[1] = '振替休日'\n data[line[0]] = line[1]\n\n sorted_data = {}\n for k, v in sorted(data.items(), key=lambda x: x[0]):\n sorted_data[k] = v\n\n return sorted_data\n\n \ndef getYears(contents):\n '''辞書データから祝日・休日の「年」だけを取り出す\n '''\n years = []\n for k in contents.keys():\n years.append(k.split('-')[0])\n return list(set(years))\n\n\ndef putObject(contents, key):\n '''生成した JSON データを S3 バケットに put する\n '''\n session = boto3.session.Session()\n if os.getenv('ENVIRONMENT') == 'debug':\n s3 = session.client(service_name='s3', endpoint_url='http://127.0.0.1:5001/')\n else:\n s3 = session.client(service_name='s3')\n\n s3.put_object(ACL='private',\n Body=contents,\n Bucket=os.getenv('BUCKET_NAME'),\n Key=key)\n\n\ndef saveYearsData(contents):\n '''年ごとの祝日・休日データを JSON データを保存する\n '''\n years = getYears(contents)\n\n for year in years:\n data = {}\n for k, v in contents.items():\n if year in k:\n data[k] = v\n\n putObject(json.dumps(data, ensure_ascii=False), '%s/data.json' % year)\n\n\ndef saveAllData(contents):\n '''全ての年の祝日・休日データを保存する\n '''\n # 全体のデータを保存\n putObject(json.dumps(contents, ensure_ascii=False), 'data.json')\n\n\ndef main():\n '''main\n '''\n res = getHolidayCsv()\n decoded_content = decodeContent(res)\n contents = convertDict(decoded_content)\n saveYearsData(contents)\n saveAllData(contents)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"inokappa/holidays.py","sub_path":"holidays.py","file_name":"holidays.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"37068099820","text":"#%% \nimport numpy as np\nimport csv\nimport os\nimport decimal\nimport matplotlib.pyplot as plt\nfrom matplotlib import pyplot as mp\nimport pandas as pd\nimport math\nimport scipy\nfrom scipy.optimize import curve_fit\nfrom math import pi,sin\nfrom heapq import nsmallest\n\n\ndef fwhm(y_values_q, x_values):\n y_values, q_l, q_r,q,inten = [], [], [],[],[]\n\n # To make 'y_values_temp', a numpy array, into a python list\n for x in range(0,len(y_values_q)):\n y_values.append(y_values_q[x])\n peak_height = max(y_values)\n print(peak_height)\n half_peak_height = max(y_values)/2\n print(half_peak_height)\n # Splitting the y_values data into before and after x_value at peak height\n y_l_q = y_values[0:y_values.index(peak_height)]\n #print(y_l_temp)\n y_r_q = y_values[y_values.index(peak_height):len(y_values)]\n #print(y_r_temp)\n # Finds 1st closest value to half_peak_height in y_l and y_r\n y_l = nsmallest(1, y_l_q, key=lambda x: abs(x-half_peak_height))\n print (y_l)\n y_r = nsmallest(1, y_r_q, key=lambda x: abs(x-half_peak_height))\n print (y_r)\n inten.append(y_l)\n inten.append(y_r)\n #print(inten)\n # Gets x_value pairs for y_l and y_r\n q_l.append(x_values[y_values.index(y_l)])#[0]\n q_r.append(x_values[y_values.index(y_r)])#[0]+ len(y_l) -1\n fwhm_n = ((abs(q_l[0] - q_r[0])))\n q.append(q_l)\n q.append(q_r)\n #print (temp_l[0])\n print(q_l)\n print(q_r)\n #print ( fwhm_n)\n plt.plot(q,inten)\n return(float(fwhm_n))\n#%%\n#Defining all functions that will be used in program\ndef readcsv(filename):\n data = pd.read_csv(filename)\n return(np.array(data))\n\ndef find_nearest(array, value):\n array = np.asarray(array)\n idx = (np.abs(array - value)).argmin()\n return array[idx]\n\ndef find_index(array, value):\n #array is a 1D vector of two_theta or q values\n #value is the specific angle or q for which you want the index\n array = np.asarray(array)\n idx = (np.abs(array - value)).argmin()\n return idx\n \ndef back_subtract(x, data, length):\n #x is a 1D array of two theta or q values\n #data is an array of x-ray intensities\n #length is the number of values on the edges of the data you want to use to create a linear background \n x_linear = np.hstack((x[0:length], x[-length:-1])) #I'm taking the starting and ending values\n data_linear = np.hstack((data[0:length], data[-length:-1])) #We'll use these to fit a straight line\n slope, intercept = np.polyfit(x_linear, data_linear, 1) #Do linear fit\n back = slope*x+intercept \n data_correct=(data-back)\n return data_correct\n\n \n#%%\nperov = readcsv('/Users/rbelisle/Desktop/SSRL_Data_113/Xraydeg/B1_MAPbI2Br_xraydeg/b1_deg.csv') #openfile of interest\nplt.plot(perov[:,0],perov[:,1]) #plot inititial data\nplt.title('Initial:')\nplt.xlabel('2-theta')\nplt.ylabel('Intensity')\nplt.show()\n\n# %%\n# Convert two theta to Q and set data limits\n#should turn this into a function that accepts an array and limits\nwave = 0.982381 # wavelength from GSAS-II\nq =[4*math.pi*math.sin(math.pi/180*row/2)/wave for row in perov[:,0]]\n#plt.plot(q,y, marker='.',color='blue')\nplt.title('Initial:')\nplt.xlabel('Q')\nplt.ylabel('Intensity')\nq_1 = 1.94\nq_2 = 2.18\nlimit1 = q.index(find_nearest(q, q_1))\nlimit2 = q.index(find_nearest(q, q_2))\nq_sub = q[limit1:limit2]\n\n\n#%%\n#remove background\nsize = perov_sub.shape\nq_bins = size[0]\nnum_frames = size[1]\nperov_fit = perov_sub\nfor file in range(num_frames): \n perov_fit[:,file] = back_subtract(np.array(q_sub),perov_sub[:,file],10) #remove background from that file\nplt.plot(q_sub,perov_sub[:,0]) # plot to ensure it worked\n\n# %%\n\ny_values = perov_sub[:,0]\nx_values = np.array(q_sub)\n#for x in range(0,len(y_values_temp)):\n# y_values.append(y_values_temp[x]) I don't think you need to do this, since you already have an arrat of y-values\npeak_height = max(y_values)\nprint(peak_height)\n\n \nhalf_peak_height = max(y_values)/2\nprint(half_peak_height)\n# Splitting the y_values data into before and after x_value at peak height\ny_l_temp = y_values[0:find_index(y_values, peak_height)]\nprint(y_l_temp)\ny_r_temp = y_values[find_index(y_values, peak_height):] #adjusted so it works with nparray, see new find index function\nprint(y_r_temp)\n\n\n# Finds 1st closest value to half_peak_height in y_l and y_r\ny_l = find_nearest(y_l_temp,half_peak_height) #can use find nearest again here\nprint (y_l)\n\ny_r = find_nearest(y_r_temp,half_peak_height) #can use find nearest again here\nprint (y_r)\n\n# I think find index will work here\ntemp_l = find_index(y_l_temp,y_l)\ntemp_r = find_index(y_r_temp, y_r)\nfwhm = abs(q_sub[temp_r]-q_sub[temp_l])\nprint(temp_l)\nprint(temp_r)\nprint('FWHM', fwhm)\n# %% Perhaps a cleaner way to do this is pull the FWHM from the pseudo voight fit\ndef normal_gaussian(x, a, b, c): \n #nomralized gaussian curve for XRD analysis:\n #x is a 1D array of two theta or q values\n #a is the instensity \n #b is the peak position and \n #c is the variance (FWHM = sqrt(2ln2)*c)\n return a/(c*np.sqrt(2*math.pi))*np.exp(-(x - b)**2/(2*c**2))\n\ndef lorentz(x, a, b, c):\n #generic lorentzian curve, for xrd analysis\n #x is a 1D array of two theta or q values\n #a is the max intensity of the peak and representative of crystalling\n #b is the peak position and \n # c is the FWHM\n return a/np.pi*((c/2)/((x-b)**2+(c/2)**2))\n\ndef pvoigt(x, e, a, b, c):\n #pseudovoigt curve common in xrd analysis\n #linear combination of lorentzian and gaussian curves\n #e is the fraction that is lorentzian\n # a is the intensity\n # b is the centroid\n # c is the FWHM\n c_g = c/(2*np.sqrt(2*np.log(2)))\n return e*lorentz(x, a, b, c) + (1-e)*normal_gaussian(x,a,b,c_g)\n\np0 = [0.2, 300, 2, .01] #best guess for initial values in format [a1, b1, c1, a2, c2, a3, b3, c3]\nupper_limit = [1, 3000, q_2, 5]\nlower_limit = [0, 0, q_1, 0]\npopt,pcov = curve_fit(pvoigt, q_sub, perov_fit[:,0], p0, bounds=(lower_limit, upper_limit), maxfev=6000)\nplt.plot(q_sub,perov_fit[:,0],'b-', label='Data') #plot subfield of data\nplt.plot(q_sub,pvoigt(q_sub, *popt),'c--', label='Model') #plot best fit\n\n# %%\n","repo_name":"Wellesley-Solar/XRD_Tools","sub_path":"Python Programs/XRD Analysis/FWHM.py","file_name":"FWHM.py","file_ext":"py","file_size_in_byte":6131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"11030664388","text":"from django.urls import include, path\nfrom rest_framework import routers\n\nfrom .views import AuthorViewSet, BookViewSet\nfrom .views import getAllAuthors,getBookByNameLike,addAuthor,addBook,deleteAuthor,deleteBook,updateAuthor,updateBook,getAllBooks\n\nrouter=routers.DefaultRouter()\n#if \"r\" or \"R\" prefix is present escape sequences (like \\n, \\a,\\t,\",',\\,...)\n#are not interpreted and they'll be shown as they are written\nrouter.register(r'author',AuthorViewSet)\nrouter.register(r'book',BookViewSet)\n\n\n\n\nurlpatterns = [\n path('',include(router.urls)),\n path(r'authors/all/',getAllAuthors,name='allAuthor'),\n path(r'authors/add/',addAuthor,name=\"addAuthor\"),\n path(r'authors/delete/',deleteAuthor,name=\"deleteAuthor\"),\n path(r'authors/update/',updateAuthor,name=\"updateAuthor\"),\n path(r'books/add/',addBook,name=\"addBook\"),\n path(r'books/all/',getAllBooks,name='allBooks'),\n path(r'books/delete/',deleteBook,name='deleteBook'),\n path(r'books/update/',updateBook,name='updateBook'),\n path(r'books/title-like/',getBookByNameLike,name='bookTitleLike')\n]\n","repo_name":"ChaoukiBayoudhi/library_rest_api_in_django","sub_path":"library_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"32974366294","text":"# coding=utf8\n\nimport unittest\nfrom main import replace_by_str_function, replace_by_re\n\nclass SimpleTest(unittest.TestCase):\n\n def test_replace_by_str_function(self):\n self.assertEqual(\n replace_by_str_function(\n 'test 12 case 1234 http://www.example.com 123 https://www.example.com m.a.gomza@yandex.ru'\n ),\n 'Test 12 case [Ссылка запрещена] 123 [Ссылка запрещена] [Контакты запрещены]'\n )\n\n def test_replace_by_re(self):\n self.assertEqual(\n replace_by_re(\n 'test 12 case 1234 http://www.example.com 123 https://www.example.com m.a.gomza@yandex.ru'\n ),\n 'Test 12 case [Ссылка запрещена] 123 [Ссылка запрещена] [Контакты запрещены]'\n )\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"magakoos/fogstream_python_course_homeworks","sub_path":"homeworks/03__02__replace_href_and_email/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"30232029717","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.linspace(-np.pi, np.pi, 200)\ncosy = np.cos(x) / 2\nsiny = np.sin(x)\n\nplt.plot(x, cosy, linestyle=\"-\", linewidth=1, color=\"red\")\nplt.plot(x, siny, linestyle=\":\", linewidth=2.5, color=\"green\")\n\nplt.show()","repo_name":"nanshannan1/matplotlib-numpy-pandas","sub_path":"改变线条的形状.py","file_name":"改变线条的形状.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"15209385711","text":"import pandas as pd\n\n\nif __name__ == '__main__':\n path = \"D:/\"\n print('ok')\n meta_df = pd.read_csv(path + '/data/meta_data.csv')\n holding_df = pd.read_csv(path + '/data/holding_data.csv')\n\n meta_df = meta_df.head(100)\n meta_df = meta_df.set_index('symbol')\n holding_df = holding_df.set_index('symbol')\n\n meta_df.to_csv(path + '/data/test.csv')\n holding_df = holding_df.join(meta_df, how='inner',\n lsuffix='_l', rsuffix='_r')\n\n holding_df.to_csv(path + '/data/join_data.csv')\n stock_df = holding_df.groupby('stock_name')['weight'].sum()\n stock_df = stock_df.sort_values(axis=0, ascending=False)\n stock_df.to_csv(path + '/data/stock_rank_data.csv')\n\n segment_df = holding_df.groupby('segment_name')['weight'].sum()\n segment_df = segment_df.sort_values(axis=0, ascending=False)\n segment_df.to_csv(path + '/data/segment_rank_data.csv')\n","repo_name":"philolee/astar","sub_path":"data_analyser.py","file_name":"data_analyser.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"23801533541","text":"import numpy as np\n\nfrom scipy.optimize import fmin_bfgs\nfrom scipy.misc import logsumexp\n\n\nclass LogisticRegression:\n def __init__(self, noutcomes, npredictors, penalty=0.0):\n self.noutcomes = noutcomes\n self.npredictors = npredictors\n self.penalty = penalty\n self._init_params()\n\n def _init_params(self):\n k, p = self.noutcomes, self.npredictors\n self.weights = np.random.normal(size=(k - 1, p))\n\n def fit(self, X, y):\n p = self.npredictors\n f = lambda w: -logistic_loglik(w.reshape((-1, p)), X, y) + self.penalty * w.dot(w)\n g = lambda w: -logistic_loglik_grad(w.reshape((-1, p)), X, y).ravel() + 2 * self.penalty * w.sum()\n\n solution = fmin_bfgs(f, self.weights.ravel().copy(), g, disp=False)\n self.weights = solution.reshape((-1, p))\n\n return self\n\n def predict_prob(self, X):\n prob = np.zeros((X.shape[0], self.noutcomes))\n\n for i, x_i in enumerate(X):\n prob[i] = logistic_predict_prob(self.weights, x_i)\n\n return prob\n \n def predict_outcome(self, X):\n prob = self.predict_prob(X)\n yhat = np.argmax(prob, axis=1)\n return yhat\n\n\ndef onehot_encode(x, k):\n n = x.size\n X = np.zeros((n, k))\n\n for i, j in enumerate(x):\n X[i, j] = 1\n\n return X\n\n\ndef logistic_predict_prob(W, x):\n k = W.shape[0] + 1\n\n lp = np.zeros(k)\n lp[:-1] = W.dot(x.ravel())\n p = np.exp(lp - logsumexp(lp))\n \n return p\n\n\ndef logistic_loglik(W, X, y):\n k = W.shape[0] + 1\n n, p = X.shape\n\n if y.ndim == 1:\n y = onehot_encode(y, k)\n\n ll = 0.0\n\n for i, x_i in enumerate(X):\n p_i = logistic_predict_prob(W, x_i)\n ll += y[i].dot(np.log(p_i))\n\n return ll\n\n\ndef logistic_loglik_grad(W, X, y):\n k = W.shape[0] + 1\n n, p = X.shape\n\n if y.ndim == 1:\n y = onehot_encode(y, k)\n\n g = np.zeros_like(W)\n\n for i, x_i in enumerate(X):\n p_i = logistic_predict_prob(W, x_i)\n\n for j, y_ij in enumerate(y[i]):\n if j >= k - 1:\n continue\n\n g[j] += (y_ij - p_i[j]) * x_i\n\n return g\n","repo_name":"pschulam-attic/subtype","sub_path":"logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"15879349156","text":"\ndef rot_decrypt(string, shift=8):\n cipher = \"\"\n for char in string: \n if char == \" \":\n cipher = cipher + char\n elif char.isupper():\n cipher = cipher + chr((ord(char) - shift - 65) % 26 + 65)\n else:\n cipher = cipher + chr((ord(char) - shift - 97) % 26 + 97)\n \n return cipher\n\n\nfilename = str(input(\"Please input timestamp (without .txt)\")) + \".txt\"\noutput_filename = filename + \" - DECRYPTED.txt\"\n\noutput = open(output_filename, \"w\")\n\nfile = open(filename, \"r\")\n\nfor line in file:\n # Ignore decryption for keywords, Section Lines and empty lines.\n if (line == \"\\n\") or (\"SECTION\" in line) or line.startswith('['):\n output.write(line)\n else:\n output.write(rot_decrypt(line.replace('\\n', '')))\n output.write(\"\\n\")\n\nprint(\"Decryption attempt completed.\")","repo_name":"eirikhr/noroff","sub_path":"UC1PR1102/00 ASSESSMENTS/03 Banking/src3/decrypt.py","file_name":"decrypt.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"14929394376","text":"\nfrom discord.ext import commands\nimport os\nimport sys\n\nclass DevCommands(commands.Cog):\n \n '''A cog specifically for developers (i.e. bot owner).'''\n\n def __init__(self, bot, *args, **kwargs):\n self.bot = bot\n self.args = args\n self.kwargs = kwargs\n \n # =============================\n # put any instanced variables here.\n # =============================\n \n async def cog_check(self, ctx):\n '''This method is used to check a role/channel'''\n \n if ctx.message.author.id == self.bot.owner_id:\n return True\n \n await ctx.send(\"You cannot run this command, as you are not a developer.\")\n return False\n\n @commands.command()\n async def ping(self, ctx):\n await ctx.send('Pong!')\n \n @commands.command(aliases=[\"r\", \"R\"])\n async def restart(self, ctx): \n await ctx.message.add_reaction('\\U0001f44d')\n os.system(\"clear\")\n os.execv(sys.executable, ['python'] + sys.argv)\n\ndef setup(bot, *args, **kwargs):\n bot.add_cog(DevCommands(bot, *args, **kwargs))\n\n","repo_name":"WxBDM/simple-discord-bot","sub_path":"src/cogs/devcog.py","file_name":"devcog.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"32495374200","text":"import csv\nimport pandas as pd \nyear = []\ndata = []\ncsv_reader = csv.reader(open('world life expectanct at birth, total.csv'))\nfor line in csv_reader:\n year.append(line[0])\n data.append(line[1])\ndata = data[1:]\nresult = []\nfor i in range(len(data)):\n result.append(float(data[i]))\nprint(result)","repo_name":"sakuraxin/data-vis","sub_path":"data/world.py","file_name":"world.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"24611729329","text":"# @Time : 2021/03/14 22:44\r\n# @Author : SY.M\r\n# @FileName: build_glove_embeddind_dict.py\r\n\r\nimport pickle\r\n\r\npath = 'E:/PyCharmWorkSpace/dataset/utils/glove_embedding/glove.42B.300d.txt'\r\n\r\nglove_embedding = {}\r\nwith open(path, 'r', encoding='utf-8') as f:\r\n while True:\r\n embedding = []\r\n line = f.readline()\r\n if line == '':\r\n break\r\n word, embedding_str = line.split(' ')[0], line.split(' ')[1:]\r\n for i in embedding_str:\r\n embedding.append(eval(i))\r\n glove_embedding[word] = embedding\r\n\r\n with open('E:/PyCharmProjects/RNN/RNN_on_sentiment-analysis-on-movie-reviews/utils/glove_embedding_dict_42B_300d'\r\n '.pkl', 'wb') as f1:\r\n pickle.dump(glove_embedding, f1, pickle.HIGHEST_PROTOCOL)\r\n","repo_name":"SY-Ma/RNN_on_sentiment-analysis-on-movie-reviews","sub_path":"RNN_on_sentiment-analysis-on-movie-reviews/utils/build_glove_embeddind_dict.py","file_name":"build_glove_embeddind_dict.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"77"}
+{"seq_id":"40362475571","text":"from django.shortcuts import render\nimport spotipy\nimport socket\n\n\n# Create your views here.\ndef do_command(data):\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect(('localhost', 7674))\n s.sendall(data)\n return s.recv(1024).decode()\n\n\ndef now_playing(request):\n client = spotipy.Spotify()\n song_uri = do_command(b'c')\n song = client.track(song_uri)\n song['artist_names'] = list(map(lambda a: a['name'], song['artists']))\n return render(request, 'now_playing.html', {'track': song})\n","repo_name":"ryanhornik/partify","sub_path":"web/partifyweb/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"14644041930","text":"class Solution:\n def findAndReplacePattern(self, words, pattern):\n \"\"\"\n :type words: List[str]\n :type pattern: str\n :rtype: List[str]\n \"\"\"\n b = pattern\n def is_iso(a):\n return len(a) == len(b) and len(set(a)) == len(set(b)) == len(set(zip(a, b)))\n return list(filter(is_iso, words))\n\n# filter(func,list),返回一个迭代器\n# 仅仅返回func判断为真的值\n# zip这个绝了\n\n\nclass Solution:\n def findAndReplacePattern(self, words, pattern):\n \"\"\"\n \"\"\"\n result = []\n for word in words:\n if len(word) == len(pattern):\n word_to_pattern_dict = {}\n pattern_to_word_dict = {}\n flag = True\n for i, char in enumerate(pattern):\n if char not in pattern_to_word_dict and word[i] not in word_to_pattern_dict:\n pattern_to_word_dict[char] = word[i]\n word_to_pattern_dict[word[i]] = char\n elif char in pattern_to_word_dict and pattern_to_word_dict[char] == word[i]:\n continue\n else:\n flag = False\n break\n if flag: result.append(word)\n return result\n\n\n# 我最开始的想法:\nfrom collections import OrderedDict\n\nclass Solution(object):\n def getPattern(self, s):\n temp = OrderedDict()\n for ch in s:\n if ch not in temp.keys():\n temp[ch] = [i for i, x in enumerate(s) if x == ch]\n #print temp.values()\n return temp.values()\n\n def findAndReplacePattern(self, words, pattern):\n \"\"\"\n :type words: List[str]\n :type pattern: str\n :rtype: List[str]\n \"\"\"\n res = []\n basePattern = self.getPattern(pattern)\n #basePattern2 = self.getPattern2(pattern)\n for word in words:\n if basePattern == self.getPattern(word):\n res.append(word)\n return res\n ","repo_name":"whoisalan/leetcode","sub_path":"medium/890FindandReplacePattern.py","file_name":"890FindandReplacePattern.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"35323266217","text":"from entities.ku_downloader import KuDownloader\nfrom entities.ku_parser import KUParser\n\ndef download_and_process_kus():\n try:\n # Create an instance of the downloader\n # Download the KUs zip files\n kd = KuDownloader()\n kd.download_all_kus()\n\n # Extract target files from the downloaded zip\n kp = KUParser()\n kp.extract_zip_files()\n kp.upload_data_to_gdb()\n \n # Remove the zip files and unpacked files\n kp.remove_zip_files()\n kp.remove_unpacked_files()\n \n print('Done')\n \n except Exception as e:\n print(f\"An error occurred: {e}\")\n\nif __name__ == \"__main__\":\n download_and_process_kus()","repo_name":"dedtadeas/ku_download_parse_app","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"41963757297","text":"import os\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\n# Substitua os valores apropriados para o seu banco de dados\nSQLALCHEMY_DATABASE_URI = '{SGBD}://{usuario}:{senha}@{servidor}/{database}'.format(\n SGBD='mysql+mysqlconnector',\n usuario='root',\n senha=\"root\",\n servidor='127.0.0.1',\n database='ProjetoPI'\n)\n\nengine = create_engine(SQLALCHEMY_DATABASE_URI)\nSession = sessionmaker(bind=engine)\nBase = declarative_base()\n\nUPLOAD_PATH = os.path.dirname(os.path.abspath(__file__)) + '/uploads'\n","repo_name":"Sogoid/Projeto_Integrador_2023_N2","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"9827677626","text":"import numpy as np\nfrom numpy import random as rd\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport knn\n\nKs = [1, 2, 5, 10, 100]\nTEST_SET_AMOUNT = 1000\nDATA_PATH = './spam.data.txt'\n\ndef randomly_split_data(data):\n data_size = data.shape[0]\n amount_of_training_data = data_size - TEST_SET_AMOUNT\n training_set_indices = rd.choice(data_size, size=amount_of_training_data, replace=False)\n\n training_data = data[training_set_indices, :]\n test_data = np.delete(data, training_set_indices, axis=0)\n\n return training_data, test_data\n\n\ndef read_data():\n data_table = pd.read_csv(DATA_PATH, sep=' ', header=None)\n data_mat = data_table.values\n return data_mat.astype(np.float64)\n\n\ndef split_samples_and_lables(data):\n return data[:,0:-1], data[:,-1]\n\ndef q7c():\n data = read_data()\n\n for i in range(1,11):\n test_iteration(data, i)\n\n plt.xlabel(\"K\")\n plt.ylabel(\"Error\")\n plt.title(\"Error as a function of K\")\n plt.legend()\n plt.show()\n\n\ndef test_iteration(data, test_number):\n train_set, test_set = randomly_split_data(data)\n train_set_samples, train_set_labels = split_samples_and_lables(train_set)\n test_set_samples, test_set_labels = split_samples_and_lables(test_set)\n\n ks_array = np.array(Ks)\n errors = np.zeros_like(ks_array).astype(np.float64)\n\n i = 0\n for k in Ks:\n knn_learner = knn.knn(k)\n knn_learner.fit(train_set_samples, train_set_labels)\n predictions = np.apply_along_axis(knn_learner.predict, 1, test_set_samples)\n\n error = np.sum(np.square(predictions - test_set_labels)) / TEST_SET_AMOUNT\n errors[i] = error\n i += 1\n\n plt.plot(ks_array, errors, label=\"test \" + str(test_number), marker='o')\n\n\n\nq7c()","repo_name":"Alont93/simple-classifications-self-implemented","sub_path":"test_knn.py","file_name":"test_knn.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"6533318069","text":"import random\nimport sys\nimport math\nimport copy\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\n\ndef apply_drift(terrain, num_drifts=10, max_drift_segments=8):\n\tprint(\"Apply drift to terrain...\")\n\theight = len(terrain)\n\twidth = len(terrain[0])\n\tmax_segment_length = (height + width) / num_drifts / max_drift_segments * 5\n\tterrain = create_potential_map_and_drift(terrain, height, width, \n\t\tnum_drifts, max_drift_segments, max_segment_length, 100)\n\n\n\t# Modify potentials and drit\n\treturn terrain\n\n\ndef calculate_vertices(potential_map, num_segments, max_segment_length):\n\theight = len(potential_map)\n\twidth = len(potential_map[0])\n\tvertices = [np.array([random.randrange(height), random.randrange(width)])]\n\tdisplacement = random_vector(max_segment_length)\n\tfor i in range(num_segments):\n\t\tlast = vertices[-1]\n\t\tdisplacement = displacement + random_vector(max_segment_length * 0.5)\n\t\tnew = last + displacement\n\t\tif new[0] <= 0:\n\t\t\tnew[0] = 0\n\t\telif new[0] >= len(potential_map) - 1:\n\t\t\tnew[0] = len(potential_map) - 1\n\t\tvertices.append(new)\n\t\tdisplacement = new - last\n\treturn vertices\n\n\ndef create_potential_map_and_drift(terrain, height, width, n=10, max_drift_segments=8, max_segment_length=10, iterations=30):\n\tprint(\"Creating potential map...\")\n\tpotential_map = np.zeros([height, width])\n\tvertices_set = []\n\tfor i in range(n):\n\t\tnum_segments = random.randrange(max_drift_segments) + 3\n\t\tvertices = calculate_vertices(potential_map, num_segments, max_segment_length)\n\t\tvertices_set.append(vertices)\n\t\tpotential_map = draw_vertices_on_potential(vertices, potential_map)\n\tsolved_map = solve_potential(potential_map)\n\tterrain = terrain + solved_map\n\tfor it in range(iterations):\n\t\tprint(\"Drifting, time=%d\" % it)\n\t\tpotential_map = np.zeros([height, width])\n\t\tvertices_set = modify_vertices(vertices_set, potential_map, num_segments, max_segment_length, max_segment_length / 4)\n\t\tfor vertices in vertices_set:\n\t\t\tpotential_map = draw_vertices_on_potential(vertices, potential_map)\n\t\tsolved_map = solve_potential(potential_map)\n\t\tterrain = terrain + solved_map\n\n\treturn terrain\n\n\ndef draw_vertices_on_potential(vertices, potential_map):\n\theight = len(potential_map)\n\twidth = len(potential_map[0])\n\tpower = []\n\tif len(vertices) == 1:\n\t\tpower = [1]\n\telse:\n\t\tfor i in range(len(vertices) - 1):\n\t\t\tpower.append( math.sin( math.pi * (i + 0.5) / (len(vertices) - 1) ) )\n\n\tinvert = random.randrange(2)\n\tfor i in range(len(power)):\n\t\tif invert == 1:\n\t\t\tpower[i] = - power[i]\n\t\tpower[i] = power[i] * random.uniform(0,2)\n\n\n\tfor i in range(len(vertices) - 1):\n\t\tbegin = vertices[i]\n\t\tend = vertices[i + 1]\n\t\tdelta_h = end[0] - begin[0]\n\t\tdelta_w = end[1] - begin[1]\n\t\tnum_points = math.ceil(max(abs(delta_h), abs(delta_w)))\n\t\tfor j in range(num_points + 1):\n\t\t\tl = 1 / num_points * j\n\t\t\tp = l * begin + (1 - l) * end\n\t\t\tpotential_map[math.floor(p[0])][math.floor(p[1]) % width] = power[i]\n\treturn potential_map\n\n\ndef generate_empty_terrain(height, width):\n\treturn np.zeros([height, width])\n\n\ndef generate_terrain(height, width):\n\tprint(\"Generating terrain %d*%d...\" % (height, width))\n\tterrain = generate_empty_terrain(height, width)\n\tterrain = apply_drift(terrain)\n\tterrain = terrain - np.mean(terrain)\n\tterrain = terrain / np.std(terrain) * 1000 - 100\n\n\tterrain[0][0]=5000\n\tterrain[-1][-1]=-5000\n\tshow_terrain(terrain)\n\tland = copy.deepcopy(terrain)\n\tland[land<0]=-5000\n\tshow_terrain(land)\n\n\n\ndef modify_vertices(vertices_set, potential_map, num_segments, max_segment_length, displ):\n\tfor i in range(len(vertices_set)):\n\t\tdisplacement = random_vector(displ)\n\t\tr = random.randrange(8)\n\t\tfor j in range(len(vertices_set[i])):\n\t\t\tv_displ = displacement + random_vector(displ / 4)\n\t\t\tvertices_set[i][j] = vertices_set[i][j] + v_displ\n\t\t\tif vertices_set[i][j][0] <= 0:\n\t\t\t\tvertices_set[i][j][0] = 0\n\t\t\telif vertices_set[i][j][0] >= height - 1:\n\t\t\t\tvertices_set[i][j][0] = height - 0.01\n\tfor i in range(len(vertices_set)):\n\t\tr = random.randrange(15)\n\t\tif r == 0:\n\t\t\tvertices_set[i] = calculate_vertices(potential_map, num_segments, max_segment_length)\n\treturn vertices_set\n\n\ndef random_direction():\n\ttheta = random.uniform(0, 2 * math.pi)\n\treturn np.array([math.cos(theta), math.sin(theta)])\n\n\ndef random_vector(max_length):\n\tr = random_direction()\n\tl = random.uniform(0, max_length)\n\treturn r * l\n\n\ndef show_terrain(terrain):\n\tplt.matshow(terrain, cmap=\"terrain\")\n\tplt.colorbar()\n\tplt.show()\n\n\ndef solve_potential(potential):\n\tmask = potential != 0\n\theight = len(potential)\n\twidth = len(potential[0])\n\titerations = math.ceil((height + width) / 5)\n\tnew_potential = potential\n\n\tfor it in range(iterations):\n\t\tfor h in range(height):\n\t\t\tfor w in range(width):\n\t\t\t\tif mask[h][w] == False:\n\t\t\t\t\tneighbours = []\n\t\t\t\t\tif h != 0:\n\t\t\t\t\t\tneighbours.append(potential[h-1][w])\n\t\t\t\t\tif h != height - 1:\n\t\t\t\t\t\tneighbours.append(potential[h+1][w])\n\t\t\t\t\tneighbours.append(potential[h][(w+1)%width])\n\t\t\t\t\tneighbours.append(potential[h][(w-1)%width])\n\t\t\t\t\ts = 0\n\t\t\t\t\tfor neighbour in neighbours:\n\t\t\t\t\t\ts += neighbour\n\t\t\t\t\tnew_potential[h][w] = s / len(neighbours)\n\t\t\t\telse:\n\t\t\t\t\tnew_potential[h][w] = potential[h][w]\n\t\tpotential = new_potential\n\treturn potential\n\n\n\nif __name__ == \"__main__\":\n\tprint(sys.argv)\n\tif len(sys.argv) <= 2:\n\t\theight = int(input('Enter height of the terrain: '))\n\t\twidth = int(input('Enter width of the terrain: '))\n\telse:\n\t\theight = int(sys.argv[1])\n\t\twidth = int(sys.argv[2])\n\tgenerate_terrain(height, width)","repo_name":"Wangzzh/Terra-Generator","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":5410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"10363544390","text":"\"\"\"\nLatch phy layer object\n\nWARNING, ALERT, ETC\n\nThis module does not support changing the system time while running.\nDon't do it\n\"\"\"\nfrom datetime import datetime, timedelta\nfrom threading import Thread, Lock\nfrom time import sleep\nfrom gpiozero import DigitalOutputDevice\n\n\nclass Latch:\n def __init__(self,\n pin: int,\n max_on_seconds: float = 3,\n hold_off_seconds: float = 10,\n last_disabled: datetime = datetime.now()):\n \"\"\"\n Creates a latch object with the provided parameters\n :param pin: pin number\n :param max_on_seconds:\n :param hold_off_seconds:\n :param last_disabled: a datetime object for when this object was last disabled, else now.\n \"\"\"\n self.__gpio = DigitalOutputDevice(pin)\n self.__max_on_time = timedelta(seconds=max_on_seconds)\n self.__hold_off_time = timedelta(seconds=hold_off_seconds)\n self.__last_disabled = last_disabled\n self.__phy_lock = Lock()\n self.__background_thread = None\n self.__stop_thread = False\n\n def _unlatch_after_max_hold_time(self):\n start_time = datetime.now()\n while 1:\n if (datetime.now() - start_time) >= self.__max_on_time:\n with self.__phy_lock:\n self.__gpio.off()\n break\n with self.__phy_lock:\n if self.__stop_thread:\n break\n sleep(.1)\n\n def unlatch(self):\n \"\"\"\n actuate the latch\n :return:\n \"\"\"\n with self.__phy_lock:\n if (datetime.now() - self.__last_disabled) < self.__hold_off_time:\n return False\n else:\n if self.__background_thread is None:\n self.__background_thread = Thread(target=self._unlatch_after_max_hold_time)\n self.__stop_thread = False\n self.__background_thread.start()\n self.__gpio.on()\n return True\n\n def release(self):\n \"\"\"\n Release the latch and stop the background thread\n :return:\n \"\"\"\n with self.__phy_lock:\n if self.__gpio.is_active:\n self.__gpio.off()\n self.__last_disabled = datetime.now()\n if self.__background_thread is not None:\n self.__stop_thread = True\n if self.__background_thread is not None:\n self.__background_thread.join()\n self.__stop_thread = False\n\n def close(self):\n \"\"\"\n tear down this object\n :return:\n \"\"\"\n with self.__phy_lock:\n self.__gpio.off()\n self.__last_disabled = datetime.now()\n if self.__background_thread is not None:\n self.__stop_thread = True\n if self.__background_thread is not None:\n self.__background_thread.join()\n self.__gpio.close()\n","repo_name":"PseudoDesign/dbox_app","sub_path":"dbox_app/phy/latch.py","file_name":"latch.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"21106928374","text":"import tensorflow as tf\nimport numpy as np\nimport psutil\nfrom os import getpid\n\nval_num = 8*256*256\nval_dim = 5\nmax_val = 200\nnum_steps = 10000\n\n\ndef main():\n\n with tf.device(\"/gpu:0\"):\n x = tf.placeholder(tf.int32, [val_num, val_dim])\n \n def tf_unique_row_idxs(inp, max_dim=None, name=''):\n with tf.variable_scope('tf_unique_row_idxs_'+name) as scope:\n if not max_dim:\n max_dim = inp.get_shape().as_list()[1]\n new_vals = inp[:,0]\n new_vals = tf.cast(new_vals, dtype=tf.int32)\n _, idx = tf.unique(new_vals, out_idx=tf.int32)\n for j in range(1, max_dim):\n new_vals = inp[:,j]\n new_vals = tf.cast(new_vals, dtype=tf.int32)\n val_min = tf.reduce_min(new_vals)\n val_max = tf.reduce_max(new_vals)\n idx_shift = val_max - val_min + 1\n vals = idx*idx_shift + new_vals - val_min\n uvals, idx = tf.unique(vals, out_idx=tf.int32)\n max_pos = tf.shape(uvals, out_type=tf.int32)[0] + 0\n return idx, max_pos\n \n idxs, max_pos = tf_unique_row_idxs(x)\n \n \n process = psutil.Process(getpid())\n\n cur_config=tf.ConfigProto(allow_soft_placement=False,log_device_placement=False)\n sess = tf.Session(config=cur_config)\n sess.run(tf.global_variables_initializer())\n \n\n mem_usage = np.zeros([num_steps], dtype=np.float32)\n\n np.random.seed(0)\n for i in range(num_steps):\n cur_x = np.random.randint(0, max_val, [val_num, val_dim], dtype=np.int32)\n cur_feed_dict = {x: cur_x}\n cur_max_pos, cur_idxs = sess.run([max_pos, idxs], feed_dict=cur_feed_dict)\n mem_usage[i] = process.memory_info().rss/2**30\n if i%100==0:\n print(i/num_steps)\n \n\n np.savetxt('unique_memlog.txt', mem_usage)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dantkz/snippets","sub_path":"unique.py","file_name":"unique.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"10521463595","text":"from asyncio.log import logger\nimport logging\nimport sys\n\nfrom scania_truck.components.data_ingestion import DataIngestion\nfrom scania_truck.components.data_transformation import DataTransformation\nfrom scania_truck.components.data_validation import DataValidation\nfrom scania_truck.components.model_trainer import ModelTrainer\nfrom scania_truck.exception import ScaniaException\nfrom scania_truck.utils.main_utils import MainUtils\nfrom scania_truck.utils.read_params import read_params\n\nlogger = logging.getLogger(__name__)\n\n\nclass TrainPipeline:\n def __init__(self):\n self.config = read_params()\n\n self.utils = MainUtils()\n\n self.artifacts_dir = self.config[\"artifacts_dir\"]\n\n @staticmethod\n def start_data_ingestion():\n logger.info(\"Entered the start_data_ingestion method of Pipeline class\")\n\n try:\n logging.info(\"Getting the data from mongodb\")\n\n data_ingestion = DataIngestion()\n\n df = data_ingestion.get_data_from_mongodb()\n\n train_set, test_set = data_ingestion.split_data_as_train_test(df)\n\n logger.info(\"Got the data from mongodb\")\n\n logger.info(\"Exited the start_data_ingestion method of Pipeline class\")\n\n return train_set, test_set\n\n except Exception as e:\n\n message = ScaniaException(e, sys)\n \n logger.error(message.error_message)\n \n raise message.error_message\n\n\n @staticmethod\n def start_data_validation(train_set, test_set):\n try:\n data_validation = DataValidation(train_set, test_set)\n\n logger.info(\"Exited the start_data_validation method of Pipeline class\")\n\n return data_validation.initiate_data_validation()\n\n except Exception as e:\n\n message = ScaniaException(e, sys)\n \n logger.error(message.error_message)\n \n raise message.error_message\n\n\n @staticmethod\n def start_data_transformation(train_set, test_set):\n try:\n data_transformation = DataTransformation()\n\n train_set, test_set = data_transformation.initiate_data_transformation(train_set, test_set)\n\n logger.info(\"Exited the start_data_transformation method of Pipeline class\")\n\n return train_set, test_set\n\n except Exception as e:\n\n message = ScaniaException(e, sys)\n \n logger.error(message.error_message)\n \n raise message.error_message\n\n\n def start_model_trainer(self, train_set, test_set):\n try:\n model_trainer = ModelTrainer()\n\n model_trainer.initiate_model_trainer(train_set, test_set)\n\n except Exception as e:\n\n message = ScaniaException(e, sys)\n \n logger.error(message.error_message)\n \n raise message.error_message","repo_name":"Adityashinde1/Scania-truck","sub_path":"scania_truck/pipeline/train_pipeline.py","file_name":"train_pipeline.py","file_ext":"py","file_size_in_byte":2900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"22483344839","text":"\"\"\"This class represents the game.\"\"\"\n\nimport player\nimport dice\nimport intelligence\nimport highscore\n\n\nclass Game:\n\n # class variable shared by all instances\n number_of_players = 1\n player1_score = 0\n player2_score = 0\n player_turn = 0\n level_of_intelligence = 1\n is_cheating = False\n p_1 = None\n p_2 = None\n\n def start(self):\n \"\"\"Starts the game\"\"\"\n try:\n self.number_of_players = int(input(\"\\nEnter number of players (1/2): \"))\n if self.number_of_players < 1 or self.number_of_players > 2:\n raise ValueError\n\n if self.number_of_players == 1:\n self.level_of_intelligence = int(\n input(\"\\nChoose level of difficulty (1/2): \")\n )\n if self.level_of_intelligence < 1 or self.level_of_intelligence > 2:\n raise ValueError\n except ValueError:\n raise ValueError(\"Choose between '1' or '2'. Start the game again.\")\n\n self.p_1 = player.Player()\n self.p_1.set_name(1)\n\n self.p_2 = player.Player()\n if self.number_of_players == 2:\n self.p_2.set_name(2)\n else:\n self.p_2.name = \"Computer\"\n\n if self.p_1.name == \"\" or self.p_2.name == \"\":\n raise ValueError(\"Name cannot be empty. Start the game again.\")\n\n def roll(self):\n \"\"\"Player rolls the dice and chooses wheather to hold or continue.\"\"\"\n die = dice.Dice()\n roll = die.roll_dice()\n\n if self.computer_turn() and self.is_cheating:\n roll = 1\n self.is_cheating = False\n\n if self.player_1_turn():\n print(f\"\\n{self.p_1.name}'s rolling the dice, it was a {roll}\")\n else:\n print(f\"\\n{self.p_2.name}'s rolling the dice, it was a {roll}\")\n\n if self.computer_turn():\n self.computer(roll)\n return\n\n if roll != 1:\n hold = input(\"Do you want to hold? (y/n): \")\n if hold == \"y\":\n self.hold(roll)\n if self.one_player() and self.score_below_100():\n self.roll()\n else:\n if self.player_1_turn():\n self.player1_score += roll\n print(f\"({self.p_1.name}) Score : {self.player1_score}\\n\")\n else:\n self.player2_score += roll\n print(f\"({self.p_2.name}) Score : {self.player2_score}\\n\")\n else:\n if self.player_1_turn():\n self.player1_score = 0\n self.player_turn = 1\n print(f\"({self.p_1.name}) Total score : {self.p_1.score}\\n\")\n if self.one_player() and self.score_below_100():\n self.roll()\n else:\n self.player2_score = 0\n self.player_turn = 0\n print(f\"({self.p_2.name}) Total score : {self.p_2.score}\\n\")\n\n def computer(self, roll):\n \"\"\"Computer's turn to play\"\"\"\n if roll != 1:\n intel = intelligence.Intelligence()\n if self.level_of_intelligence == 1:\n hold_or_cont = intel.level_1()\n elif self.level_of_intelligence == 2:\n hold_or_cont = intel.level_2()\n\n if hold_or_cont == \"y\":\n print('Computer chose to \"hold\"')\n self.hold(roll)\n else:\n self.player2_score += roll\n print('Computer chose to \"continue\"')\n print(f\"({self.p_2.name}) Score : {self.player2_score}\\n\")\n self.roll()\n else:\n self.player2_score = 0\n self.player_turn = 0\n print(f\"({self.p_2.name}) Total score : {self.p_2.score}\\n\")\n\n def hold(self, roll):\n \"\"\"Hold the rolled die.\"\"\"\n if self.player_turn == 0:\n self.player1_score += roll\n self.p_1.score += self.player1_score\n self.player1_score = 0\n self.player_turn = 1\n print(f\"({self.p_1.name}) Total score : {self.p_1.score}\\n\")\n else:\n self.player2_score += roll\n self.p_2.score += self.player2_score\n self.player2_score = 0\n self.player_turn = 0\n print(f\"({self.p_2.name}) Total score : {self.p_2.score}\\n\")\n\n def player_1_turn(self):\n \"\"\"Returns if current player is Player 1.\"\"\"\n return self.player_turn == 0\n\n def player_2_turn(self):\n \"\"\"Returns if current player is Player 2.\"\"\"\n return self.player_turn == 1\n\n def one_player(self):\n \"\"\"Returns if the game is played by 1 player.\"\"\"\n return self.number_of_players == 1\n\n def computer_turn(self):\n \"\"\"Return if it's computer's turn.\"\"\"\n return self.player_2_turn() and self.one_player()\n\n def score_below_100(self):\n \"\"\"Checks if score is under 100\"\"\"\n if self.p_1.score < 100 and self.p_2.score < 100:\n return True\n\n return False\n\n def get_winner(self):\n \"\"\"Return the name of the winner player.\"\"\"\n if self.p_1.score >= 100:\n return self.p_1.name\n\n return self.p_2.name\n\n def change_player_name(self):\n \"\"\"Changed the name of the chosen player.\"\"\"\n if self.p_1 and self.p_2:\n if self.number_of_players == 1:\n self.p_1.update_name()\n else:\n plyr = int(input(\"Choose player (1/2): \"))\n if plyr == 1:\n self.p_1.update_name()\n else:\n self.p_2.update_name()\n else:\n print(\"You haven't started the game yet!\\n\")\n\n def change_game_level(self):\n \"\"\"Changes the games level of intelligence\"\"\"\n if self.p_1 and self.p_2:\n if self.number_of_players == 1:\n print(f\"Current level is {self.level_of_intelligence}.\")\n val = input(\"Do you wish to change the level? (y/n): \")\n if val == \"y\":\n self.level_of_intelligence = int(\n input(\"\\nChoose level of difficulty (1/2): \")\n )\n print(\n f\"Level successfully changed to {self.level_of_intelligence}.\\n\"\n )\n else:\n print(\n \"This setting is only configurable when playing towards a computer!\\n\"\n )\n else:\n print(\"You haven't started the game yet!\\n\")\n\n def get_highscore(self):\n \"\"\"Represents the highscore of the current game.\"\"\"\n if self.p_1 and self.p_2:\n h_score = highscore.HighScore()\n players = [self.p_1.name, self.p_2.name]\n current_scores = [self.player1_score, self.player2_score]\n total_scores = [self.p_1.score, self.p_2.score]\n h_score.get_highscore(players, current_scores, total_scores)\n else:\n print(\"You haven't started the game yet!\\n\")\n\n def cheat(self):\n \"\"\"Activates cheat\"\"\"\n if self.p_1 and self.p_2:\n if self.number_of_players == 2:\n print(\n \"Cheating is only available when you're playing against a computer.\\n\"\n )\n return\n self.is_cheating = True\n print('Cheating... Computer will get a \"1\" in the next round.\\n')\n else:\n print(\"You haven't started the game yet!\\n\")\n","repo_name":"ahmedmohd957/game","sub_path":"dice_game/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":7507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"40652920249","text":"\"\"\"\n\n Main file\n\n\"\"\"\n\nimport re\nimport argparse\n\nfrom pathlib import Path\n\n\nfrom source.ui_bezier_path_generator import UIBezierPathGenerator\n\n\ndef parse_command_arguments():\n \"\"\"Returns parsed command arguments\"\"\"\n parser = argparse.ArgumentParser(description=\"svg-to-swift converter\")\n parser.add_argument(\"--input_file\", required=True, help=\"SVG file to convert.\")\n parser.add_argument(\"--output_file\", default=\"svg.swift\", help=\"File to save in swift code.\")\n return parser.parse_args()\n\n\ndef check_input_file(input_file_path: str):\n \"\"\"Raises ValueException if file does not exist or has incorrect extension\"\"\"\n path2file = Path(input_file_path)\n\n if not path2file.is_file():\n raise ValueError(\"File {input} not found!\".format(input=input_file_path))\n if not input_file_path.endswith(\".svg\"):\n raise ValueError(\"File should have .svg extension\")\n\n\ndef get_svg_file_d_attribute(path2file: str):\n \"\"\"Returns d attribute content\"\"\"\n\n def find_d_attribute(text):\n return re.findall(r' Recipe:\n \"\"\"Prints a recipe with the name \\\n {name} and returns the instance\"\"\"\n if not isinstance(name, str):\n raise TypeError(\"Recipe name must be a string\")\n for recipes in self.__recipes_list.values():\n for recipe in recipes:\n if name in recipe.name:\n print(str(recipe))\n return recipe\n raise ValueError(f'{name} not in {self.name}')\n\n def get_recipes_by_types(self, recipe_type: str) -> list:\n \"\"\"Get all recipe names for a given recipe_type \"\"\"\n if not isinstance(recipe_type, str):\n raise TypeError(\"Recipe type must be a string\")\n if recipe_type not in self.__recipes_list:\n raise ValueError(f\"Recipe types : {self.__recipes_list.keys()}\")\n names_list = [recipe.name\n for recipe in self.__recipes_list[recipe_type]\n if len(self.__recipes_list[recipe_type])]\n return names_list\n # print(f'{recipe_type}')\n # for recipes in self.__recipes_list[recipe_type]:\n # if not len(self.__recipes_list[recipe_type]):\n # print(\"\\tempty\")\n # else:\n # print(f'\\t{recipes.name}')\n\n def add_recipe(self, recipe: Recipe):\n \"\"\"Add a recipe to the book and update last_update\"\"\"\n if not isinstance(recipe, Recipe):\n raise TypeError(\"add_recipe must be Recipe instance\")\n if recipe.recipe_type not in self.__recipes_list:\n raise ValueError(\"how can you do that you strange wizard ?\")\n self.__recipes_list[recipe.recipe_type].append(recipe)\n self.last_update = datetime.datetime.now()\n # print(f'{recipe.name} added to the cookbook {self.name}')\n\n def __str__(self):\n return (\n f'\"{self.name}\" created at {self.creation_date}, '\n f'last update {self.last_update}')\n","repo_name":"Ggilb3rt/piscinePython","sub_path":"module01/ex00/book.py","file_name":"book.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"38575742596","text":"with open('input.txt','r') as f:\n\tlistl=[]\n\tfor line in f:\n\t\tstrip_lines=line.strip()\n\t\tm=listl.append(strip_lines)\n\nprint(listl)\nhorizontal = 0\ndepth = 0\naim = 0\nfor i in listl:\n command, number = i.split(' ')\n if( command == 'forward'):\n horizontal += int(number)\n depth += aim * int(number)\n elif(command == 'down'):\n aim += int(number)\n else:\n aim -= int(number)\n\nprint(\"Horizontal is {} and depth is {} and aim is {}\".format(horizontal, depth, aim))\nprint(f'final result is {horizontal*depth}')","repo_name":"donicjak/advent_of_code","sub_path":"02/app2.py","file_name":"app2.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"2856470049","text":"import re\n \n# Multiplicar por 2 los numeros en posiciones impares\n# en el arreglo. Restarle 9 si el resultado es\n# mayor que 9\n\ndef eval_pos(n, pos):\n \n if ( pos % 2 != 0 ):\n t = n * 2\n if ( t > 9 ): \n t -= 9\n return t\n return n\n\ndef validate_cedula( value ):\n \n # Regex para filtrar cedulas con el formato correcto: 11 digitos \n # que no empienzan con 000 ni contenga guiones\n p = re.compile(r'^(?!000)[0-9]{11}$')\n m = p.match( value )\n \n is_valid = False\n \n if m:\n ced = m.group(0)\n v = int( ced[-1] ) # Digito verificador. Ultimo digito del arreglo\n z = [ int(n) for n in ced[:10] ] #Los primeros 10 digitos\n \n sn = 0 # sumatoria de los n-elementos del arreglo\n pos = 0 # Posicion en el arreglo\n \n for n in z[::-1]: # Procesar arreglo descendentemente: der -> izq\n pos += 1\n sn += eval_pos(n, pos)\n \n sn = 10 - sn % 10\n \n # Si la suma es 10 el verificador debe ser cero\n # o el verificador y la suma deben coincidir\n if ( (sn == 10 and v == 0) or sn == v):\n is_valid = True\n \n return is_valid\n \nprint( validate_cedula('00104464664'))\nprint( validate_cedula('01800475863'))\nprint( validate_cedula('02601172932'))\nprint( validate_cedula('00000000012') )\nprint( validate_cedula('001-0247021') )\n\n","repo_name":"mevaldezm/Algoritmos","sub_path":"valcedula.py","file_name":"valcedula.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"71157272249","text":"__author__ = \"Vincent Marois, Tomasz Kornuta\"\n\nfrom os import path,makedirs\nimport yaml\nimport torch\nfrom time import sleep\nfrom datetime import datetime\n\nimport ptp.configuration.config_parsing as config_parse\nimport ptp.utils.logger as logging\n\nfrom ptp.workers.worker import Worker\n\nfrom ptp.application.task_manager import TaskManager\nfrom ptp.application.pipeline_manager import PipelineManager\n\nfrom ptp.utils.statistics_collector import StatisticsCollector\nfrom ptp.utils.statistics_aggregator import StatisticsAggregator\n\n\nclass Trainer(Worker):\n \"\"\"\n Base class for the trainers.\n\n Iterates over epochs on the dataset.\n\n All other types of trainers (e.g. ``OnlineTrainer`` & ``OfflineTrainer``) should subclass it.\n\n \"\"\"\n\n def __init__(self, name, class_type):\n \"\"\"\n Base constructor for all trainers:\n\n - Adds default trainer command line arguments\n\n :param name: Name of the worker\n :type name: str\n\n :param class_type: Class type of the component.\n\n \"\"\" \n # Call base constructor to set up app state, registry and add default arguments.\n super(Trainer, self).__init__(name, class_type)\n\n # Add arguments to the specific parser.\n # These arguments will be shared by all basic trainers.\n self.parser.add_argument(\n '--tensorboard',\n action='store',\n dest='tensorboard', choices=[0, 1, 2],\n type=int,\n help=\"If present, enable logging to TensorBoard. Available log levels:\\n\"\n \"0: Log the collected statistics.\\n\"\n \"1: Add the histograms of the model's biases & weights (Warning: Slow).\\n\"\n \"2: Add the histograms of the model's biases & weights gradients \"\n \"(Warning: Even slower).\")\n\n self.parser.add_argument(\n '--saveall',\n dest='save_intermediate',\n action='store_true',\n help='Setting to true results in saving intermediate models during training (DEFAULT: False)')\n\n self.parser.add_argument(\n '--training',\n dest='training_section_name',\n type=str,\n default=\"training\",\n help='Name of the section defining the training procedure (DEFAULT: training)')\n\n self.parser.add_argument(\n '--validation',\n dest='validation_section_name',\n type=str,\n default=\"validation\",\n help='Name of the section defining the validation procedure (DEFAULT: validation)')\n\n\n def setup_experiment(self):\n \"\"\"\n Sets up experiment of all trainers:\n\n - Calls base class setup_experiment to parse the command line arguments,\n\n - Loads the config file(s)\n\n - Set up the log directory path\n\n - Add a ``FileHandler`` to the logger\n\n - Set random seeds\n\n - Creates the pipeline consisting of many components\n\n - Creates training task manager\n\n - Handles curriculum learning if indicated\n\n - Creates validation task manager\n\n - Set optimizer\n\n - Performs testing of compatibility of both training and validation tasks and created pipeline.\n\n \"\"\"\n # Call base method to parse all command line arguments and add default sections.\n super(Trainer, self).setup_experiment()\n\n # \"Pass\" configuration parameters from the \"default_training\" section to training section indicated by the section_name.\n self.config.add_default_params({ self.app_state.args.training_section_name : self.config['default_training'].to_dict()} )\n self.config.del_default_params('default_training')\n \n # \"Pass\" configuration parameters from the \"default_validation\" section to validation section indicated by the section_name.\n self.config.add_default_params({ self.app_state.args.validation_section_name: self.config['default_validation'].to_dict()} )\n self.config.del_default_params('default_validation')\n\n\n # Check the presence of the CUDA-compatible devices.\n if self.app_state.args.use_gpu and (torch.cuda.device_count() == 0):\n self.logger.error(\"Cannot use GPU as there are no CUDA-compatible devices present in the system!\")\n exit(-1)\n\n # Check if config file was selected.\n if self.app_state.args.config == '':\n print('Please pass configuration file(s) as --c parameter')\n exit(-2)\n\n # Split and make them absolute.\n root_configs = self.app_state.args.config.replace(\" \", \"\").split(',')\n # If there are - expand them to absolute paths.\n abs_root_configs = [path.expanduser(config) for config in root_configs]\n \n # Get the list of configurations which need to be loaded.\n configs_to_load = config_parse.recurrent_config_parse(abs_root_configs, [], self.app_state.absolute_config_path)\n\n # Read the YAML files one by one - but in reverse order -> overwrite the first indicated config(s)\n config_parse.reverse_order_config_load(self.config, configs_to_load)\n\n # -> At this point, the Param Registry contains the configuration loaded (and overwritten) from several files.\n # Log the resulting training configuration.\n conf_str = 'Loaded (initial) configuration:\\n'\n conf_str += '='*80 + '\\n'\n conf_str += yaml.safe_dump(self.config.to_dict(), default_flow_style=False)\n conf_str += '='*80 + '\\n'\n print(conf_str)\n\n # Get training section.\n try:\n tsn = self.app_state.args.training_section_name\n self.config_training = self.config[tsn]\n # We must additionally check if it is None - weird behvaiour when using default value.\n if self.config_training is None:\n raise KeyError()\n except KeyError:\n print(\"Error: Couldn't retrieve the training section '{}' from the loaded configuration\".format(tsn))\n exit(-1)\n\n # Get training task type.\n try:\n training_task_type = self.config_training['task']['type']\n except KeyError:\n print(\"Error: Couldn't retrieve the task 'type' from the training section '{}' in the loaded configuration\".format(tsn))\n exit(-1)\n\n # Get validation section.\n try:\n vsn = self.app_state.args.validation_section_name\n self.config_validation = self.config[vsn]\n if self.config_validation is None:\n raise KeyError()\n except KeyError:\n print(\"Error: Couldn't retrieve the validation section '{}' from the loaded configuration\".format(vsn))\n exit(-1)\n\n # Get validation task type.\n try:\n _ = self.config_validation['task']['type']\n except KeyError:\n print(\"Error: Couldn't retrieve the task 'type' from the validation section '{}' in the loaded configuration\".format(vsn))\n exit(-1)\n\n # Get pipeline section.\n try:\n psn = self.app_state.args.pipeline_section_name\n self.config_pipeline = self.config[psn]\n if self.config_pipeline is None:\n raise KeyError()\n except KeyError:\n print(\"Error: Couldn't retrieve the pipeline section '{}' from the loaded configuration\".format(psn))\n exit(-1)\n\n # Get pipeline name.\n try:\n pipeline_name = self.config_pipeline['name']\n except KeyError:\n # Using name of the first configuration file from command line.\n basename = path.basename(root_configs[0])\n # Take config filename without extension.\n pipeline_name = path.splitext(basename)[0] \n # Set pipeline name, so processor can use it afterwards.\n self.config_pipeline.add_config_params({'name': pipeline_name})\n\n # Prepare the output path for logging\n while True: # Dirty fix: if log_dir already exists, wait for 1 second and try again\n try:\n time_str = '{0:%Y%m%d_%H%M%S}'.format(datetime.now())\n if self.app_state.args.exptag != '':\n time_str = time_str + \"_\" + self.app_state.args.exptag\n self.app_state.log_dir = path.expanduser(self.app_state.args.expdir) + '/' + training_task_type + '/' + pipeline_name + '/' + time_str + '/'\n # Lowercase dir.\n self.app_state.log_dir = self.app_state.log_dir.lower()\n makedirs(self.app_state.log_dir, exist_ok=False)\n except FileExistsError:\n sleep(1)\n else:\n break\n\n # Set log dir.\n self.app_state.log_file = self.app_state.log_dir + 'trainer.log'\n # Initialize logger in app state.\n self.app_state.logger = logging.initialize_logger(\"AppState\")\n # Add handlers for the logfile to worker logger.\n logging.add_file_handler_to_logger(self.logger)\n self.logger.info(\"Logger directory set to: {}\".format(self.app_state.log_dir))\n\n # Set cpu/gpu types.\n self.app_state.set_types()\n\n # Models dir.\n self.checkpoint_dir = self.app_state.log_dir + 'checkpoints/'\n makedirs(self.checkpoint_dir, exist_ok=False)\n\n # Set random seeds in the training section.\n self.set_random_seeds('training', self.config_training)\n\n # Total number of detected errors.\n errors =0\n\n ################# TRAINING PROBLEM ################# \n\n # Build training task manager.\n self.training = TaskManager('training', self.config_training) \n errors += self.training.build()\n \n # parse the curriculum learning section in the loaded configuration.\n if 'curriculum_learning' in self.config_training:\n\n # Initialize curriculum learning - with values from loaded configuration.\n self.training.task.curriculum_learning_initialize(self.config_training['curriculum_learning'])\n\n # If the 'must_finish' key is not present in config then then it will be finished by default\n self.config_training['curriculum_learning'].add_default_params({'must_finish': True})\n\n self.must_finish_curriculum = self.config_training['curriculum_learning']['must_finish']\n self.logger.info(\"Curriculum Learning activated\")\n\n else:\n # If not using curriculum learning then it does not have to be finished.\n self.must_finish_curriculum = False\n self.curric_done = True\n\n ################# VALIDATION PROBLEM ################# \n \n # Build validation task manager.\n self.validation = TaskManager('validation', self.config_validation)\n errors += self.validation.build()\n\n ###################### PIPELINE ######################\n \n # Build the pipeline using the loaded configuration.\n self.pipeline = PipelineManager(pipeline_name, self.config_pipeline)\n errors += self.pipeline.build()\n\n # Check errors.\n if errors > 0:\n self.logger.error('Found {} errors, terminating execution'.format(errors))\n exit(-2)\n\n # Show pipeline.\n summary_str = self.pipeline.summarize_all_components_header()\n summary_str += self.training.task.summarize_io(\"training\")\n summary_str += self.validation.task.summarize_io(\"validation\")\n summary_str += self.pipeline.summarize_all_components()\n self.logger.info(summary_str)\n \n # Handshake definitions.\n self.logger.info(\"Handshaking training pipeline\")\n defs_training = self.training.task.output_data_definitions()\n errors += self.pipeline.handshake(defs_training)\n\n self.logger.info(\"Handshaking validation pipeline\")\n defs_valid = self.validation.task.output_data_definitions()\n errors += self.pipeline.handshake(defs_valid)\n\n # Check errors.\n if errors > 0:\n self.logger.error('Found {} errors, terminating execution'.format(errors))\n exit(-2)\n\n ################## MODEL LOAD/FREEZE #################\n\n # Load the pretrained models params from checkpoint.\n try: \n # Check command line arguments, then check load option in config.\n if self.app_state.args.load_checkpoint != \"\":\n pipeline_name = self.app_state.args.load_checkpoint\n msg = \"command line (--load)\"\n elif \"load\" in self.config_pipeline:\n pipeline_name = self.config_pipeline['load']\n msg = \"'pipeline' section of the configuration file\"\n else:\n pipeline_name = \"\"\n # Try to load the model.\n if pipeline_name != \"\":\n if path.isfile(pipeline_name):\n # Load parameters from checkpoint.\n self.pipeline.load(pipeline_name)\n else:\n raise Exception(\"Couldn't load the checkpoint {} indicated in the {}: file does not exist\".format(pipeline_name, msg))\n # If we succeeded, we do not want to load the models from the file anymore!\n else:\n # Try to load the models parameters - one by one, if set so in the configuration file.\n self.pipeline.load_models()\n\n except KeyError:\n self.logger.error(\"File {} indicated in the {} seems not to be a valid model checkpoint\".format(pipeline_name, msg))\n exit(-5)\n except Exception as e:\n self.logger.error(e)\n # Exit by following the logic: if user wanted to load the model but failed, then continuing the experiment makes no sense.\n exit(-6)\n\n # Finally, freeze the models (that the user wants to freeze).\n self.pipeline.freeze_models()\n\n # Log the model summaries.\n summary_str = self.pipeline.summarize_models_header()\n summary_str += self.pipeline.summarize_models()\n self.logger.info(summary_str)\n\n # Move the models in the pipeline to GPU.\n if self.app_state.args.use_gpu:\n self.pipeline.cuda() \n\n ################# OPTIMIZER ################# \n\n # Set the optimizer.\n optimizer_conf = dict(self.config_training['optimizer'])\n optimizer_type = optimizer_conf['type']\n del optimizer_conf['type']\n\n # Check if there are any models in the pipeline.\n if len(list(filter(lambda p: p.requires_grad, self.pipeline.parameters()))) == 0:\n self.logger.error('Cannot proceed with training, as there are no trainable models in the pipeline (or all models are frozen)')\n exit(-7)\n\n # Instantiate the optimizer and filter the model parameters based on if they require gradients.\n self.optimizer = getattr(torch.optim, optimizer_type)(\n filter(lambda p: p.requires_grad, self.pipeline.parameters()), **optimizer_conf)\n\n log_str = 'Optimizer:\\n' + '='*80 + \"\\n\"\n log_str += \" Type: \" + optimizer_type + \"\\n\"\n log_str += \" Params: {}\".format(optimizer_conf)\n\n self.logger.info(log_str)\n\n def add_statistics(self, stat_col):\n \"\"\"\n Calls base method and adds epoch statistics to ``StatisticsCollector``.\n\n :param stat_col: ``StatisticsCollector``.\n\n \"\"\"\n # Add loss and episode.\n super(Trainer, self).add_statistics(stat_col)\n\n # Add default statistics with formatting.\n stat_col.add_statistics('epoch', '{:02d}')\n\n\n def add_aggregators(self, stat_agg):\n \"\"\"\n Adds basic aggregators to to ``StatisticsAggregator`` and extends them with: epoch.\n\n :param stat_agg: ``StatisticsAggregator``.\n\n \"\"\"\n # Add basic aggregators.\n super(Trainer, self).add_aggregators(stat_agg)\n\n # add 'aggregators' for the epoch.\n stat_agg.add_aggregator('epoch', '{:02d}')\n\n\n def initialize_statistics_collection(self):\n \"\"\"\n - Initializes all ``StatisticsCollectors`` and ``StatisticsAggregators`` used by a given worker: \\\n\n - For training statistics (adds the statistics of the model & task),\n - For validation statistics (adds the statistics of the model & task).\n\n - Creates the output files (csv).\n\n \"\"\"\n # TRAINING.\n # Create statistics collector for training.\n self.training_stat_col = StatisticsCollector()\n self.add_statistics(self.training_stat_col)\n self.training.task.add_statistics(self.training_stat_col)\n self.pipeline.add_statistics(self.training_stat_col)\n # Create the csv file to store the training statistics.\n self.training_batch_stats_file = self.training_stat_col.initialize_csv_file(self.app_state.log_dir, 'training_statistics.csv')\n\n # Create statistics aggregator for training.\n self.training_stat_agg = StatisticsAggregator()\n self.add_aggregators(self.training_stat_agg)\n self.training.task.add_aggregators(self.training_stat_agg)\n self.pipeline.add_aggregators(self.training_stat_agg)\n # Create the csv file to store the training statistic aggregations.\n self.training_set_stats_file = self.training_stat_agg.initialize_csv_file(self.app_state.log_dir, 'training_set_agg_statistics.csv')\n\n # VALIDATION.\n # Create statistics collector for validation.\n self.validation_stat_col = StatisticsCollector()\n self.add_statistics(self.validation_stat_col)\n self.validation.task.add_statistics(self.validation_stat_col)\n self.pipeline.add_statistics(self.validation_stat_col)\n # Create the csv file to store the validation statistics.\n self.validation_batch_stats_file = self.validation_stat_col.initialize_csv_file(self.app_state.log_dir, 'validation_statistics.csv')\n\n # Create statistics aggregator for validation.\n self.validation_stat_agg = StatisticsAggregator()\n self.add_aggregators(self.validation_stat_agg)\n self.validation.task.add_aggregators(self.validation_stat_agg)\n self.pipeline.add_aggregators(self.validation_stat_agg)\n # Create the csv file to store the validation statistic aggregations.\n self.validation_set_stats_file = self.validation_stat_agg.initialize_csv_file(self.app_state.log_dir, 'validation_set_agg_statistics.csv')\n\n\n def finalize_statistics_collection(self):\n \"\"\"\n Finalizes the statistics collection by closing the csv files.\n\n \"\"\"\n # Close all files.\n self.training_batch_stats_file.close()\n self.training_set_stats_file.close()\n self.validation_batch_stats_file.close()\n self.validation_set_stats_file.close()\n\n\n def initialize_tensorboard(self):\n \"\"\"\n Initializes the TensorBoard writers, and log directories.\n\n \"\"\"\n # Create TensorBoard outputs - if TensorBoard is supposed to be used.\n if self.app_state.args.tensorboard is not None:\n from tensorboardX import SummaryWriter\n self.training_batch_writer = SummaryWriter(self.app_state.log_dir + '/training')\n self.training_stat_col.initialize_tensorboard(self.training_batch_writer)\n\n self.training_set_writer = SummaryWriter(self.app_state.log_dir + '/training_set_agg')\n self.training_stat_agg.initialize_tensorboard(self.training_set_writer)\n \n self.validation_batch_writer = SummaryWriter(self.app_state.log_dir + '/validation')\n self.validation_stat_col.initialize_tensorboard(self.validation_batch_writer)\n\n self.validation_set_writer = SummaryWriter(self.app_state.log_dir + '/validation_set_agg')\n self.validation_stat_agg.initialize_tensorboard(self.validation_set_writer)\n else:\n self.training_batch_writer = None\n self.training_set_writer = None\n self.validation_batch_writer = None\n self.validation_set_writer = None\n\n def finalize_tensorboard(self):\n \"\"\" \n Finalizes the operation of TensorBoard writers by closing them.\n \"\"\"\n # Close the TensorBoard writers.\n if self.training_batch_writer is not None:\n self.training_batch_writer.close()\n if self.training_set_writer is not None:\n self.training_set_writer.close()\n if self.validation_batch_writer is not None:\n self.validation_batch_writer.close()\n if self.validation_set_writer is not None:\n self.validation_set_writer.close()\n\n def validate_on_batch(self, valid_batch):\n \"\"\"\n Performs a validation of the model using the provided batch.\n\n Additionally logs results (to files, TensorBoard) and handles visualization.\n\n :param valid_batch: data batch generated by the task and used as input to the model.\n :type valid_batch: ``DataStreams``\n\n :return: Validation loss.\n\n \"\"\"\n # Turn on evaluation mode.\n self.pipeline.eval()\n # Empty the statistics collector.\n self.validation_stat_col.empty()\n\n # Compute the validation loss using the provided data batch.\n with torch.no_grad():\n # Forward pass.\n self.pipeline.forward(valid_batch)\n # Collect the statistics.\n self.collect_all_statistics(self.validation, self.pipeline, valid_batch, self.validation_stat_col)\n\n # Export collected statistics.\n self.export_all_statistics(self.validation_stat_col, '[Partial Validation]')\n\n def validate_on_set(self):\n \"\"\"\n Performs a validation of the model on the whole validation set, using the validation ``DataLoader``.\n\n Iterates over the entire validation set (through the `DataLoader``), aggregates the collected statistics \\\n and logs that to the console, csv and TensorBoard (if set).\n\n \"\"\"\n # Get number of samples.\n num_samples = len(self.validation)\n \n self.logger.info('Validating over the entire validation set ({} samples in {} episodes)'.format(\n num_samples, len(self.validation.dataloader)))\n\n # Turn on evaluation mode.\n self.pipeline.eval()\n\n # Reset the statistics.\n self.validation_stat_col.empty()\n\n # Remember global episode number.\n old_episode = self.app_state.episode\n\n with torch.no_grad():\n for ep, valid_batch in enumerate(self.validation.dataloader):\n\n self.app_state.episode = ep\n # Forward pass.\n self.pipeline.forward(valid_batch)\n # Collect the statistics.\n self.collect_all_statistics(self.validation, self.pipeline, valid_batch,\n self.validation_stat_col)\n\n # Revert to global episode number.\n self.app_state.episode = old_episode\n\n # Aggregate statistics for the whole set.\n self.aggregate_all_statistics(self.validation, self.pipeline,\n self.validation_stat_col, self.validation_stat_agg)\n\n # Export aggregated statistics.\n self.export_all_statistics(self.validation_stat_agg, '[Full Validation]')\n\n\nif __name__ == '__main__':\n print(\"The trainer.py file contains only an abstract base class. Please try to use the \\\nonline_trainer (mip-online-trainer) or offline_trainer (mip-offline-trainer) instead.\")\n","repo_name":"IBM/pytorchpipe","sub_path":"ptp/workers/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":23509,"program_lang":"python","lang":"en","doc_type":"code","stars":224,"dataset":"github-code","pt":"77"}
+{"seq_id":"40385547745","text":"from .words_cloud import *\r\nfrom .w2v_tsne import *\r\nfrom .data_ploting import *\r\nfrom .get_pdf import *\r\n\r\nimport nltk\r\nfrom nltk.corpus import stopwords\r\n\r\n\r\ndef main(p_data, b_data,\r\n p_gif_name,b_gif_name,\r\n b_wc_name,p_wc_name,\r\n b_wc_name_mask,p_wc_name_mask,\r\n b_pdf_name,p_pdf_name,\r\n b_site,p_site, b_2d_name1,\r\n b_2d_name2, p_2d_name1,\r\n p_2d_name2, b_sim_name, \r\n p_sim_name, theme,\r\n mask, img_promo):\r\n\r\n pubmed_sentences = get_sentences(p_data, \"pubmed\")\r\n biorxiv_sentences = get_sentences(b_data, \"bioarchiv\")\r\n biorxiv_model = Word2Vec(biorxiv_sentences,\r\n size=200,\r\n window=5,\r\n min_count=3, \r\n workers=multiprocessing.cpu_count())\r\n pubmed_model = Word2Vec(pubmed_sentences,\r\n size=200,\r\n window=5,\r\n min_count=3, \r\n workers=multiprocessing.cpu_count())\r\n\r\n biorxiv_embeddings, biorxiv_words = get_embedds_and_words(biorxiv_model)\r\n pubmed_embeddings, pubmed_words = get_embedds_and_words(pubmed_model)\r\n\r\n biorxiv_embeddings_2d = get_tsna_2d(biorxiv_embeddings)\r\n biorxiv_embeddings_3d = get_tsna_3d(biorxiv_embeddings)\r\n\r\n pubmed_embeddings_2d = get_tsna_2d(pubmed_embeddings)\r\n pubmed_embeddings_3d = get_tsna_3d(pubmed_embeddings)\r\n \r\n tsne_plot_2d(filename=b_2d_name1,\r\n label='Visualizing Embeddings using t-SNE',\r\n embeddings=pubmed_embeddings_2d,\r\n a=0.4)\r\n tsne_plot_2d(filename=b_2d_name2,\r\n label='Visualizing Embeddings using t-SNE',\r\n embeddings=pubmed_embeddings_2d,\r\n words=pubmed_words,\r\n a=0.4)\r\n \r\n tsne_plot_2d(filename=p_2d_name1,\r\n label='Similar words on the topic \"{theme}',\r\n embeddings=biorxiv_embeddings_2d, \r\n a=0.4)\r\n tsne_plot_2d(filename=p_2d_name2,\r\n label='Similar words on the topic \"{theme}',\r\n embeddings=biorxiv_embeddings_2d,\r\n words=biorxiv_words, \r\n a=0.4)\r\n\r\n tsne_plot_3d_gif(title=f'Visualizing Word Embeddings using t-SNE', \r\n label=f'Papers from the \"{b_site}\" on the topic -\"{theme}\"',\r\n embeddings=biorxiv_embeddings_3d, \r\n filename=b_gif_name)\r\n \r\n tsne_plot_3d_gif(title=f'Visualizing Word Embeddings using t-SNE', \r\n label= f'Papers from the \"{p_site}\" on the topic -\"{theme}\"',\r\n embeddings=pubmed_embeddings_3d, \r\n filename=p_gif_name)\r\n \r\n b_keys, b_embeddings_2d, b_word_clusters = get_2d_clusters(biorxiv_model, k_words=30, n_top_words=25)\r\n p_keys, p_embeddings_2d, p_word_clusters = get_2d_clusters(pubmed_model, k_words=30, n_top_words=25)\r\n\r\n tsne_plot_similar_words(f'Similar words from {b_site} on the topic {theme}',\r\n b_keys,\r\n b_embeddings_2d,\r\n b_word_clusters,\r\n 0.7,\r\n b_sim_name)\r\n tsne_plot_similar_words(f'Similar words from {p_site} on the topic {theme}',\r\n p_keys,\r\n p_embeddings_2d,\r\n p_word_clusters,\r\n 0.7,\r\n p_sim_name)\r\n \r\n biorxiv = makeWordCloud(10000000, \r\n b_data,\r\n b_wc_name)\r\n\r\n biorxiv_with_mask = makeWordCloud(10000000,\r\n b_data,\r\n b_wc_name_mask,\r\n mask=mask)\r\n \r\n pubmed = makeWordCloud(10000000, \r\n p_data,\r\n p_wc_name)\r\n\r\n pubmed_with_mask = makeWordCloud(10000000,\r\n p_data,\r\n p_wc_name_mask,\r\n mask=mask)\r\n \r\n make_pdf(site=p_site,\r\n MAP=p_data,\r\n pdf_name=p_pdf_name,\r\n wc_name=p_wc_name,\r\n wc_name_mask=p_wc_name_mask,\r\n name1_2d = p_2d_name1,\r\n name2_2d = p_2d_name2,\r\n sim_name=p_sim_name,\r\n gif_name=p_gif_name,\r\n img_promo=img_promo)\r\n\r\n make_pdf(site=b_site,\r\n MAP=b_data,\r\n pdf_name=b_pdf_name,\r\n wc_name=b_wc_name,\r\n wc_name_mask=b_wc_name_mask,\r\n name1_2d = b_2d_name1,\r\n name2_2d = b_2d_name2,\r\n sim_name=b_sim_name,\r\n gif_name=b_gif_name,\r\n img_promo=img_promo)\r\n\r\n print(\"Done!\")\r\n","repo_name":"OldBonhart/EDA-NLP-PubMed-and-bioRxiv","sub_path":"source/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"16948836554","text":"import csv\nimport os\nimport socket\nimport subprocess\nimport time\nimport paramiko\nfrom pprint import pprint\nfrom paramiko.ssh_exception import AuthenticationException, BadHostKeyException, SSHException\nfrom lensless.hardware.sensor import SensorOptions\nimport cv2\nfrom lensless.utils.image import print_image_info\nfrom lensless.utils.io import load_image\n\n\nimport logging\n\nlogging.getLogger(\"paramiko\").setLevel(logging.WARNING)\n\n\ndef capture(\n rpi_username,\n rpi_hostname,\n sensor,\n bayer,\n exp,\n fn=\"capture\",\n iso=100,\n config_pause=2,\n sensor_mode=\"0\",\n nbits_out=12,\n legacy=True,\n rgb=False,\n gray=False,\n nbits=12,\n down=None,\n awb_gains=None,\n rpi_python=\"~/LenslessPiCam/lensless_env/bin/python\",\n capture_script=\"~/LenslessPiCam/scripts/measure/on_device_capture.py\",\n verbose=False,\n output_path=None,\n **kwargs,\n):\n \"\"\"\n Capture image.\n\n Parameters\n ----------\n fn : str\n File name captured image.\n rpi_username : str\n Username of Raspberry Pi.\n rpi_hostname : str\n Hostname of Raspberry Pi.\n sensor : str\n Sensor name\n bayer : bool\n Whether to return bayer data (larger file size to transfer back).\n exp : int\n Exposure time in microseconds.\n iso : int\n ISO.\n config_pause : int\n Time to pause after configuring camera.\n sensor_mode : str\n Sensor mode.\n nbits_out : int\n Number of bits of output image.\n legacy : bool\n Whether to use legacy capture software of Raspberry Pi.\n rgb : bool\n Whether to capture RGB image.\n gray : bool\n Whether to capture grayscale image.\n nbits : int\n Number of bits of image.\n down : int\n Downsample factor.\n awb_gains : list\n AWB gains (red, blue).\n rpi_python : str\n Path to Python on Raspberry Pi.\n capture_script : str\n Path to capture script on Raspberry Pi.\n output_path : str\n Path to save image.\n verbose : bool\n Whether to print extra info.\n\n \"\"\"\n\n # check_username_hostname(rpi_username, rpi_hostname)\n assert sensor in SensorOptions.values(), f\"Sensor must be one of {SensorOptions.values()}\"\n\n # form command\n remote_fn = \"remote_capture\"\n pic_command = (\n f\"{rpi_python} {capture_script} sensor={sensor} bayer={bayer} fn={remote_fn} exp={exp} iso={iso} \"\n f\"config_pause={config_pause} sensor_mode={sensor_mode} nbits_out={nbits_out} \"\n f\"legacy={legacy} rgb={rgb} gray={gray} \"\n )\n if nbits > 8:\n pic_command += \" sixteen=True\"\n if down:\n pic_command += f\" down={down}\"\n if awb_gains:\n pic_command += f\" awb_gains=[{awb_gains[0]},{awb_gains[1]}]\"\n\n if verbose:\n print(f\"COMMAND : {pic_command}\")\n\n # take picture\n ssh = subprocess.Popen(\n [\"ssh\", \"%s@%s\" % (rpi_username, rpi_hostname), pic_command],\n shell=False,\n # stdout=DEVNULL,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n result = ssh.stdout.readlines()\n error = ssh.stderr.readlines()\n\n if error != [] and legacy: # new camera software seems to return error even if it works\n print(\"ERROR: %s\" % error)\n return\n if result == []:\n error = ssh.stderr.readlines()\n print(\"ERROR: %s\" % error)\n return\n else:\n result = [res.decode(\"UTF-8\") for res in result]\n result = [res for res in result if len(res) > 3]\n result_dict = dict()\n for res in result:\n _key = res.split(\":\")[0].strip()\n _val = \"\".join(res.split(\":\")[1:]).strip()\n result_dict[_key] = _val\n # result_dict = dict(map(lambda s: map(str.strip, s.split(\":\")), result))\n if verbose:\n print(\"COMMAND OUTPUT : \")\n pprint(result_dict)\n\n # copy over file\n if (\n \"RPi distribution\" in result_dict.keys()\n and \"bullseye\" in result_dict[\"RPi distribution\"]\n and not legacy\n ):\n\n if bayer:\n\n # copy over DNG file\n remotefile = f\"~/{remote_fn}.dng\"\n localfile = f\"{fn}.dng\"\n if output_path is not None:\n localfile = os.path.join(output_path, localfile)\n if verbose:\n print(f\"\\nCopying over picture as {localfile}...\")\n os.system(\n 'scp \"%s@%s:%s\" %s >/dev/null 2>&1'\n % (rpi_username, rpi_hostname, remotefile, localfile)\n )\n\n img = load_image(localfile, verbose=True, bayer=bayer, nbits_out=nbits_out)\n\n # print image properties\n print_image_info(img)\n\n # save as PNG\n png_out = f\"{fn}.png\"\n print(f\"Saving RGB file as: {png_out}\")\n cv2.imwrite(png_out, cv2.cvtColor(img, cv2.COLOR_RGB2BGR))\n\n else:\n\n remotefile = f\"~/{remote_fn}.png\"\n localfile = f\"{fn}.png\"\n if output_path is not None:\n localfile = os.path.join(output_path, localfile)\n if verbose:\n print(f\"\\nCopying over picture as {localfile}...\")\n os.system(\n 'scp \"%s@%s:%s\" %s >/dev/null 2>&1'\n % (rpi_username, rpi_hostname, remotefile, localfile)\n )\n\n img = load_image(localfile, verbose=True)\n\n # legacy software running on RPi\n else:\n # copy over file\n # more pythonic? https://stackoverflow.com/questions/250283/how-to-scp-in-python\n remotefile = f\"~/{remote_fn}.png\"\n localfile = f\"{fn}.png\"\n if output_path is not None:\n localfile = os.path.join(output_path, localfile)\n if verbose:\n print(f\"\\nCopying over picture as {localfile}...\")\n os.system(\n 'scp \"%s@%s:%s\" %s >/dev/null 2>&1'\n % (rpi_username, rpi_hostname, remotefile, localfile)\n )\n\n if rgb or gray:\n img = load_image(localfile, verbose=verbose)\n\n else:\n\n if not bayer:\n # red_gain = config.camera.red_gain\n # blue_gain = config.camera.blue_gain\n red_gain = awb_gains[0]\n blue_gain = awb_gains[1]\n else:\n red_gain = None\n blue_gain = None\n\n # load image\n if verbose:\n print(\"\\nLoading picture...\")\n\n img = load_image(\n localfile,\n verbose=True,\n bayer=bayer,\n blue_gain=blue_gain,\n red_gain=red_gain,\n nbits_out=nbits_out,\n )\n\n # write RGB data\n if not bayer:\n cv2.imwrite(localfile, cv2.cvtColor(img, cv2.COLOR_RGB2BGR))\n\n return localfile, img\n\n\ndef display(\n fp,\n rpi_username,\n rpi_hostname,\n screen_res,\n brightness=100,\n rot90=0,\n pad=0,\n vshift=0,\n hshift=0,\n verbose=False,\n **kwargs,\n):\n \"\"\"\n Display image on a screen.\n\n Assumes setup described here: https://lensless.readthedocs.io/en/latest/measurement.html#remote-display\n\n Parameters\n ----------\n fp : str\n File path to image.\n rpi_username : str\n Username of Raspberry Pi.\n rpi_hostname : str\n Hostname of Raspberry Pi.\n screen_res : tuple\n Screen resolution of Raspberry Pi.\n \"\"\"\n\n # assumes that `LenslessPiCam` is in home directory and environment inside `LenslessPiCam`\n rpi_python = \"~/LenslessPiCam/lensless_env/bin/python\"\n script = \"~/LenslessPiCam/scripts/measure/prep_display_image.py\"\n remote_tmp_file = \"~/tmp_display.png\"\n display_path = \"~/LenslessPiCam_display/test.png\"\n\n os.system(\n 'scp %s \"%s@%s:%s\" >/dev/null 2>&1' % (fp, rpi_username, rpi_hostname, remote_tmp_file)\n )\n\n # run script on Raspberry Pi to prepare image to display\n prep_command = f\"{rpi_python} {script} --fp {remote_tmp_file} \\\n --pad {pad} --vshift {vshift} --hshift {hshift} --screen_res {screen_res[0]} {screen_res[1]} \\\n --brightness {brightness} --rot90 {rot90} --output_path {display_path} \"\n if verbose:\n print(f\"COMMAND : {prep_command}\")\n subprocess.Popen(\n [\"ssh\", \"%s@%s\" % (rpi_username, rpi_hostname), prep_command],\n shell=False,\n # stdout=DEVNULL\n )\n\n\ndef check_username_hostname(username, hostname, timeout=10):\n\n assert username is not None, \"Username must be specified\"\n assert hostname is not None, \"Hostname must be specified\"\n\n client = paramiko.client.SSHClient()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\n try:\n # with suppress_stdout():\n client.connect(hostname, username=username, timeout=timeout)\n except (BadHostKeyException, AuthenticationException, SSHException, socket.error) as e:\n raise ValueError(f\"Could not connect to {username}@{hostname}\\n{e}\")\n\n return client\n\n\ndef get_distro():\n \"\"\"\n Get current OS distribution.\n Returns\n -------\n result : str\n Name and version of OS.\n \"\"\"\n # https://majornetwork.net/2019/11/get-linux-distribution-name-and-version-with-python/\n RELEASE_DATA = {}\n with open(\"/etc/os-release\") as f:\n reader = csv.reader(f, delimiter=\"=\")\n for row in reader:\n if row:\n RELEASE_DATA[row[0]] = row[1]\n if RELEASE_DATA[\"ID\"] in [\"debian\", \"raspbian\"]:\n with open(\"/etc/debian_version\") as f:\n DEBIAN_VERSION = f.readline().strip()\n major_version = DEBIAN_VERSION.split(\".\")[0]\n version_split = RELEASE_DATA[\"VERSION\"].split(\" \", maxsplit=1)\n if version_split[0] == major_version:\n # Just major version shown, replace it with the full version\n RELEASE_DATA[\"VERSION\"] = \" \".join([DEBIAN_VERSION] + version_split[1:])\n return f\"{RELEASE_DATA['NAME']} {RELEASE_DATA['VERSION']}\"\n\n\ndef set_mask_sensor_distance(\n distance, rpi_username, rpi_hostname, motor=1, max_distance=16, timeout=5\n):\n \"\"\"\n Set the distance between the mask and sensor.\n\n This functions assumes that `StepperDriver `_ is installed.\n is downloaded on the Raspberry Pi.\n\n Parameters\n ----------\n distance : float\n Distance in mm. Positive values move the mask away from the sensor.\n rpi_username : str\n Username of Raspberry Pi.\n rpi_hostname : str\n Hostname of Raspberry Pi.\n \"\"\"\n\n client = check_username_hostname(rpi_username, rpi_hostname)\n assert motor in [0, 1]\n assert distance >= 0, \"Distance must be non-negative\"\n assert distance <= max_distance, f\"Distance must be less than {max_distance} mm\"\n\n # assumes that `StepperDriver` is in home directory\n rpi_python = \"python3\"\n script = \"~/StepperDriver/Python/serial_motors.py\"\n\n # reset to zero\n print(\"Resetting to zero distance...\")\n try:\n command = f\"{rpi_python} {script} {motor} REV {max_distance * 1000}\"\n _stdin, _stdout, _stderr = client.exec_command(command, timeout=timeout)\n except socket.timeout: # socket.timeout\n pass\n\n client.close()\n time.sleep(5) # TODO reduce this time\n client = check_username_hostname(rpi_username, rpi_hostname)\n\n # set to desired distance\n if distance != 0:\n print(f\"Setting distance to {distance} mm...\")\n distance_um = distance * 1000\n if distance_um >= 0:\n command = f\"{rpi_python} {script} {motor} FWD {distance_um}\"\n else:\n command = f\"{rpi_python} {script} {motor} REV {-1 * distance_um}\"\n print(f\"COMMAND : {command}\")\n try:\n _stdin, _stdout, _stderr = client.exec_command(command, timeout=timeout)\n print(_stdout.read().decode())\n except socket.timeout: # socket.timeout\n client.close()\n\n client.close()\n","repo_name":"LCAV/LenslessPiCam","sub_path":"lensless/hardware/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":11917,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"77"}
+{"seq_id":"27083072613","text":"# SPDX-License-Identifier: Apache-2.0\n# © (2023) ETH Zurich and other contributors, see AUTHORS.txt for details\n\n\"\"\"\nThis module provides utility functions and classes for beam search when using dynamic ensemble decoding. It includes\nBeamHypotheses class, create_attention_mask function, expand_input_dim_to_num_beams function, and other utility\nfunctions. The module also contains an implementation of ScoreReduceStrategy abstract class and its subclasses for\ndifferent score reducing strategies, which determine in DynE how the outputs of the models are combined.\n\n\"\"\"\nfrom abc import ABC, abstractmethod\nfrom typing import Optional, Dict, List\n\nimport torch\n\n\nclass BeamHypotheses(object):\n def __init__(self, num_beams: int, max_length: int, length_penalty: int, early_stopping: bool):\n \"\"\"\n A class for maintaining n-best list of hypotheses during beam search.\n \"\"\"\n self.max_length = max_length - 1 # ignoring bos_token\n self.length_penalty = length_penalty\n self.early_stopping = early_stopping\n self.num_beams = num_beams\n self.beams = []\n self.worst_score = 1e9\n\n def __len__(self) -> int:\n \"\"\"\n Number of hypotheses in the list.\n \"\"\"\n return len(self.beams)\n\n def add(self, hyp: torch.Tensor, sum_logprobs: float, metadata: Optional[List] = None):\n \"\"\"\n Add a new hypothesis to the list.\n \"\"\"\n score = sum_logprobs / len(hyp) ** self.length_penalty\n if len(self) < self.num_beams or score > self.worst_score:\n self.beams.append((score, hyp, metadata))\n if len(self) > self.num_beams:\n sorted_scores = sorted([(s, idx) for idx, (s, _, _) in enumerate(self.beams)])\n del self.beams[sorted_scores[0][1]]\n self.worst_score = sorted_scores[1][0]\n else:\n self.worst_score = min(score, self.worst_score)\n\n def is_done(self, best_sum_logprobs: float, cur_len: Optional[int] = None) -> bool:\n \"\"\"\n If there are enough hypotheses and that none of the hypotheses being generated\n can become better than the worst one in the heap, then we are done with this sentence.\n \"\"\"\n\n if len(self) < self.num_beams:\n return False\n elif self.early_stopping:\n return True\n else:\n if cur_len is None:\n cur_len = self.max_length\n cur_score = best_sum_logprobs / cur_len ** self.length_penalty\n ret = self.worst_score >= cur_score\n return ret\n\n\ndef create_attention_mask(input_ids: torch.Tensor, pad_token_id: int) -> torch.Tensor:\n if (pad_token_id is not None) and (pad_token_id in input_ids):\n attention_mask = input_ids.ne(pad_token_id).long()\n else:\n attention_mask = input_ids.new_ones(input_ids.shape)\n\n return attention_mask\n\n\ndef expand_input_dim_to_num_beams(input_tensor: torch.Tensor, input_ids_len: int, num_beams: int, batch_size: int,\n effective_batch_mult: int,\n effective_batch_size: int) -> torch.Tensor:\n expanded_input = input_tensor.unsqueeze(1).expand(batch_size, effective_batch_mult * num_beams, input_ids_len)\n\n expanded_input = expanded_input.contiguous().view(\n effective_batch_size * num_beams, input_ids_len\n ) # shape: (batch_size * num_return_sequences * num_beams, cur_len)\n\n return expanded_input\n\n\ndef apply_heuristics_to_logits(state: Dict) -> Dict:\n # repetition penalty (from CTRL paper https://arxiv.org/abs/1909.05858)\n if state['repetition_penalty'] != 1.0:\n enforce_repetition_penalty(\n state['next_token_logits'],\n state['batch_size'],\n state['num_beams'],\n state['input_ids'],\n state['repetition_penalty']\n )\n\n if state['temperature'] != 1.0:\n state['next_token_logits'] = state['next_token_logits'] / state['temperature']\n\n return state\n\n\ndef calc_banned_ngram_tokens(prev_input_ids: torch.Tensor, num_hypos: int, no_repeat_ngram_size: int,\n cur_len: int) -> List:\n # Copied from fairseq for no_repeat_ngram in beam_search\n if cur_len + 1 < no_repeat_ngram_size:\n # return no banned tokens if we haven't generated no_repeat_ngram_size tokens yet\n return [[] for _ in range(num_hypos)]\n generated_ngrams = [{} for _ in range(num_hypos)]\n for idx in range(num_hypos):\n gen_tokens = prev_input_ids[idx].tolist()\n generated_ngram = generated_ngrams[idx]\n for ngram in zip(*[gen_tokens[i:] for i in range(no_repeat_ngram_size)]):\n prev_ngram_tuple = tuple(ngram[:-1])\n generated_ngram[prev_ngram_tuple] = generated_ngram.get(prev_ngram_tuple, []) + [ngram[-1]]\n\n def _get_generated_ngrams(hypo_idx):\n # Before decoding the next token, prevent decoding of ngrams that have already appeared\n start_idx = cur_len + 1 - no_repeat_ngram_size\n ngram_idx = tuple(prev_input_ids[hypo_idx, start_idx:cur_len].tolist())\n return generated_ngrams[hypo_idx].get(ngram_idx, [])\n\n banned_tokens = [_get_generated_ngrams(hypo_idx) for hypo_idx in range(num_hypos)]\n return banned_tokens\n\n\ndef calc_banned_bad_words_ids(prev_input_ids: torch.Tensor, bad_words_ids: List) -> List:\n banned_tokens = []\n\n def _tokens_match(prev_tokens, tokens):\n if len(tokens) == 0:\n # if bad word tokens is just one token always ban it\n return True\n if len(tokens) > len(prev_input_ids):\n # if bad word tokens are longer then prev input_ids they can't be equal\n return False\n\n if prev_tokens[-len(tokens):] == tokens:\n # if tokens match\n return True\n else:\n return False\n\n for prev_input_ids_slice in prev_input_ids:\n banned_tokens_slice = []\n\n for banned_token_seq in bad_words_ids:\n assert len(banned_token_seq) > 0, \"Banned words token sequences {} cannot have an empty list\".format(\n bad_words_ids\n )\n\n if _tokens_match(prev_input_ids_slice.tolist(), banned_token_seq[:-1]) is False:\n # if tokens do not match continue\n continue\n\n banned_tokens_slice.append(banned_token_seq[-1])\n\n banned_tokens.append(banned_tokens_slice)\n\n return banned_tokens\n\n\ndef enforce_repetition_penalty(lprobs: torch.Tensor, batch_size: int, num_beams: int, prev_output_tokens: torch.Tensor,\n repetition_penalty: float):\n \"\"\"repetition penalty (from CTRL paper https://arxiv.org/abs/1909.05858). \"\"\"\n for i in range(batch_size * num_beams):\n for previous_token in set(prev_output_tokens[i].tolist()):\n # if score < 0 then repetition penalty has to multiplied to reduce the previous token probability\n if lprobs[i, previous_token] < 0:\n lprobs[i, previous_token] *= repetition_penalty\n else:\n lprobs[i, previous_token] /= repetition_penalty\n\n\nclass ScoreReduceStrategy(ABC):\n subclasses = {}\n\n @abstractmethod\n def reduce_score(self, component_states: List[Dict]) -> torch.Tensor:\n pass\n\n @classmethod\n def register_subclass(cls, score_reduce_type):\n def decorator(subclass):\n cls.subclasses[score_reduce_type] = subclass\n return subclass\n\n return decorator\n\n @classmethod\n def get_score_reduce_strategy(cls, score_reduce_type):\n if score_reduce_type not in cls.subclasses:\n raise ValueError('Bad score reduce type {}'.format(score_reduce_type))\n\n return cls.subclasses[score_reduce_type]()\n\n\n@ScoreReduceStrategy.register_subclass(\"Single_document_sum\")\nclass SingleDocumentScoreReduceStrategy(ScoreReduceStrategy):\n def reduce_score(self, component_states: List[Dict]) -> torch.Tensor:\n num_articles = len(component_states)\n assert num_articles == 1\n return component_states[0]['scores']\n\n\n@ScoreReduceStrategy.register_subclass(\"DynE\")\nclass AverageScoreReduceStrategy(ScoreReduceStrategy):\n def reduce_score(self, component_states: List[Dict]) -> torch.Tensor:\n stacked_scores = torch.stack([s['scores'] for s in component_states])\n return torch.mean(stacked_scores, dim=0)\n\n\n@ScoreReduceStrategy.register_subclass(\"product\")\nclass ProductScoreReduceStrategy(ScoreReduceStrategy):\n def reduce_score(self, component_states: List[Dict]) -> torch.Tensor:\n stacked_scores = torch.stack([s['scores'] for s in component_states])\n return -torch.prod(torch.abs(stacked_scores), dim=0)\n\n\n@ScoreReduceStrategy.register_subclass(\"max\")\nclass MaxScoreReduceStrategy(ScoreReduceStrategy):\n def reduce_score(self, component_states: List[Dict]) -> torch.Tensor:\n stacked_scores = torch.stack([s['scores'] for s in component_states])\n return torch.max(stacked_scores, dim=0)[0]\n\n\n@ScoreReduceStrategy.register_subclass(\"H_min\")\nclass MinEntropyScoreReduceStrategy(ScoreReduceStrategy):\n def reduce_score(self, component_states: List[Dict]) -> torch.Tensor:\n stacked_entropy = torch.stack([s['entropy'] for s in component_states])\n _, min_entropy_per_beam_indices = torch.min(stacked_entropy, dim=0)\n min_entropy_scores_per_beam = torch.stack(\n [component_states[article_id]['scores'][beam_id, :] for beam_id, article_id in\n enumerate(min_entropy_per_beam_indices)])\n return min_entropy_scores_per_beam\n\n\n@ScoreReduceStrategy.register_subclass(\"H_th\")\nclass ThresholdMaxProbabilityScoreReduceStrategy(ScoreReduceStrategy):\n \"\"\"\n This strategy averages the scores for articles where the max_prob is below the threshold(0.35) and selects the\n article with maximum prob otherwise.\n \"\"\"\n max_prob_threshold = 0.35\n\n def get_max_prob_scores(self, component_states: List[Dict]) -> torch.Tensor:\n stacked_max_prob = torch.stack([s['max_prob'] for s in component_states])\n _, max_prob_per_beam_indices = torch.max(stacked_max_prob, dim=0)\n max_prob_scores_per_beam = torch.stack(\n [component_states[article_id]['scores'][beam_id, :] for beam_id, article_id in\n enumerate(max_prob_per_beam_indices)])\n return max_prob_scores_per_beam\n\n def get_mean_prob_scores_for_beam(self, component_states: List[Dict], beam_id: int) -> torch.Tensor:\n mean_prob_scores_for_beam = torch.stack([\n component_state['scores'][beam_id, :] for component_state in component_states])\n\n mean_prob_scores_for_beam = torch.mean(mean_prob_scores_for_beam, dim=0)\n return mean_prob_scores_for_beam\n\n def reduce_score(self, component_states: List[Dict]) -> torch.Tensor:\n num_articles = len(component_states)\n assert num_articles > 0\n if num_articles == 1:\n return component_states[0]['scores']\n\n num_beams = component_states[0]['num_beams']\n vocab_size = component_states[0]['vocab_size']\n device = component_states[0]['scores'].device\n reduced_scores = torch.zeros((num_beams, vocab_size), device=device)\n\n prob_above_threshold = torch.stack(\n [s['max_prob'] > self.max_prob_threshold for s in component_states])\n\n max_prob_scores_per_beam = self.get_max_prob_scores(component_states)\n\n for beam_id in range(num_beams):\n prob_above_threshold_indices_for_beam = prob_above_threshold[:, beam_id].nonzero()\n if len(prob_above_threshold_indices_for_beam) == 0:\n # set scores equal to the mean of input article scores if all max_probs < threshold\n reduced_scores[beam_id, :] = self.get_mean_prob_scores_for_beam(component_states, beam_id)\n else:\n # set scores equal to the input article score with the highest max prob\n reduced_scores[beam_id, :] = max_prob_scores_per_beam[beam_id, :]\n\n return reduced_scores\n","repo_name":"mediatechnologycenter/Entropy-basedMDS","sub_path":"entropy_based_sampling/decoding_utils.py","file_name":"decoding_utils.py","file_ext":"py","file_size_in_byte":12071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"29302467989","text":"#Cajero Automático\nfrom time import sleep\nsaldo_cajero = 1000000\nsaldo_cuenta = 100000\nusuario = str(int(input(\"Ingrese el usuario: \")))\nclave = str(int(input(\"Ingrese la contraseña: \")))\nwhile True:\n if usuario == \"10334151\" and clave == \"1803\":\n print(\"Usuario y contraseña correctos\")\n sleep(1)\n monto_a_retirar = int(input(\"Ingrese el monto a retirar: \"))\n if monto_a_retirar>saldo_cuenta and monto_a_retirar>saldo_cajero:\n print(\"monto no permitido\")\n break\n if monto_a_retirar1:\n if counter[0][1] == counter[1][1]:\n if counter[0][0] > counter[1][0]:\n print(counter[0][0])\n else:\n print(counter[1][0])\n else:\n print(counter[0][0])\nelse:\n print(l[0])\nprint(max(l)-min(l))\n","repo_name":"galug/algorithm","sub_path":"python_algorithm/2108.py","file_name":"2108.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"20542049779","text":"import random\n\n# import numpy as np\n\nfrom .GradientDescent import gradient_descent_op\n\nfrom .ParticleVectorized import Particle, Globals\n\nimport json\n\nepsilon = 0.00000001\n\n\ndef f(x):\n # simple function\n return 2 * x[0] ** 2 - 8 * x[0] + 1\n\n\ndef PSO(\n objective_function,\n n_particles,\n iterations,\n n_param,\n inertia_strategy,\n guess_random_range,\n gradient_coef=0,\n seed=random.randint(0, 1241231),\n use_random_gradients=False,\n save_path = None,\n):\n params = {\n \"obj_f\": objective_function,\n \"n_par\": n_particles,\n \"iter\": iterations,\n \"in_srat\": inertia_strategy,\n \"rng\": guess_random_range,\n \"grd_coef\": gradient_coef,\n \"seed\": seed,\n \"rnd_grad\": use_random_gradients,\n }\n\n # initialize the particles\n particles = []\n # np.random.seed(seed)\n random.seed(seed)\n\n globals = Globals(n_param, guess_random_range)\n for i in range(n_particles):\n particle = Particle(\n globals,\n objective_function,\n guess_random_range,\n gradient_coef,\n use_random_gradients,\n )\n particles.append(particle)\n\n positions = []\n global_best_history = []\n\n convergence_iteration = 1000\n\n for i in range(iterations):\n positions.append([])\n for particle in particles:\n w = inertia_strategy.get_inertia(i, particles)\n particle.update(w)\n positions[i].append(\n {\n \"position\": particle.position.tolist(),\n \"velocity\": particle.velocity.tolist(),\n }\n )\n global_best_history.append(globals.best_value)\n if globals.best_value < epsilon and convergence_iteration > i:\n convergence_iteration = i\n\n gd_positions = gradient_descent_op(\n iterations,\n objective_function,\n )\n file_name = (\n json.dumps(params, default=str)\n .replace(\" \", \"\")\n .replace('\"', \"\")\n .replace(\"{\", \"\")\n .replace(\"}\", \"\")\n )\n if save_path is None:\n save_path = \"./plot/data/\"\n else :\n save_path = save_path + \"plot/data/\"\n \n file_name = f\"{save_path}{objective_function.name}.json\"\n\n with open(\n file_name,\n \"w\",\n ) as f:\n json.dump(positions, f, indent=4)\n\n gd_file_name = f\"{save_path}{objective_function.name}_gd.json\"\n\n with open(\n gd_file_name,\n \"w\",\n ) as f:\n json.dump([[{\"position\": p}] for p in gd_positions], f, indent=4)\n\n print(f\"found minimum of {objective_function.name}: {globals.best_value} at {globals.best_position}\")\n return (\n global_best_history,\n globals.best_value,\n globals.best_position,\n convergence_iteration,\n )\n\n","repo_name":"oalee/PSO","sub_path":"pso/models/pso/PSO.py","file_name":"PSO.py","file_ext":"py","file_size_in_byte":2816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"7115998920","text":"import numpy as np\nimport cv2\nimport scipy\nimport scipy.signal\n\n\ndef add_salt_and_pepper(image):\n s_vs_p = 0.5\n amount = 0.004\n out = np.copy(image)\n # Salt mode\n num_salt = np.ceil(amount * image.size * s_vs_p)\n coords = [np.random.randint(0, i - 1, int(num_salt))\n for i in image.shape]\n out[coords] = 1\n\n # Pepper mode\n num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))\n coords = [np.random.randint(0, i - 1, int(num_pepper))\n for i in image.shape]\n out[coords] = 0\n return out\n\n\ndef do():\n image = cv2.imread('raw_images/dog.png')\n gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n image = add_salt_and_pepper(gray_image)\n\n cv2.imwrite('processed_images/dog_salt_pepper.png', image)\n\n convolution = scipy.signal.medfilt(image, kernel_size=5)\n\n cv2.imwrite('processed_images/median_dog.png', convolution)\n\nif __name__ == '__main__':\n do()","repo_name":"harshmathur1990/image-processing-learn","sub_path":"median_filter.py","file_name":"median_filter.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"13645153514","text":"class FacilityListSerializer(serializers.ModelSerializer):\n id = serializers.UUIDField(source=\"external_id\", read_only=True)\n local_body_object = LocalBodySerializer(source=\"local_body\", read_only=True)\n facility_type = serializers.SerializerMethodField()\n read_cover_image_url = serializers.CharField(read_only=True)\n features = serializers.MultipleChoiceField(choices=FEATURE_CHOICES)\n patient_count = serializers.SerializerMethodField()\n bed_count = serializers.SerializerMethodField()\n phone_number = serializers.CharField(read_only=True)\n\n\n def get_facility_type(self, facility):\n return {\n \"id\": facility.facility_type,\n \"name\": facility.get_facility_type_display(),\n }\n\n class Meta:\n model = Facility\n fields = (\n \"id\",\n \"name\",\n \"local_body_object\",\n \"facility_type\",\n \"read_cover_image_url\",\n \"features\",\n \"patient_count\",\n \"bed_count\",\n \"phone_number\",\n )\n\n def get_queryset(self):\n queryset = super().get_queryset()\n queryset = queryset.annotate(\n bed_count=Count('beds'),\n patient_count=Count('patientregistrations', filter=Q(patientregistrations__is_active=True))\n )\n return queryset\n","repo_name":"yaswanthsaivendra/listSerializers_care","sub_path":"module6_facility/FacilityListSerializer.py","file_name":"FacilityListSerializer.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"6100513096","text":"\"\"\"\r\n6.\tDiseñe un algoritmo para convertir una cantidad dada en pulgadas a pies, yardas y centímetros. Se sabe que:\r\n1 yarda = 3 pies\r\n1 pie = 12 pulgadas\r\n1 pulgada = 2.54 centímetros\r\n1 metro = 100 centímetros\r\n\"\"\"\r\ncp=float(input(\"Ingrese cantidad a convertir: \"))\r\nunidad = input(\"Especifique la unidad del valor: pul, yar, pie, m,cm: \")\r\n\r\na_unidad = input(\"Especifique a que unidad desea convertir pul, yar, pie, m,cm: \")\r\n\r\nif unidad == \"yar\" and a_unidad == \"pies\":\r\n resultado = cp*3\r\n print(resultado,'pies')\r\n\r\nelif unidad == \"yar\" and a_unidad == \"pul\":\r\n resultado = cp*3*12\r\n print(resultado,'pulgadas')\r\n\r\nelif unidad == \"yar\" and a_unidad == \"cm\":\r\n resultado = cp*3*12*2.54\r\n print(resultado,'cm')\r\n\r\nelif unidad == \"yar\" and a_unidad == \"m\":\r\n resultado = (cp*3*12*2.54)/100\r\n print(resultado,'m')\r\n\r\nelif unidad == \"pie\" and a_unidad == \"yar\":\r\n resultado = (cp/3)\r\n print(resultado,'yardas')\r\n\r\nelif unidad == \"pie\" and a_unidad == \"pul\":\r\n resultado = cp*12\r\n print(resultado, 'pulgadas')\r\n \r\nelif unidad == \"pie\" and a_unidad == \"cm\":\r\n resultado = (cp*12*2.54)\r\n print(resultado, 'centimetros') \r\n \r\nelif unidad == \"pie\" and a_unidad == \"m\":\r\n resultado = cp*12*2.54/100\r\n print(resultado,'metros')\r\nelif unidad == \"m\" and a_unidad==\"cm\":\r\n resultado=(cp*100)\r\n print(\"el resultado de la conversion es:\",resultado)\r\n\r\nelse:\r\n print(\"Hey, ingresaste mal alguna unidad.\")","repo_name":"darek20sam/Arduino-y-python","sub_path":"Python telegram profe Harold/reuniondomingoe6.py","file_name":"reuniondomingoe6.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"20182991338","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef minmod(p, q):\n if p * q > 0:\n return np.sign(p) * min(abs(p), abs(q))\n return 0\n\n\ndef ENO(u, Δt, Δx):\n v = np.copy(u)\n v[2:-1] = u[2:-1] - (\n (Δt * ((u[2:-1] + u[1:-2]) / 2)) * (((u[2:-1] - u[1:-2]) / Δx) + (Δx / 2) * np.vectorize(minmod)(\n (u[3:] - 2 * u[2:-1] + u[1:-2]) / (Δx ** 2), (u[2:-1] - 2 * u[1:-2] + u[:-3]) / (Δx ** 2))))\n v[0] = 1.0\n v[-1] = 0.0\n return v\n\n\n# Define the grid parameters\nL = 5.0 # Length of the domain in the x direction\nΔx = 0.025 # Grid spacing in the x direction\nNx = int(L / Δx) # Number of grid points in the x direction\n\nsim_time = 2.0 # Total simulation time\nΔt = Δx # time step size\nnum_time_step = round(sim_time / Δt) # Number of time steps\n\n# Define the initial condition\nx_values = np.linspace(0, L, Nx)\nu = np.zeros(Nx)\nu[x_values < 0.25] = 1\nu[(0.25 <= x_values) & (x_values <= 1.25)] = 1.25 - x_values[(0.25 <= x_values) & (x_values <= 1.25)]\n\n# Plot the initial condition\nplt.plot(x_values, u, label=\"Initial Condition\")\n\n# Run the simulation\nfor j in range(num_time_step):\n u = ENO(u, Δt, Δx)\n\n# Numerical\nplt.plot(x_values, u, label=f\"After {sim_time} seconds (numerically)\")\n\n# Run the simulation\nfor j in range(num_time_step):\n u = ENO(u, Δt, Δx)\n\n# Numerical\nplt.plot(x_values, u, label=f\"After {2 * sim_time} seconds (numerically)\")\n\n# Run the simulation\nfor j in range(num_time_step):\n u = ENO(u, Δt, Δx)\n\n# Numerical\nplt.plot(x_values, u, label=f\"After {3 * sim_time} seconds (numerically)\")\n\nplt.xlabel(\"x\")\nplt.ylabel(\"Amplitude\")\nplt.title(\"ENO\")\nplt.legend()\nplt.grid()\nplt.show()\n","repo_name":"Sauroncool/CFD_Techniques","sub_path":"FDM and FVM/Second Order ENO (FDM).py","file_name":"Second Order ENO (FDM).py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"226860431","text":"import requests\nimport csv\nimport sys\n\ndef request_until_succeed(url):\n r = requests.get(url)\n success = False\n while success is False:\n try:\n if r.status_code == 200:\n success = True\n except Exception as e:\n print(e)\n time.sleep(5)\n\n print(\"Error for URL %s: %s\" % (url, datetime.datetime.now()))\n print(\"Retrying.\")\n\n return r.text\n\ndef open_csv_w(filename):\n \"\"\"Open a csv file in proper mode depending on Python verion.\"\"\"\n return(open(filename, mode='wb') if sys.version_info[0] == 2 else\n open(filename, mode='w+', newline=''))\n","repo_name":"buzzfeed-openlab/big-picture","sub_path":"scripts/scripts/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"77"}
+{"seq_id":"74552830648","text":"\n\nimport os\nimport csv\nimport uuid\nimport random\n\nfrom sqlalchemy.orm.exc import NoResultFound\n\nfrom chintal.db import clear_database\nfrom chintal.db import commit_metadata\nfrom chintal.db import with_db\nfrom chintal.models import Person\nfrom chintal.models import Attorney\nfrom chintal.models import Case\nfrom chintal.models import State\nfrom chintal.models import CaseParty\nfrom chintal.models import PersonAssociation\nfrom chintal.models import AttorneyAssociation\n\nfrom chintal.controller import get_all\n\n\n@with_db\ndef generate_states(session=None):\n with open(os.path.join('sample_data', 'states.csv')) as csvfile:\n reader = csv.reader(csvfile)\n for name, abbrev in reader:\n try:\n _ = session.query(State).filter_by(\n code=abbrev, name=name).one()\n continue\n except NoResultFound:\n pass\n state = State(code=abbrev, name=name)\n session.add(state)\n session.flush()\n\n\n@with_db\ndef _get_states(session=None):\n return get_all(item_type=State, session=session)\n\n\ndef _get_names():\n fn, ln = [], []\n with open(os.path.join('sample_data', 'names.csv')) as csvfile:\n reader = csv.reader(csvfile)\n for first_name, last_name in reader:\n fn.append(first_name), ln.append(last_name)\n return fn, ln\n\n\nfirst_names, last_names = _get_names()\n\n\ndef _get_random_name():\n return random.choice(first_names), random.choice(last_names)\n\n\ndef _generate_attorneys():\n _rval = []\n for _ in range(1000):\n o = Attorney(first_name=random.choice(first_names),\n last_name=random.choice(last_names),\n bar_id=uuid.uuid4(),\n state_id=random.choice(states).id)\n _rval.append(o)\n return _rval\n\n\ndef _generate_people():\n _rval = []\n for _ in range(5000):\n o = Person(first_name=random.choice(first_names),\n last_name=random.choice(last_names))\n _rval.append(o)\n return _rval\n\n\ndef _choose_attorneys(state):\n na = random.randint(1, 2)\n candidates = [x for x in attorneys if x.state_id == state.id]\n return random.sample(candidates, na)\n\n\n@with_db\ndef generate_cases(session=None):\n for _ in range(100):\n state = random.choice(states)\n\n npl = random.randint(1, 2)\n ndef = random.randint(1, 2)\n\n # This is a very dumb approach that will result in all manner\n # of absurdities.\n\n _people = random.sample(people, npl + ndef)\n _plaintiffs = _people[:npl]\n _defendants = _people[npl:]\n\n plaintiff = CaseParty()\n session.add(plaintiff)\n defendant = CaseParty()\n session.add(defendant)\n\n for person in _plaintiffs:\n session.add(person)\n pa = PersonAssociation(person=person, case_party=plaintiff)\n session.add(pa)\n\n _pattorneys = _choose_attorneys(state)\n for _attorney in _pattorneys:\n session.add(_attorney)\n aa = AttorneyAssociation(attorney=_attorney,\n person_case=pa)\n session.add(aa)\n\n for person in _defendants:\n session.add(person)\n pa = PersonAssociation(person=person, case_party=defendant)\n session.add(pa)\n\n _pattorneys = _choose_attorneys(state)\n for _attorney in _pattorneys:\n session.add(_attorney)\n aa = AttorneyAssociation(attorney=_attorney,\n person_case=pa)\n session.add(aa)\n\n if len(_plaintiffs) > 1:\n pm = ' et. al.'\n else:\n pm = ''\n\n if len(_defendants) > 1:\n dm = ' et. al.'\n else:\n dm = ''\n\n title = \"{0}{1} v. {2}{3}\".format(_plaintiffs[0].name, pm,\n _defendants[0].name, dm)\n case = Case(\n title=title,\n case_number=uuid.uuid4(),\n state_id=state.id,\n plaintiff=plaintiff,\n defendant=defendant,\n )\n # print(\"CASE\", title)\n session.add(case)\n session.commit()\n session.flush()\n\n\nif __name__ == '__main__':\n clear_database()\n commit_metadata()\n generate_states()\n states = _get_states()\n attorneys = _generate_attorneys()\n people = _generate_people()\n generate_cases()\n\n","repo_name":"chintal/test-devops","sub_path":"app/populate.py","file_name":"populate.py","file_ext":"py","file_size_in_byte":4481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"18092032818","text":"from copy import deepcopy\n\nimport attr\nfrom navmazing import NavigateToAttribute\nfrom navmazing import NavigateToSibling\nfrom widgetastic.widget import ConditionalSwitchableView\nfrom widgetastic.widget import Text\nfrom widgetastic.widget import View\nfrom widgetastic_patternfly import Button\nfrom widgetastic_patternfly import Dropdown\nfrom widgetastic_patternfly import TextInput\n\nfrom cfme.base.ui import ConfigurationView\nfrom cfme.common import BaseLoggedInPage\nfrom cfme.exceptions import OptionNotAvailable\nfrom cfme.modeling.base import BaseCollection\nfrom cfme.modeling.base import BaseEntity\nfrom cfme.utils.appliance.implementations.ui import CFMENavigateStep\nfrom cfme.utils.appliance.implementations.ui import navigate_to\nfrom cfme.utils.appliance.implementations.ui import navigator\nfrom cfme.utils.blockers import BZ\nfrom cfme.utils.pretty import Pretty\nfrom cfme.utils.update import Updateable\nfrom widgetastic_manageiq import Checkbox\nfrom widgetastic_manageiq import CheckboxSelect\nfrom widgetastic_manageiq import DynamicTable\nfrom widgetastic_manageiq import PaginationPane\nfrom widgetastic_manageiq import SummaryFormItem\nfrom widgetastic_manageiq import Table\nfrom widgetastic_manageiq import WaitTab\n\n\ntable_button_classes = [Button.DEFAULT, Button.SMALL, Button.BLOCK]\n\n\nclass EventsTable(DynamicTable):\n # there is a bug in Events tables, Action column has th fields instead of td one\n # this is temporary fix for that issue\n @property\n def _is_header_in_body(self):\n \"\"\"Checks whether the header is erroneously specified in the body of table.\"\"\"\n bz = BZ(1703141, forced_streams=['5.10'])\n return False if bz.blocks else super()._is_header_in_body\n\n\nclass AnalysisProfileToolbar(View):\n \"\"\"Toolbar on the analysis profiles configuration page\n Works for both all page and details page\n \"\"\"\n configuration = Dropdown('Configuration')\n\n\nclass AnalysisProfileEntities(View):\n \"\"\"Main content on the analysis profiles configuration page, title and table\"\"\"\n title = Text('//div[@id=\"main-content\"]//h1[@id=\"explorer_title\"]'\n '/span[@id=\"explorer_title_text\"]')\n table = Table('//div[@id=\"records_div\"]//table|//div[@class=\"miq-data-table\"]//table')\n\n\nclass AnalysisProfileDetailsEntities(View):\n \"\"\"Main content on an analysis profile details page\"\"\"\n title = Text('//div[@id=\"main-content\"]//h1[@id=\"explorer_title\"]'\n '/span[@id=\"explorer_title_text\"]')\n info_name = SummaryFormItem(group_title='Info', item_name='Name')\n info_description = SummaryFormItem(group_title='Info', item_name='Description')\n info_type = SummaryFormItem(group_title='Info', item_name='Type')\n table = Table('//h3[normalize-space(.)=\"File Items\"]/following-sibling::table')\n # TODO 'Event Log Items' below the table doesn't have a label, SummaryFormItem doesn't work\n\n\nclass AnalysisProfileAllView(BaseLoggedInPage):\n \"\"\"View for the Analysis Profile collection page\"\"\"\n @property\n def is_displayed(self):\n return (self.logged_in_as_current_user and\n self.sidebar.accordions.settings.tree.selected_item.text == 'Analysis Profiles' and\n self.entities.title.text == 'Settings Analysis Profiles')\n\n toolbar = View.nested(AnalysisProfileToolbar)\n sidebar = View.nested(ConfigurationView)\n entities = View.nested(AnalysisProfileEntities)\n paginator = PaginationPane()\n\n\nclass AnalysisProfileDetailsView(BaseLoggedInPage):\n \"\"\"View for an analysis profile details page\"\"\"\n @property\n def is_displayed(self):\n return (\n self.logged_in_as_current_user and\n self.entities.title.text == 'Settings Analysis Profile \"{}\"'\n .format(self.context['object'].name))\n\n toolbar = View.nested(AnalysisProfileToolbar)\n sidebar = View.nested(ConfigurationView)\n entities = View.nested(AnalysisProfileDetailsEntities)\n\n\nclass AnalysisProfileBaseAddForm(View):\n \"\"\"View for the common elements of the two AP forms\"\"\"\n name = TextInput(id='name')\n description = TextInput(id='description')\n\n @View.nested\n class files(WaitTab): # noqa\n TAB_NAME = 'File'\n tab_form = DynamicTable(\n locator='.//h3[normalize-space(.)=\"File Entry\"]/following-sibling::table',\n column_widgets={\n 'Name': TextInput(id='entry_fname'),\n 'Collect Contents?': Checkbox(id='entry_content'),\n 'Actions': Button(title='Add this entry', classes=table_button_classes)},\n assoc_column='Name', rows_ignore_top=1, action_row=0)\n\n @View.nested\n class events(WaitTab): # noqa\n TAB_NAME = 'Event Log'\n tab_form = EventsTable(\n locator='.//h3[normalize-space(.)=\"Event Log Entry\"]/following-sibling::table',\n column_widgets={\n 'Name': TextInput(id='entry_name'),\n 'Filter Message': TextInput(id='entry_message'),\n 'Level': TextInput(id='entry_level'),\n 'Source': TextInput(id='entry_source'),\n '# of Days': TextInput(id='entry_num_days'),\n 'Actions': Button(title='Add this entry', classes=table_button_classes)},\n assoc_column='Name', rows_ignore_top=1, action_row=0)\n\n\nclass AnalysisProfileAddView(BaseLoggedInPage):\n \"\"\"View for the add form, switches between host/vm based on object type\n Uses a switchable view based on the profile type widget\n \"\"\"\n\n title = Text('//div[@id=\"main-content\"]//h1[@id=\"explorer_title\"]'\n '/span[@id=\"explorer_title_text\"]')\n # This is a ALMOST a SummaryFormItem, but there's no div to wrap the items so it doesn't work\n # instead I have this nasty xpath to hack around that\n profile_type = Text(\n locator='.//h3[normalize-space(.)=\"Basic Information\"]'\n '/following-sibling::div[@class=\"form-group\"]'\n '/label[normalize-space(.)=\"Type\"]'\n '/following-sibling::div/p')\n form = ConditionalSwitchableView(reference='profile_type')\n # to avoid dynamic table buttons use title + alt + classes\n add = Button(title='Add', classes=[Button.PRIMARY], alt='Add')\n cancel = Button(title='Cancel', classes=[Button.DEFAULT], alt='Cancel')\n\n @form.register('Host')\n class AnalysisProfileAddHost(AnalysisProfileBaseAddForm):\n \"\"\"View for the host profile add form\"\"\"\n pass\n\n @form.register('Vm')\n class AnalysisProfileAddVm(AnalysisProfileBaseAddForm):\n \"\"\"View for the vm profile add form\"\"\"\n @View.nested\n class categories(WaitTab): # noqa\n TAB_NAME = 'Category'\n tab_form = CheckboxSelect(search_root='form_div')\n\n @View.nested\n class registry(WaitTab): # noqa\n TAB_NAME = 'Registry'\n tab_form = DynamicTable(\n locator='.//h3[normalize-space(.)=\"Registry Entry\"]/following-sibling::table',\n column_widgets={\n 'Registry Hive': Text('.//tr[@id=\"new_tr\"]/td[normalize-space(.)=\"HKLM\"]'),\n 'Registry Key': TextInput(id='entry_kname'),\n 'Registry Value': TextInput(id='entry_value'),\n 'Actions': Button(title='Add this entry', classes=table_button_classes)},\n assoc_column='Registry Key', rows_ignore_top=1, action_row=0)\n\n @property\n def is_displayed(self):\n return self.title.text == 'Adding a new Analysis Profile'\n\n\nclass AnalysisProfileAddVmView(AnalysisProfileAddView):\n @property\n def is_displayed(self):\n return (\n self.title.text == 'Adding a new Analysis Profile' and\n self.profile_type.text == self.context['object'].VM_TYPE)\n\n\nclass AnalysisProfileAddHostView(AnalysisProfileAddView):\n @property\n def is_displayed(self):\n return (\n self.title.text == 'Adding a new Analysis Profile' and\n self.profile_type.text == self.context['object'].HOST_TYPE)\n\n\nclass AnalysisProfileEditView(AnalysisProfileAddView):\n \"\"\"View for the edit form, extends add view since all fields are the same and editable\"\"\"\n @property\n def is_displayed(self):\n expected_title = 'Editing Analysis Profile \"{}\"'.format(self.context['object'].name)\n return (\n self.title.text == expected_title and\n self.profile_type.text == self.context['object'].profile_type)\n\n # to avoid dynamic table buttons use title + alt + classes\n save = Button(title='Save Changes', classes=[Button.PRIMARY])\n reset = Button(title='Reset Changes', classes=[Button.DEFAULT], alt='Save Changes')\n\n\nclass AnalysisProfileCopyView(AnalysisProfileAddView):\n \"\"\"View for the copy form is the same as an add\n\n The name field is by default set with 'Copy of [profile name of copy source]\n Don't want to assert against this field to separately verify the view is displayed\n If is_displayed is called after the form is changed it will be false negative\"\"\"\n pass\n\n\n@attr.s\nclass AnalysisProfile(Pretty, Updateable, BaseEntity):\n \"\"\"Analysis profiles, Vm and Host type\n\n Example: Note the keys for files, events, registry should match UI columns\n\n .. code-block:: python\n\n p = AnalysisProfile(name, description, profile_type='VM')\n p.files = [\n {\"Name\": \"/some/anotherfile\", \"Collect Contents?\": True},\n ]\n p.events = [\n {\"Name\": name, \"Filter Message\": msg, \"Level\": lvl, \"Source\": src, \"# of Days\": 1},\n ]\n p.registry = [\n {\"Registry Key\": key, \"Registry Value\": value},\n ]\n p.categories = [\"System\", \"Software\"] # Use the checkbox text name\n p.create()\n p2 = p.copy(new_name=\"updated AP\")\n with update(p):\n p.files = [{\"Name\": \"/changed\". \"Collect Contents?\": False}]\n p.delete()\n\n \"\"\"\n pretty_attrs = \"name\", \"description\", \"files\", \"events\"\n\n name = attr.ib()\n description = attr.ib()\n profile_type = attr.ib()\n files = attr.ib(default=None)\n events = attr.ib(default=None)\n categories = attr.ib(default=None)\n registry = attr.ib(default=None)\n\n def update(self, updates, cancel=False):\n \"\"\"Update the existing Analysis Profile with given updates dict\n Make use of Updateable and use `with` to update object as well\n Note the updates dict should take the structure below if called directly\n\n .. code-block:: python\n\n updates = {\n 'name': self.name,\n 'description': self.description,\n 'files': {\n 'tab_form': ['/example/file']},\n 'events': {\n 'tab_form': ['example_event']},\n 'categories': {\n 'tab_form': ['Example']},\n 'registry': {\n 'tab_form': ['example_registry']}\n }\n\n Args:\n updates (dict): Dictionary of values to change in the object.\n cancel (boolean): whether to cancel the update\n \"\"\"\n # hack to work around how updates are passed when used in context mgr\n # TODO revisit this method when BZ is fixed:\n # https://bugzilla.redhat.com/show_bug.cgi?id=1485953\n form_fill_args = self.parent.form_fill_args(updates=updates)\n view = navigate_to(self, 'Edit')\n changed = view.form.fill(form_fill_args)\n\n if changed and not cancel: # save button won't be enabled if nothing was changed\n view.save.click()\n else:\n view.cancel.click()\n\n # redirects to details if edited from there\n view = self.create_view(AnalysisProfileDetailsView, override=updates)\n assert view.is_displayed\n\n def delete(self, cancel=False):\n \"\"\"Delete self via details page\"\"\"\n view = navigate_to(self, 'Details')\n view.toolbar.configuration.item_select(\"Delete this Analysis Profile\",\n handle_alert=not cancel)\n view = self.create_view(\n AnalysisProfileDetailsView if cancel else AnalysisProfileAllView)\n view.flush_widget_cache()\n assert view.is_displayed\n\n def copy(self, new_name=None, cancel=False):\n \"\"\"Copy the Analysis Profile\"\"\"\n # Create a new object to return in addition to running copy in the UI\n # TODO revisit this method when BZ is fixed:\n # https://bugzilla.redhat.com/show_bug.cgi?id=1485953\n if not new_name:\n new_name = f'{self.name}-copy'\n new_profile = self.parent.instantiate(\n name=new_name,\n description=self.description,\n profile_type=self.profile_type,\n files=self.files,\n events=self.events,\n categories=self.categories,\n registry=self.registry\n )\n\n # actually run copy in the UI, fill the form\n view = navigate_to(self, 'Copy')\n form_args = self.parent.form_fill_args(updates={'name': new_profile.name})\n view.form.fill(form_args)\n if cancel:\n view.cancel.click()\n else:\n view.add.click()\n\n # check the result\n view = self.create_view(\n AnalysisProfileDetailsView if cancel else AnalysisProfileAllView)\n view.flush_widget_cache()\n assert view.is_displayed\n return new_profile\n\n\n@attr.s\nclass AnalysisProfileCollection(BaseCollection):\n\n VM_TYPE = 'Vm'\n HOST_TYPE = 'Host'\n\n ENTITY = AnalysisProfile\n\n def create(self, name, description, profile_type, files=None, events=None, categories=None,\n registry=None, cancel=False):\n \"\"\"Add Analysis Profile to appliance\"\"\"\n # The tab form values have to be dictionaries with the root key matching the tab widget name\n form_values = self.form_fill_args({\n 'name': name,\n 'description': description,\n 'categories': categories,\n 'files': files,\n 'registry': registry,\n 'events': events\n })\n\n if profile_type.lower() == 'vm':\n view = navigate_to(self, 'AddVmProfile')\n elif profile_type.lower() == 'host':\n view = navigate_to(self, 'AddHostProfile')\n else:\n raise OptionNotAvailable('Not such profile available')\n\n view.form.fill(form_values)\n\n if cancel:\n view.cancel.click()\n else:\n view.add.click()\n\n view.flush_widget_cache()\n view = self.create_view(AnalysisProfileAllView)\n\n assert view.is_displayed\n\n return self.instantiate(\n name=name,\n description=description,\n profile_type=profile_type,\n files=files,\n events=events,\n categories=categories,\n registry=registry\n )\n\n def form_fill_args(self, updates=None):\n \"\"\"Build a dictionary of nested tab_forms for assoc_fill from a flat object dictionary\n If updates dictionary is passed, it is used instead of `self`\n This should work for create or update form fill args\n \"\"\"\n fill_args = {'profile_type': None} # this can't be set when adding or editing\n for key in ['name', 'description']:\n if updates and key in updates:\n arg = updates[key]\n fill_args[key] = arg\n\n for key in ['files', 'events', 'registry']:\n if updates and key in updates:\n data = deepcopy(updates[key])\n if isinstance(data, list):\n # It would be much better to not have these hardcoded, but I can't get them\n # statically from the form (ConditionalSwitchWidget)\n assoc_column = 'Name' if key in ['files', 'events'] else 'Registry Key'\n values_dict = {}\n for item in data:\n name = item.pop(assoc_column)\n values_dict[name] = item\n\n fill_args[key] = {'tab_form': values_dict}\n\n for key in ['categories']:\n # No assoc_fill for checkbox select, just tab_form mapping here\n if updates and key in updates:\n arg = deepcopy(updates[key])\n fill_args[key] = {'tab_form': arg}\n\n return fill_args\n\n def all(self):\n profiles = []\n view = navigate_to(self, 'All')\n view.paginator.set_items_per_page(1000)\n all_profiles_rows = view.entities.table\n if all_profiles_rows:\n for profile in all_profiles_rows:\n profiles.append(self.instantiate(\n name=profile.name.text,\n description=profile.description.text,\n profile_type=profile.type.text))\n return profiles\n\n\n@navigator.register(AnalysisProfileCollection, 'All')\nclass AnalysisProfileAll(CFMENavigateStep):\n VIEW = AnalysisProfileAllView\n prerequisite = NavigateToAttribute('appliance.server', 'Configuration')\n\n def step(self, *args, **kwargs):\n server_region = self.obj.appliance.server_region_string()\n self.prerequisite_view.accordions.settings.tree.click_path(\n server_region, \"Analysis Profiles\")\n\n def resetter(self, *args, **kwargs):\n self.view.browser.refresh()\n\n\n@navigator.register(AnalysisProfileCollection, 'AddVmProfile')\nclass AnalysisProfileVmAdd(CFMENavigateStep):\n VIEW = AnalysisProfileAddVmView\n prerequisite = NavigateToSibling('All')\n\n def step(self, *args, **kwargs):\n self.prerequisite_view.toolbar.configuration.item_select(\"Add VM Analysis Profile\")\n\n\n@navigator.register(AnalysisProfileCollection, 'AddHostProfile')\nclass AnalysisProfileHostAdd(CFMENavigateStep):\n VIEW = AnalysisProfileAddHostView\n prerequisite = NavigateToSibling('All')\n\n def step(self, *args, **kwargs):\n self.prerequisite_view.toolbar.configuration.item_select(\"Add Host Analysis Profile\")\n\n\n@navigator.register(AnalysisProfile, 'Details')\nclass AnalysisProfileDetails(CFMENavigateStep):\n VIEW = AnalysisProfileDetailsView\n prerequisite = NavigateToAttribute('parent', 'All')\n\n def step(self, *args, **kwargs):\n server_region = self.obj.appliance.server_region_string()\n self.prerequisite_view.sidebar.accordions.settings.tree.click_path(\n server_region, \"Analysis Profiles\", self.obj.name)\n\n\n@navigator.register(AnalysisProfile, 'Edit')\nclass AnalysisProfileEdit(CFMENavigateStep):\n VIEW = AnalysisProfileEditView\n prerequisite = NavigateToSibling('Details')\n\n def step(self, *args, **kwargs):\n self.prerequisite_view.toolbar.configuration.item_select(\"Edit this Analysis Profile\")\n\n\n@navigator.register(AnalysisProfile, 'Copy')\nclass AnalysisProfileCopy(CFMENavigateStep):\n VIEW = AnalysisProfileCopyView\n prerequisite = NavigateToSibling('Details')\n\n def step(self, *args, **kwargs):\n self.prerequisite_view.toolbar.configuration.item_select(\n 'Copy this selected Analysis Profile')\n","repo_name":"ManageIQ/integration_tests","sub_path":"cfme/configure/configuration/analysis_profile.py","file_name":"analysis_profile.py","file_ext":"py","file_size_in_byte":19242,"program_lang":"python","lang":"en","doc_type":"code","stars":70,"dataset":"github-code","pt":"77"}
+{"seq_id":"5293292507","text":"\"\"\"\nDjango settings for cornerwise project.\n\"\"\"\n\nimport os\nimport re\n# For celery:\nfrom celery.schedules import crontab\nfrom django.utils.log import DEFAULT_LOGGING\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n# Determine if the app is in production mode by examining the\n# environment variable set by Docker:\nAPP_MODE = os.environ.get(\"APP_MODE\", \"development\").lower()\nIS_PRODUCTION = (APP_MODE == \"production\")\nIS_CELERY = os.environ.get(\"IS_CELERY\") == \"1\"\n\nREDIS_HOST = \"redis://\" + os.environ.get(\"REDIS_HOST\", \"\")\n\nSECRET_KEY = os.environ.get(\n \"DJANGO_SECRET\", \"98yd3te$59^w!j(@b!@f8%fv49&p)vu+8)b4e5jcvfx_yeqs\")\n\n\ndef dev_default(var_name, default=True):\n \"\"\"If the environment variable `var_name` is set, use it to determine whether a\n feature is turned on. Otherwise, fall back on `default` in development mode\n and `not default` in production mode.\n\n \"\"\"\n return os.environ[var_name] == \"1\" if var_name in os.environ else IS_PRODUCTION != default\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = not IS_PRODUCTION or os.environ.get(\"DJANGO_DEBUG_MODE\") == \"1\"\n\nSERVE_STATIC = dev_default(\"DJANGO_SERVE_STATIC\")\nSERVE_MEDIA = dev_default(\"DJANGO_SERVE_MEDIA\")\n\nALLOWED_HOSTS_RAW = os.environ.get(\"ALLOWED_HOSTS\", \"*\")\nALLOWED_HOSTS = ALLOWED_HOSTS_RAW.split(\",\")\nUSE_X_FORWARDED_HOST = dev_default(\"USE_X_FORWARDED_HOST\", False)\n\nVIRTUAL_HOST = os.environ.get(\"VIRTUAL_HOST\")\n\nCSRF_COOKIE_SECURE = SESSION_COOKIE_SECURE = dev_default(\"SECURE_COOKIES\", False)\nSESSION_COOKIE_DOMAIN = CSRF_COOKIE_DOMAIN = \\\n os.environ.get(\"COOKIE_DOMAIN\") \\\n or (VIRTUAL_HOST and VIRTUAL_HOST.split(\",\")[0]) \\\n or (ALLOWED_HOSTS[0] if ALLOWED_HOSTS_RAW != \"*\" else None)\n\n# Application definition\nINSTALLED_APPS = [\n \"django.contrib.admin\",\n \"django.contrib.auth\",\n \"django.contrib.contenttypes\",\n \"django.contrib.humanize\",\n \"django.contrib.sessions\",\n \"django.contrib.messages\",\n \"django.contrib.staticfiles\",\n \"django.contrib.gis\",\n \"django.contrib.postgres\",\n \"django_celery_results\",\n \"django_pgviews\",\n \"tinymce\",\n \"parcel.ParcelConfig\",\n \"proposal.ProposalConfig\",\n \"project.ProjectConfig\",\n \"user.UserAppConfig\",\n \"shared.SharedAppConfig\",\n \"task\",\n]\n\nMIDDLEWARE = [\n \"django.contrib.sessions.middleware.SessionMiddleware\",\n \"django.middleware.common.CommonMiddleware\",\n \"django.middleware.csrf.CsrfViewMiddleware\",\n \"django.contrib.auth.middleware.AuthenticationMiddleware\",\n \"django.contrib.messages.middleware.MessageMiddleware\",\n \"django.middleware.clickjacking.XFrameOptionsMiddleware\",\n \"django.middleware.security.SecurityMiddleware\",\n \"site_config.SiteMiddleware\",\n]\n\ndef get_bridge_ip():\n if \"CONTAINER_CIDR\" in os.environ:\n import ipaddress\n net = ipaddress.IPv4Network(os.environ[\"CONTAINER_CIDR\"], strict=False)\n return str(next(net.hosts()))\n else:\n return \"127.0.0.1\"\n\nINTERNAL_IPS = [get_bridge_ip()]\n\nENABLE_DEBUG_TOOLBAR = os.environ.get(\"ENABLE_DEBUG_TOOLBAR\") == \"1\"\nif ENABLE_DEBUG_TOOLBAR:\n INSTALLED_APPS.append(\"debug_toolbar\")\n MIDDLEWARE.insert(0, \"debug_toolbar.middleware.DebugToolbarMiddleware\")\n\n\nROOT_URLCONF = \"cornerwise.urls\"\n\n\ndef templates_config():\n context_processors = [\n \"django.template.context_processors.request\",\n \"django.contrib.auth.context_processors.auth\",\n \"django.contrib.messages.context_processors.messages\",\n \"site_config.context_processor\",\n ]\n if DEBUG:\n context_processors.insert(0, \"django.template.context_processors.debug\")\n\n return [{\n \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n \"DIRS\": [\"templates\"],\n \"APP_DIRS\": True,\n \"OPTIONS\": {\n \"debug\": not IS_PRODUCTION,\n \"context_processors\": context_processors,\n },\n }]\n\nTEMPLATES = templates_config()\n\nWSGI_APPLICATION = \"cornerwise.wsgi.application\"\n\n#####################\n# Database and Cache\n\nPOSTGRES_HOST = os.environ.get(\"POSTGRES_HOST\", \"\")\nDATABASES = {\n \"default\": {\n \"ENGINE\": \"django.contrib.gis.db.backends.postgis\",\n \"HOST\": POSTGRES_HOST,\n \"NAME\": \"postgres\",\n \"USER\": \"postgres\"\n }\n}\n\nSESSION_ENGINE = \"django.contrib.sessions.backends.cache\"\n\nCACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": REDIS_HOST,\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n \"CONNECTION_POOL_CLASS\": \"redis.BlockingConnectionPool\",\n \"CONNECTION_POOL_CLASS_KWARGS\": {\n \"max_connections\": 50,\n \"timeout\": 20\n },\n \"TIMEOUT\": None\n }\n }\n}\n\nLOGGING = DEFAULT_LOGGING\n\nLOGGING[\"handlers\"][\"record\"] = {\n \"level\": \"INFO\",\n \"class\": \"logging.handlers.RotatingFileHandler\",\n \"filename\": \"logs/celery_tasks.log\",\n \"formatter\": \"django.server\",\n \"maxBytes\": 1024*1024*10,\n \"backupCount\": 5\n}\n\nLOGGING[\"loggers\"][\"celery_tasks\"] = {\n \"handlers\": [\"console\", \"mail_admins\", \"record\"],\n \"level\": \"INFO\"\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.8/topics/i18n/\n\nLANGUAGE_CODE = \"en-us\"\n\nTIME_ZONE = \"US/Eastern\"\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\nSERVER_DOMAIN = \"cornerwise.org\"\n\nSTATIC_URL = \"/static/\"\nMEDIA_URL = \"/media/\"\n\nMEDIA_ROOT = \"/media/\"\n\n# Files to be copied when static files are collected for deployment.\nSTATICFILES_DIRS = [\n (\"images\", \"/static/images\"),\n (\"errors\", \"/static/errors\"),\n (\"layerdata\", \"/static/scripts/src/layerdata\"),\n (\"css\", \"/static/css\"),\n (\"scripts\", \"/static/scripts\"),\n]\n\n\ndef get_built_resources():\n with open(\"/static/build/built.json\", \"r\") as built:\n import json\n info = json.load(built)\n return info[\"js_filename\"], info[\"css_filename\"]\n\n\nif not SERVE_STATIC:\n STATICFILES_DIRS.extend([\n (\"build\", \"/static/build\"),\n ])\n\n STATIC_ROOT = \"/static_build\"\n\n try:\n JS_FILENAME, CSS_FILENAME = get_built_resources()\n except:\n JS_FILENAME = \"app.build.js\"\n CSS_FILENAME = \"app.build.css\"\nelse:\n JS_FILENAME = CSS_FILENAME = \"\"\n STATICFILES_DIRS.extend([\n (\"template\", \"/static/template\"),\n ])\n\n#######################\n# Celery configuration\nBROKER_URL = REDIS_HOST\n\nCELERY_ACCEPT_CONTENT = [\"json\"]\nCELERY_TASK_SERIALIZER = \"json\"\n\n# Persist task results to the database\nCELERY_RESULT_BACKEND = 'django-cache'\n\nCELERYBEAT_SCHEDULE = {\n \"scrape-proposals\": {\n \"task\": \"proposal.tasks.pull_updates\",\n # Run daily at midnight:\n \"schedule\": crontab(\n minute=0, hour=0)\n },\n\n \"send-notifications\": {\n \"task\": \"user.tasks.send_notifications\",\n \"schedule\": crontab(minute=0, hour=1)\n },\n\n \"cleanup-subscriptions\": {\n \"task\": \"user.tasks.cleanup_subscriptions\",\n \"schedule\": crontab(minute=0, hour=0)\n },\n\n \"collect-sendgrid-stats\": {\n \"task\": \"user.tasks.collect_sendgrid_stats\",\n \"schedule\": crontab(minute=0, hour=2, day_of_week=0)\n },\n}\n\nCELERYD_TASK_SOFT_TIME_LIMIT = 60\n\n###########\n# Messages\nfrom django.contrib.messages import constants as messages\nMESSAGE_TAGS = {messages.ERROR: \"danger\"}\n\n###############################\n# Cornerwise-specific settings\n\nGEO_BOUNDS = [\n 42.371861543730496,\n -71.13338470458984, # northwest\n 42.40393908425197,\n -71.0679817199707\n] # southeast\n\n# The 'fit-width' of image thumbnails:\nTHUMBNAIL_DIM = (300, 300)\n# Set to a color name to pad thumbnails to the desired dimensions\nTHUMBNAIL_PAD = None\n\nGEOCODER = \"arcgis\"\n\n# Email address and name for emails:\nEMAIL_ADDRESS = \"cornerwise@cornerwise.org\"\nEMAIL_NAME = \"Cornerwise\"\n\n# TinyMCE configuration:\n# TINYMCE_JS_URL = 'http://debug.example.org/tiny_mce/tiny_mce_src.js'\nTINYMCE_DEFAULT_CONFIG = {\n \"plugins\": \"paste,searchreplace\",\n \"theme\": \"advanced\",\n \"theme_advanced_buttons2\": \"\",\n \"theme_advanced_buttons3\": \"\",\n \"theme_advanced_path\": False,\n \"cleanup_on_startup\": True,\n \"custom_undo_redo_levels\": 10,\n}\nTINYMCE_SPELLCHECKER = False\nTINYMCE_COMPRESSOR = True\n\n# Local settings will override this:\nSENDGRID_TEMPLATES = {\n \"generic\": \"5b82e3d6-151a-44e0-82ec-a6fdcae746bb\",\n}\n\nMIN_ALERT_RADIUS = 50\nMAX_ALERT_RADIUS = 10000\n\n# URL to use for generating minimap raster images for emails, etc.\nMINIMAP_SRC = (\"https://minimap.cornerwise.org/bounds?\"\n \"tile-provider=cartodb-light&\"\n \"sw-lat={swlat}&sw-lng={swlon}&\"\n \"ne-lat={nelat}&ne-lng={nelon}&circle={circle}\")\n\nGEO_REGION = \"Somerville, MA\"\n\nAUTHENTICATION_BACKENDS = [\"user.auth.TokenBackend\",\n \"django.contrib.auth.backends.ModelBackend\"]\n\nIMPORTER_SCHEMA = \"/app/scraper-schema.json\"\n\n# Site config\nSITE_CONFIG = {\n \"somerville\": {\n \"module\": \"site_config.somervillema\",\n \"hostnames\": [\"somerville.cornerwise.org\", \"cornerwise.somervillema.gov\", \"default\"]\n },\n # \"cambridge\": {\n # \"module\": \"site_config.cambridgema\",\n # \"hostnames\": [\"cambridge.cornerwise.org\"]\n # }\n}\n\nUSE_SITE_HOSTNAMES = True\n\n# Load select environment variables into settings:\nfor envvar in [\n \"GOOGLE_API_KEY\", \"GOOGLE_BROWSER_API_KEY\",\n \"GOOGLE_STREET_VIEW_SECRET\", \"GEOCODER\", \"ARCGIS_CLIENT_ID\",\n \"ARCGIS_CLIENT_SECRET\", \"SOCRATA_APP_TOKEN\", \"SOCRATA_APP_SECRET\",\n \"SENDGRID_API_KEY\", \"FOURSQUARE_CLIENT\", \"FOURSQUARE_SECRET\",\n \"SENDGRID_PARSE_KEY\", \"SERVER_DOMAIN\", \"BASE_URL\", \"SITE_REDIRECT\"\n]:\n if envvar in os.environ or envvar not in globals():\n globals()[envvar] = os.environ.get(envvar, \"\")\n\n\n# If the user accesses the site via a domain that does not match any of the\n# configured domains and SITE_REDIRECT is set to 1, redirect requests to the\n# default hostname.\nSITE_REDIRECT = SITE_REDIRECT == \"1\"\n\ndef get_admins():\n admins_from_env = []\n for admin_str in re.split(r\"\\s*;\\s*\", os.environ.get(\"ADMINS\", \"\")):\n m = re.search(r\"\\s*<([^>]+)>\", admin_str)\n username, email = \\\n (admin_str[0:m.start()], m.group(1).strip()) if m \\\n else (admin_str, admin_str)\n\n admins_from_env.append((username, email))\n return admins_from_env\n\n\nADMINS = get_admins()\n\nif IS_PRODUCTION and not ADMINS:\n print(\"No ADMINS configured.\")\n\n\ntry:\n # Allow user's local settings to shadow shared settings:\n from .local_settings import *\nexcept ImportError as err:\n print(\"Could not find local_settings.py -- \", err)\n\n\nif SENDGRID_API_KEY:\n EMAIL_BACKEND = \"sendgrid_backend.SendgridBackend\"\n SENDGRID_SANDBOX_MODE_IN_DEBUG = False\n","repo_name":"codeforboston/cornerwise","sub_path":"server/cornerwise/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":10747,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"77"}
+{"seq_id":"15819964718","text":"from PIL import Image, ImageDraw\nfrom colors import colors, random_color\nimport random\n\nimg = Image.new('RGB', (512,512), 'black')\n\npixels = img.load()\nfor i in range(img.size[0]):\n for j in range(img.size[1]):\n pixels[i,j] = (colors[\"periwinkle\"][0]+(i-j)//2, colors[\"periwinkle\"][1]+(i-j)//3, colors[\"periwinkle\"][2]+(i-j)//4)\n\ndraw = ImageDraw.Draw(img)\nfor i in range(0, img.size[0], 50):\n for j in range(0, img.size[1], 50):\n upper = random.random()*50-20\n lower = random.random()*50+20\n draw.ellipse((i+upper, j+upper, i+lower, j+lower), outline=random_color())\n\nimg.save(\"RING\", \"PNG\")\n","repo_name":"RogueWaverly/Art-Generator","sub_path":"2019-Inktober/01-ring.py","file_name":"01-ring.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"29398584326","text":"# Crie um programa que leia vários números inteiros pelo teclado.\n# O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada.\n# No final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando o flag).\nqty = soma = 0\nwhile True:\n num = int(input('Digite um valor [999 p/ parar]: '))\n if num == 999:\n break\n qty += 1\n soma += num\nprint(f'A soma dos {qty} valores foi {soma}!')","repo_name":"eduardoalmeida-frontend/python","sub_path":"Mundo 2 - Estruturas de Controle/ex066.py","file_name":"ex066.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"3081071592","text":"import fileinput\n\nif __name__ == \"__main__\":\n hor = 0\n ver = 0\n for line in fileinput.input():\n typ, dist = line.split()\n dist = int(dist)\n if typ == \"forward\":\n hor += dist\n elif typ == \"down\":\n ver += dist\n else:\n ver -= dist\n \n print(hor * ver)","repo_name":"mo-morgan/CPSolutions","sub_path":"aoc/2021/day2/day2.py","file_name":"day2.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"27334445106","text":"from __future__ import absolute_import\r\n\r\ndef convert_TF_SD(comm, line, *args, **kwargs):\r\n if \"TF\" not in line:\r\n return line\r\n goodline = line.replace(\"TF\",\"SD\")\r\n return goodline\r\n\r\n\r\n\r\n\r\n__plugin_hooks__ = {\r\n \"octoprint.comm.protocol.gcode.received\": convert_TF_SD\r\n}\r\n\r\n\r\n","repo_name":"Tctutt/Ender-3-SD-card-fixer","sub_path":"Ender3_SD_fix/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"1480529622","text":"import pymysql \npymysql.install_as_MySQLdb()\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, String, DateTime, Boolean\n\nfrom sqlalchemy.orm import sessionmaker\n\nengine = create_engine('mysql+mysqldb://root:123456@192.168.91.129/tornado',\n encoding='utf8', echo=True)\nBase = declarative_base()\nSession = sessionmaker(bind=engine)\n\nclass News(Base):\n __tablename__ = 'news'\n id = Column(Integer, primary_key=True)\n title = Column(String(2000), nullable=False)\n content = Column(String(2000), nullable=False)\n types = Column(String(2000), nullable=False)\n author = Column(String(2000), nullable=False)\n created_at = Column(DateTime,)\n is_valid = Column(Boolean,)\n\n\nif __name__ == '__main__':\n # News.metadata.create_all(engine)\n\n s = Session()\n\n # insert\n\n # s.add(News(title='lishulong',content='this is content',types = 'types',author = 'author'))\n # s.add(News(title='lishulong',content='this is content',types = 'types',author = 'author'))\n # s.add(News(title='lishulong',content='this is content',types = 'types',author = 'author'))\n # s.add(News(title='lishulong',content='this is content',types = 'types',author = 'author'))\n # s.add(News(title='lishulong',content='this is content',types = 'types',author = 'author'))\n # s.add(News(title='lishulong',content='this is content',types = 'types',author = 'author'))\n # s.add(News(title='lishulong',content='this is content',types = 'types',author = 'author'))\n\n # query\n print(s.query(News).get(1))\n print(s.query(News).get(2).title)\n\n\n # update\n\n obj = s.query(News).filter_by(title='lishulong').first()\n\n print(obj.content)\n\n obj.content = 'good'\n\n s.add(obj)\n\n s.commit()\n\n\n\n # delete\n # print(s.delete(s.query(News).get(1)))\n # s.commit()\n\n # s.commit()\n\n","repo_name":"lishulongVI/9277","sub_path":"python/orm/sql_client.py","file_name":"sql_client.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"31709283570","text":"\"\"\"Implement REAP patch rendering for MTSD data.\"\"\"\n\nfrom __future__ import annotations\n\nfrom adv_patch_bench.transforms import reap_object\n\n\nclass MtsdObject(reap_object.ReapObject):\n \"\"\"Object wrapper for MTSD samples.\"\"\"\n\n def __init__(self, **kwargs) -> None:\n \"\"\"Initialize MtsdObject.\"\"\"\n if \"dataset\" not in kwargs:\n kwargs[\"dataset\"] = \"mtsd\"\n super().__init__(\n pad_to_square=True,\n use_box_mode=True,\n **kwargs,\n )\n","repo_name":"wagner-group/reap-benchmark","sub_path":"adv_patch_bench/transforms/mtsd_object.py","file_name":"mtsd_object.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"77"}
+{"seq_id":"38878034086","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy import stats\n\nfrom load_balancing_simulations.SimulationBase import SimulationBase\n\n\nclass SimulationHT(SimulationBase):\n # Class for Heavy Traffic simulations\n\n # PLOTTING\n def draw_plots(self):\n # Plots histograms showing exponential behavior\n plt.style.use('seaborn-dark')\n\n # Histogram\n\n plot_data = self.epsilon * super().draw_plots()\n\n bin_heights, bin_borders, _ = plt.hist(plot_data, density=True,\n bins='doane', color='green',\n edgecolor='black', linewidth=1, label='Histogram')\n plt.autoscale()\n plt.xlabel('epsilon * sum of queue lengths')\n\n # Curve Fit\n\n mean = (self.n * self.lambda_ + self.n) / 2\n x_interval_for_fit = np.linspace(bin_borders[0], bin_borders[-1], self.num_arrivals / 2)\n plt.plot(x_interval_for_fit, stats.expon.pdf(x_interval_for_fit, scale=mean), label='Exponential Fit',\n color='red',\n linewidth=1.3)\n\n plt.grid()\n plt.legend(loc='upper right')\n plt.autoscale()\n plt.show()\n","repo_name":"milton-pagan/load-balancing-simulations","sub_path":"load_balancing_simulations/HeavyTraffic.py","file_name":"HeavyTraffic.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"22819570674","text":"# Given two binary strings a and b, return their sum as a binary string.\n\n# Example 1:\n#\n# Input: a = \"11\", b = \"1\"\n# Output: \"100\"\n#\n# Example 2:\n#\n# Input: a = \"1010\", b = \"1011\"\n# Output: \"10101\"\n\n\ndef addBinary(a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: str\n \"\"\"\n diff = abs(len(a) - len(b))\n if diff != 0:\n if len(a) > len(b):\n b = diff * \"0\" + b\n else:\n a = diff * \"0\" + a\n\n carry = 0\n res = \"\"\n\n for i in range(len(a) - 1, -1, -1):\n curr = \"\"\n if a[i] == \"0\" and b[i] == \"0\":\n curr = 0\n elif a[i] == \"1\" and b[i] == \"1\":\n curr = 2\n else:\n curr = 1\n\n if curr + carry == 0:\n res = \"0\" + res\n carry = 0\n elif curr + carry == 1:\n res = \"1\" + res\n carry = 0\n elif curr + carry == 2:\n res = \"0\" + res\n carry = 1\n else:\n res = \"1\" + res\n carry = 1\n\n if carry:\n res = \"1\" + res\n\n return str(res)\n\n\naddBinary(\"1010\", \"1011\")\n","repo_name":"joelhoelting/algorithms","sub_path":"leetcode/iteration/67_add_binary.py","file_name":"67_add_binary.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"42121278269","text":"# 汇率兑换.py\n# 2020/09/18\n# fyj\n\nprint(\"'y'&'Y'为‘人民币’\")\nprint(\"'d'&'D'为‘美元’\\n\")\n\ns = input(\"金钱值和金钱符号:\")\n\nwhile s[-1] not in ['N','n']:\n if s[-1] in [\"d\",\"D\"]:\n Yuan=eval(s[0:-1])*6\n print(\"转换后的金钱{:.2f}Yuan\".format(Yuan))\n elif s[-1] in [\"y\",\"Y\"]:\n Dollar= eval(s[0:-1]) / 6\n print(\"转换后的金钱{:.2f}Dollar\".format(Dollar))\n else:\n print(\"输入有误,请重试!\")\n \n \n s = input(\"\\n金钱值和金钱符号:\")\n","repo_name":"EdwinVan/Python","sub_path":"Python Homework/20-09-18-week02/WEEK 02/2-2-huilv.py","file_name":"2-2-huilv.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"4621322554","text":"from text_exp import find_pos\n\nfrom typing import List, Tuple, Counter\nimport spacy\n\nnlp = spacy.load('en_core_web_sm')\n\n\ndef find_pos_in_three_parts(split_file: Tuple[List[str], List[str], List[str]], pos: str) -> List[Counter]:\n \"\"\"Find pos in first, middle and end of a file\n\n :param split_file:The tuple containing three even length lists of strings, converted from a fairy tale.\n :param pos: The POS to be checked.\n :return: The list containing three counters with token_lemmas with their count, corresponding beginning, middle and end part of\n a file.\n \"\"\"\n pos_list = []\n for lines in split_file:\n pos_dict = find_pos(lines, pos)\n pos_list.append(pos_dict)\n return pos_list\n\n\n\n","repo_name":"qing-dai/FairyTale","sub_path":"metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"40420364369","text":"# encoding=utf8\n\nfrom PyQt4 import QtGui\n\nfrom Ui_UpdatesChecker import Ui_UpdatesCheckerDialog\nfrom library.Utils import forceString, forceInt\nfrom sql.updates_list import updates_list\n\nSTATUS_MAP = {\n -1: u'Отсутствует',\n 0: u'Не выполнен',\n 1: u'Выполнен'\n}\n\n\nclass CUpdatesChecker(QtGui.QDialog):\n def __init__(self, parent=None):\n super(CUpdatesChecker, self).__init__(parent)\n self.ui = Ui_UpdatesCheckerDialog()\n self.ui.setupUi(self)\n\n self.ui.buttonBox.clicked.connect(self.close)\n\n self.load_list()\n\n def load_list(self):\n result = dict((number, -1) for number in updates_list)\n for rec in QtGui.qApp.db.iterRecordList(stmt=u'SELECT updateNumber, completed'\n u' FROM DatabaseUpdateInfo'\n u' WHERE updateNumber IS NOT NULL AND updateNumber != \\'\\''):\n result[forceString(rec.value('updateNumber'))] = forceInt(rec.value('completed'))\n for number in sorted(result.keys()):\n row = self.ui.table.rowCount()\n self.ui.table.setRowCount(row + 1)\n self.ui.table.setItem(row, 0, QtGui.QTableWidgetItem(number))\n self.ui.table.setItem(row, 1, QtGui.QTableWidgetItem(STATUS_MAP[result[number]]))\n\n\nif __name__ == '__main__':\n app = QtGui.QApplication()\n w = CUpdatesChecker().show()\n app.exec_()\n","repo_name":"dio4/vista_1","sub_path":"DataCheck/UpdatesChecker.py","file_name":"UpdatesChecker.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"33216426057","text":"import unstructured_grid\nfrom delft import dfm_grid\nreload(unstructured_grid)\nreload(dfm_grid)\nimport qnc\n## \n\nnc_path=\"/Users/rusty/models/sfbd-grid-southbay/SFEI_SSFB_fo_dwrbathy_net.nc\"\n# nc=qnc.QDataset(nc_path)\ng=dfm_grid.DFMGrid(nc_path)\ng.write_ugrid('test_ugrid.nc',overwrite=True)\n\n## \n\n# g.plot_edges()\n\n# ugrid writing:\n\n\n## \n\nnc=qnc.QDataset('test_ugrid.nc')\ng=unstructured_grid.UnstructuredGrid.from_ugrid(nc)\n\n## \n\n# For the moment, not sure how much functionality will be put\n# in UnstructuredGrid, a Paving-like subclass of it, outside\n# classes, or outside methods.\n# easiest to work with some discrete methods for now.\n\ndef set_marks_on_full_grid(self):\n \"\"\"\n getting edge marks set up for grid generation\n uses cells to define the half-edge marks\n \"\"\"\n # make sure that edges['cells'] is set\n e2c=self.edge_to_cells()\n g.edges['mark'][:]=self.INTERNAL\n g.edges['mark'][e2c[:,1]<0] = self.LAND\n\n\nset_marks_on_full_grid(g) \n\n## \n\nzoom0=(580841., 587152., 4143806, 4148726)\nzoom1=(583471., 584479, 4146240, 4147026)\nsel_nodes=g.select_nodes_intersecting(xxyy=zoom1)\n\n## \n\nplt.figure(1).clf()\nfig,ax=plt.subplots(1,1,num=1)\n\ncoll=g.plot_edges(values=g.edges['mark'])\ncolln=g.plot_nodes(mask=sel_nodes)\n\nax.axis(zoom0)\n\n## \n\n# screwed up - this should be starting with construct_quads_v03.py,\n# and on to ...\n# for both the next step of quad generation, and for any\n# sort of port of tom to unstructured_grid, need support\n# for nodes which are constrained to a curve.\n\n# class NodeConstraints(object):\n\n","repo_name":"rustychris/umbra","sub_path":"construct_quads_v04.py","file_name":"construct_quads_v04.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"8049345530","text":"from Application.Utils.AlgorithmDecorators import RegisterAlgorithm\nfrom Application.Utils.OutputDecorators import OutputDialog\n\nimport numpy as np\nimport math\n\n\n@RegisterAlgorithm(\"Hough\", \"Tools\")\n@OutputDialog(title=\"Output\")\ndef hough(image):\n\n f=int(round(math.sqrt(image.shape[0]*image.shape[0]+image.shape[1]*image.shape[1]))+100)\n houghMap=np.zeros((f, 271), dtype=np.uint8)\n houghMap2 = np.zeros((f, 271), dtype=np.uint8)\n\n for k in range(1,image.shape[0]-1):\n for m in range(1,image.shape[1]-1):\n if(image[k,m]>10):\n for i in range(-90, 181):\n r = m * math.cos(i * math.pi / 180) + k * math.sin(i * math.pi / 180)\n if r>=0:\n houghMap[math.floor(r), i + 90] += 1\n\n for i in range(0, houghMap2.shape[0]):\n for j in range(0, houghMap2.shape[1]):\n if (houghMap[i, j] >= 150):\n houghMap2[i, j] = houghMap[i, j]\n if houghMap2[i, j] > 255:\n houghMap2[i, j] = 255\n\n\n\n for i in range(0, houghMap2.shape[0]-1):\n for j in range(0, houghMap2.shape[1]-1):\n if houghMap2[i, j] != 0:\n houghMap2[i-25:i+26, j-25:j+26] = 0\n houghMap2[i, j] = 255\n return houghMap2\n\n\n\n\n\n\n\n\n\n\n","repo_name":"becatalina/ISIP2018","sub_path":"HoughRect.py","file_name":"HoughRect.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"44817548654","text":"import pandas as pd\nimport requests\n\ntable_url = snakemake.params.table_url\nalignment_counts = snakemake.output.alignment_counts\n\nprint(f\"mutation count dataframe from {table_url}\")\nhtml_text = requests.get(table_url, verify=False).content.decode(\"utf-8\")\ndf = pd.read_html(html_text, encoding=\"utf-8\")[0]\n\nprint(f\"parsing mutation count dataframe \")\ncols_of_interest = {\n \"WildtypeAA\": \"wildtype\",\n \"Position\": \"site\",\n \"MutatedAA\": \"mutant\",\n \"#Occurrence\": \"count\",\n}\n\nmut_counts = (\n df\n .query(\"MutatedAA.notnull()\", engine=\"python\")\n .query(\"WildtypeAA.notnull()\", engine=\"python\")\n .query(\"Position.notnull()\", engine=\"python\")\n .query(\"Protein == 'Spike'\")\n .rename(columns=cols_of_interest)\n [cols_of_interest.values()]\n .assign(site=lambda x: x[\"site\"].astype(int))\n .sort_values(\"count\", ascending=False)\n .reset_index(drop=True)\n)\n\nmut_counts = mut_counts[(mut_counts.mutant != 'J') & (mut_counts.mutant != 'Z') & (mut_counts.mutant != 'B')]\n\n#save mutation counts\nprint(f\"saving {alignment_counts}\")\nmut_counts.to_csv(alignment_counts, index=False)","repo_name":"dms-vep/SARS-CoV-2_Omicron_BA.2_spike_ACE2_binding","sub_path":"library_design/scripts/spike_alignment_counts.py","file_name":"spike_alignment_counts.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"24457901612","text":"from __future__ import annotations\nfrom pathlib import Path\nfrom random import sample\nfrom typing import Callable, Dict, List\nfrom fastapi import WebSocket\n\nfrom utils import log\nfrom event import Event, LoginEvent, MessageEvent, InitEvent\n\nuid_build_str = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\n\ndef get_uid():\n return \"\".join(sample(uid_build_str, 6))\n\n\nclass User:\n users: List[User] = []\n history: List[MessageEvent] = []\n dealer_dict: Dict[str, List[Callable]] = {}\n\n @classmethod\n def add_user(self, user: User):\n self.users.append(user)\n\n @classmethod\n def remove_user(self, user: User):\n self.users.remove(user)\n\n @classmethod\n def add_msg(self, msg: MessageEvent):\n self.history.append(msg)\n with Path(\"output.log\").open(\"a+\", encoding=\"utf8\") as f:\n f.write(msg.json(ensure_ascii=False) + \"\\n\")\n\n @classmethod\n def dealer(self, event: Event):\n def base(func: Callable):\n key = event.__event__\n func_list = self.dealer_dict.get(key, None)\n if not func_list:\n self.dealer_dict[key] = [func]\n else:\n func_list.append(func)\n return base\n\n def __init__(self, ws: WebSocket) -> None:\n self.uid = \"\"\n self.ws = ws\n self.logined = False\n self.add_user(self)\n log.success(self.ws.client, \"connect\")\n\n def disconnect(self):\n self.remove_user(self)\n log.success(self.ws.client, \"disconnect\")\n\n async def send(self, event: Event):\n data = event.dict()\n data[\"type\"] = event.__event__\n await self.ws.send_json(data)\n\n log.info(\"send\", data)\n\n async def handle_event(self, event: Event):\n log.info(\"recv\", event.__event__, event)\n\n func_list = self.dealer_dict.get(event.__event__, [])\n for func in func_list:\n await func(self, event)\n\n\n@User.dealer(MessageEvent)\nasync def forward(self: User, event: MessageEvent):\n # 添加到历史记录\n self.add_msg(event)\n\n # 转发\n users = [u for u in self.users if u.logined and u != self]\n for u in users:\n await u.send(event)\n\n\n@User.dealer(LoginEvent)\nasync def login(self: User, event: LoginEvent):\n # 发送初始化信息:uid、房间历史消息\n self.uid = event.uid if event.uid else get_uid()\n self.logined = True\n event = InitEvent(uid=self.uid, history=self.history)\n await self.send(event)\n","repo_name":"bridgeL/chat.vue.fastapi","sub_path":"user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"37394351019","text":"\"\"\"\nson-emu compute CLI\n(c) 2016 by Manuel Peuster \n\"\"\"\n\nimport argparse\nimport pprint\nfrom tabulate import tabulate\nimport zerorpc\n\n\npp = pprint.PrettyPrinter(indent=4)\n\n\nclass ZeroRpcClient(object):\n\n def __init__(self):\n self.c = zerorpc.Client(heartbeat=None, timeout=120) #heartbeat=None, timeout=120\n self.c.connect(\"tcp://127.0.0.1:4242\") # TODO hard coded for now. we'll change this later\n self.cmds = {}\n\n def execute_command(self, args):\n if getattr(self, args[\"command\"]) is not None:\n # call the local method with the same name as the command arg\n getattr(self, args[\"command\"])(args)\n else:\n print(\"Command not implemented.\")\n\n def start(self, args):\n nw_list = list()\n if args.get(\"network\") is not None:\n nw_list = self._parse_network(args.get(\"network\"))\n r = self.c.compute_action_start(\n args.get(\"datacenter\"),\n args.get(\"name\"),\n args.get(\"image\"),\n nw_list,\n args.get(\"docker_command\")\n )\n pp.pprint(r)\n\n def stop(self, args):\n r = self.c.compute_action_stop(\n args.get(\"datacenter\"), args.get(\"name\"))\n pp.pprint(r)\n\n def list(self, args):\n r = self.c.compute_list(\n args.get(\"datacenter\"))\n table = []\n for c in r:\n # for each container add a line to the output table\n if len(c) > 1:\n name = c[0]\n status = c[1]\n eth0ip = None\n eth0status = \"down\"\n if len(status.get(\"network\")) > 0:\n eth0ip = status.get(\"network\")[0].get(\"ip\")\n eth0status = \"up\" if status.get(\n \"network\")[0].get(\"up\") else \"down\"\n table.append([status.get(\"datacenter\"),\n name,\n status.get(\"image\"),\n eth0ip,\n eth0status,\n status.get(\"state\").get(\"Status\")])\n headers = [\"Datacenter\",\n \"Container\",\n \"Image\",\n \"eth0 IP\",\n \"eth0 status\",\n \"Status\"]\n print(tabulate(table, headers=headers, tablefmt=\"grid\"))\n\n def status(self, args):\n r = self.c.compute_status(\n args.get(\"datacenter\"), args.get(\"name\"))\n pp.pprint(r)\n\n def profile(self, args):\n nw_list = list()\n if args.get(\"network\") is not None:\n nw_list = self._parse_network(args.get(\"network\"))\n\n params = self._create_dict(\n network=nw_list,\n command=args.get(\"docker_command\"),\n image=args.get(\"image\"),\n input=args.get(\"input\"),\n output=args.get(\"output\"))\n\n for output in self.c.compute_profile(\n args.get(\"datacenter\"),\n args.get(\"name\"),\n params):\n print(output + '\\n')\n\n #pp.pprint(r)\n #print(r)\n\n def _create_dict(self, **kwargs):\n return kwargs\n\n def _parse_network(self, network_str):\n '''\n parse the options for all network interfaces of the vnf\n :param network_str: (id=x,ip=x.x.x.x/x), ...\n :return: list of dicts [{\"id\":x,\"ip\":\"x.x.x.x/x\"}, ...]\n '''\n nw_list = list()\n networks = network_str[1:-1].split('),(')\n for nw in networks:\n nw_dict = dict(tuple(e.split('=')) for e in nw.split(','))\n nw_list.append(nw_dict)\n\n return nw_list\n\n\n\nparser = argparse.ArgumentParser(description='son-emu compute')\nparser.add_argument(\n \"command\",\n choices=['start', 'stop', 'list', 'status', 'profile'],\n help=\"Action to be executed.\")\nparser.add_argument(\n \"--datacenter\", \"-d\", dest=\"datacenter\",\n help=\"Data center to in which the compute instance should be executed\")\nparser.add_argument(\n \"--name\", \"-n\", dest=\"name\",\n help=\"Name of compute instance e.g. 'vnf1'\")\nparser.add_argument(\n \"--image\",\"-i\", dest=\"image\",\n help=\"Name of container image to be used e.g. 'ubuntu:trusty'\")\nparser.add_argument(\n \"--dcmd\", \"-c\", dest=\"docker_command\",\n help=\"Startup command of the container e.g. './start.sh'\")\nparser.add_argument(\n \"--net\", dest=\"network\",\n help=\"Network properties of a compute instance e.g. \\\n '(id=input,ip=10.0.10.3/24),(id=output,ip=10.0.10.4/24)' for multiple interfaces.\")\nparser.add_argument(\n \"--input\", \"-in\", dest=\"input\",\n help=\"input interface of the vnf to profile\")\nparser.add_argument(\n \"--output\", \"-out\", dest=\"output\",\n help=\"output interface of the vnf to profile\")\n\n\ndef main(argv):\n args = vars(parser.parse_args(argv))\n c = ZeroRpcClient()\n c.execute_command(args)\n","repo_name":"xilouris/son-emu","sub_path":"src/emuvim/cli/compute.py","file_name":"compute.py","file_ext":"py","file_size_in_byte":4894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"26403215533","text":"# Import External Packages\nimport tkinter\n\n# Import Internal Packages\nfrom src.common.ui_util import UIUtil, Position\nfrom src.dashboard.dashboard_ui import DashboardUI\n\n# Class for Login Window UI\nfrom src.login.credential_manager import CredentialManager\n\n\nclass LoginUI(tkinter.Tk):\n # Utility and Libraries\n ui_util = None\n credential_manager = CredentialManager()\n\n # UI Fields\n account_select = None\n\n # Constructor\n def __init__(self):\n super().__init__()\n self.setup()\n\n # Methods\n def setup(self):\n self.title(\"NewCentury Auto Trader\")\n self.ui_util = UIUtil(self, 400, 200)\n self.geometry(self.ui_util.calc_geometry())\n self.resizable(False, False)\n self.launch()\n\n def launch(self):\n title = self.ui_util.make_title(\"Welcome\")\n account_select_label = self.ui_util.make_label(\n \"Account Choice: \",\n Position(45, 0, 100, 25), cst_x=None, cst_y=title\n )\n self.account_select = self.ui_util.make_combo_box([\n \"Test Account (모의투자)\",\n \"Real Account (실전투자)\"\n ], Position(10, 0, 200, 25), cst_x=account_select_label, cst_y=title, readonly=True)\n self.ui_util.make_button(\n \"Connect To Server\", Position(45, 10, 310, 40),\n cst_x=None, cst_y=self.account_select,\n onclick=self.login\n )\n\n def login(self):\n self.credential_manager.load_credentials(self.account_select.current(), self.open_dashboard)\n\n def open_dashboard(self):\n DashboardUI(self, self.credential_manager.get_api()).setup()\n self.withdraw()\n","repo_name":"NewCentury99/SJU_SW_Engneering","sub_path":"src/login/login_ui.py","file_name":"login_ui.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"33130047417","text":"import json\nimport os\nimport re\nimport subprocess\nimport sys\nimport unittest\nfrom datetime import datetime, timedelta\n\nfrom hec.heclib.dss import HecDSSFileAccess\n\nthis = \"/tiffdss/tests/integration\"\n\n\nclass TestDssConvert(unittest.TestCase):\n @staticmethod\n def convert_to_dss(tif, dss, *args):\n _args = \" \".join(args)\n cmd = \" \".join([\"tiffdss\", _args, tif, dss])\n proc = subprocess.Popen(\n cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n close_fds=True,\n shell=True,\n )\n stdout, stderr = proc.communicate()\n if stderr:\n return 0\n else:\n return 1\n\n @staticmethod\n def gdalinfo(tif):\n p = subprocess.Popen(\n \"gdalinfo -json {}\".format(tif),\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n close_fds=True,\n shell=True,\n )\n stdout, stderr = p.communicate()\n return stdout\n\n @classmethod\n def meta_time(cls, attr):\n pattern = re.compile(\"^(\\\\d+).*\")\n m = pattern.match(attr).group(1)\n dt = datetime.fromtimestamp(int(m))\n return dt\n\n def setUp(self):\n self.fixtures = os.path.join(this, \"fixtures\")\n self.dss7 = os.path.join(\"/tmp\", \"test7.dss\")\n self.dss6 = os.path.join(\"/tmp\", \"test6.dss\")\n if os.path.exists(self.dss7):\n os.remove(self.dss7)\n if os.path.exists(self.dss6):\n os.remove(self.dss6)\n test_products = os.path.join(this, \"fixtures\", \"test_products.json\")\n with open(test_products, \"r\") as f:\n self.products = json.load(f)\n\n def test_convert_tiff(self):\n for p, attr in self.products.items():\n self.p_path = os.path.join(self.fixtures, p)\n if os.path.exists(self.p_path):\n for dirpath, dirnames, filenames in os.walk(self.p_path):\n nrecords = 0\n for filename in filenames:\n tif = os.path.join(dirpath, filename)\n\n stdout = self.gdalinfo(tif)\n metadata_dict = json.loads(stdout)\n\n vtime = self.meta_time(\n metadata_dict[\"bands\"][0][\"metadata\"][\"\"][\"GRIB_VALID_TIME\"]\n )\n etime = vtime + timedelta(seconds=attr[\"data_interval\"])\n dsspath = \"/{}/{}/{}/{}/{}/{}/\".format(\n attr[\"apart\"],\n attr[\"bpart\"],\n attr[\"cpart\"],\n vtime.strftime(\"%d%b%Y:%H%M\").upper(),\n etime.strftime(\"%d%b%Y:%H%M\").upper(),\n attr[\"fpart\"],\n )\n # convert tiff to dss7\n self.convert_to_dss(\n tif,\n self.dss7,\n \"-d {}\".format(attr[\"data_type\"].upper()),\n \"-u {}\".format(attr[\"data_unit\"].upper()),\n \"-p '{}'\".format(dsspath),\n \"-m -999\",\n )\n nrecords += 1\n file_access = HecDSSFileAccess(self.dss7)\n dss_records = file_access.getNumberRecords()\n self.assertEqual(nrecords, dss_records)\n\n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)\n","repo_name":"HydrologicEngineeringCenter/tiffdss","sub_path":"tests/integration/test_dss_convert_tiff.py","file_name":"test_dss_convert_tiff.py","file_ext":"py","file_size_in_byte":3546,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"33504514251","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport datetime\n\n# Set display options for pandas for easier printing\npd.set_option('display.max_columns', 500)\npd.set_option('display.max_rows', 500)\npd.set_option('display.width', 1000)\n\n\nreddit = pd.read_csv('./data/reddit_data.csv')\n\n\ndef convert_date(date_in):\n if date_in is None or pd.isna(date_in):\n return None\n\n date = datetime.datetime.strptime(date_in.strip(), '%m %d %Y')\n return date\n\nreddit['DateIn'] = reddit['Date'].apply(convert_date)\nreddit['DateOut'] = reddit['Date Out'].apply(convert_date)\n\n\nreddit_dates = reddit[['DateIn', 'DateOut']]\n\nhashtag = pd.read_csv('./data/hashtag_data_2021.csv')\n\ndef convert_hashtag_date(date_in):\n if date_in is None or pd.isna(date_in):\n return None\n\n date = datetime.datetime.strptime(date_in.strip(), '%d %B %Y')\n return date\n\nhashtag['DateIn'] = hashtag['INJURED ON'].apply(convert_hashtag_date)\nhashtag['DateOut'] = hashtag['RETURNED'].apply(convert_hashtag_date)\n\nhashtag_dates = hashtag[['DateIn', 'DateOut']]\n\nall_dates = pd.concat([hashtag_dates, reddit_dates]).to_dict('records')\n\nday_count = 79\nstart_date = datetime.datetime.strptime('1 October 2021', '%d %B %Y')\n\ndates = []\nprotocol = []\n\nfor single_date in (start_date + datetime.timedelta(n) for n in range(day_count)):\n in_protocol = 0\n for p in all_dates:\n if single_date >= p['DateIn']:\n if pd.isnull(p['DateOut']) or single_date <= p['DateOut']:\n in_protocol += 1\n # print(single_date)\n # print(in_protocol)\n dates.append(single_date)\n protocol.append(in_protocol)\n\nplt.figure(figsize=(12,8))\nplt.plot(dates, protocol, color='red')\nplt.xlabel('Date')\nplt.ylabel('Players in Protocol')\nplt.title('NBA Players in Health and Safety Protocol By Date')\nplt.show()","repo_name":"rd11490/NBA_Tutorials","sub_path":"covidball/explore.py","file_name":"explore.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","stars":146,"dataset":"github-code","pt":"77"}
+{"seq_id":"15472005030","text":"import os\nfrom pathlib import Path\n\nimport setuptools\n\nfrom data_browser import version\n\nroot = Path(\"data_browser\")\ndata_files = []\nfor directory in (\"fe_build\", \"templates\", \"web_root\"):\n for path, _, filenames in os.walk(root / directory):\n for filename in filenames:\n data_files.append(os.path.join(\"..\", path, filename))\n\n\nsetuptools.setup(\n name=\"django-data-browser\",\n version=version,\n author=\"Gordon Wrigley\",\n author_email=\"gordon.wrigley@gmail.com\",\n description=\"Interactive user-friendly database explorer.\",\n long_description=Path(\"README.rst\").read_text(),\n long_description_content_type=\"text/x-rst\",\n url=\"https://github.com/tolomea/django-data-browser\",\n packages=setuptools.find_packages(exclude=[\"tests*\"]),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n python_requires=\">=3.7\",\n package_data={\"\": data_files},\n install_requires=[\"Django>=3.2\", \"hyperlink\", \"python-dateutil\", \"sqlparse\"],\n)\n","repo_name":"tolomea/django-data-browser","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","stars":260,"dataset":"github-code","pt":"77"}
+{"seq_id":"40157650830","text":"import csv\nimport matplotlib.pyplot as pyplot\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nimport numpy as np\n# getting training and testing data from full dataset\ndef create_dataset(dataset, look_back=1):\n\tdataX, dataY = [], []\n\tfor i in range(len(dataset)-look_back-1):\n\t\ta = dataset[i:(i+look_back)]\n\t\tdataX.append(a)\n\t\tdataY.append(dataset[i + look_back])\n\treturn np.array(dataX), np.array(dataY)\n# loading data from excel fille\nwith open('UOB1.csv') as csvfile:\n reader = csv.DictReader(csvfile)\n series=[]\n for row in reader:\n series.append(float(row['Close']))# select the Close row from full rows.\nseries= np.asarray(series)\n# given data\ndataset = series\n# split into train and test sets\ntrain_size = int(len(dataset) * 0.70)\ntest_size = len(dataset) - train_size\ntrain, test = dataset[0:train_size], dataset[train_size:len(dataset)]\nprint(len(train), len(test))\n#create the training and testind data\nlook_back = 1\ntrainX, trainY = create_dataset(train, look_back)\ntestX, testY = create_dataset(test, look_back)\n#create ANN model.\nmodel = Sequential()\nmodel.add(Dense(8, input_dim=look_back, activation='relu'))\nmodel.add(Dense(1))\n# fitting the model\nmodel.compile(loss='mean_squared_error', optimizer='adam')\nmodel.fit(trainX, trainY, epochs=20, batch_size=2, verbose=2)\n\n\n# Estimate model performance\ntrainScore = model.evaluate(trainX, trainY, verbose=0)\nprint('Train Score: %.2f MSE (%.2f RMSE)' % (trainScore, np.sqrt(trainScore)))\ntestScore = model.evaluate(testX, testY, verbose=0)\nprint('Test Score: %.2f MSE (%.2f RMSE)' % (testScore, np.sqrt(testScore)))\n\n# prediction with testind data\ntrainPredict = model.predict(trainX)\ntestPredict = model.predict(testX)\nMs=np.mean(testPredict)\nm=len(trainPredict)\n# shift train predictions for plotting\ntrainPredictPlot = dataset\ns=0.0\ns1=0.0\nfor i in range (look_back, m+look_back):\n\ttrainPredictPlot[i]=trainPredict[i-look_back][0]\n\nnum=0\ntestPredictPlot = dataset\n\nfor i in range (m+ (look_back * 2) + 1, len(dataset) - 1):\n\ttestPredictPlot[i]=testPredict[i-(m+ (look_back * 2) + 1)][0]\n\ts=s+abs(testPredict[i-(m+ (look_back * 2) + 1)][0]-testY[i-(m+ (look_back * 2) + 1)])\n\ts1 = s1 + abs(Ms - testY[i - (m + (look_back * 2) + 1)])\n\tnum+=1\nMAE=(s/num)\nMAPE=(s/num)*100\nRsquare=1-s/s1\nprint('MAE: %.2f ' % MAE)\nprint('MAPE: %.2f ' % MAPE)\nprint('RMSE: %.2f ' % np.sqrt(testScore))\nprint('Rsquare: %.2f ' % Rsquare)\n# plot baseline and predictions\n#pyplot.plot(dataset)\n#pyplot.show()\npyplot.plot(testY, 'b', label='Real Data', linewidth=1)\n #plt.show()#\npyplot.plot(testPredict, 'r', label='Prediction Data', linewidth=2)\n\npyplot.grid()\npyplot.title(\"ANN algorithm\")\npyplot.ylabel(\"Stock price\")\npyplot.xlabel(\"Time\")\npyplot.legend()\npyplot.show()\n\"\"\"\"\"\npyplot.plot(testX)\npyplot.show()\npyplot.plot(testPredict)\npyplot.show()\n\"\"\"","repo_name":"AlexandrKrainiy/time-series","sub_path":"ANN.py","file_name":"ANN.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"35061723018","text":"from dotenv import load_dotenv\nimport os\nimport requests\nfrom twilio.rest import Client\n\nload_dotenv()\n\nSTOCK = \"AAPL\"\nCOMPANY_NAME = \"Apple Inc\"\n\nSTOCK_ENDPOINT = \"https://www.alphavantage.co/query\"\nNEWS_ENDPOINT = \"https://newsapi.org/v2/everything\"\n\nstock_details = {\n \"function\": \"TIME_SERIES_DAILY\",\n \"symbol\": STOCK,\n \"apikey\": os.getenv('STOCK_API_KEY'),\n}\n\nstock_response = requests.get(STOCK_ENDPOINT, params=stock_details)\ndata = stock_response.json()[\"Time Series (Daily)\"]\nprice_values = [value for (key, value) in data.items()]\nprev_data = price_values[0]\nprev_closing_price = prev_data[\"4. close\"]\nprint(prev_closing_price)\n\nday_before_prev_data = price_values[1]\nday_before_prev_closing_price = day_before_prev_data[\"4. close\"]\nprint(day_before_prev_closing_price)\n\ndifference = float(prev_closing_price) - float(day_before_prev_closing_price)\nup_down = None\nif difference > 0:\n up_down = \"🚀🚀🚀🚀🚀🚀🚀\"\nelse:\n up_down = \"📉📉📉📉\"\n\nstock_diff = round((difference / float(prev_closing_price)) * 100)\nprint(stock_diff)\n\n\nif abs(stock_diff) > 1:\n news_params = {\n \"apiKey\": os.getenv('NEWS_API_KEY'),\n \"qInTitle\": COMPANY_NAME,\n }\n\n news_response = requests.get(NEWS_ENDPOINT, params=news_params)\n articles = news_response.json()[\"articles\"]\n\n three_articles = articles[:3]\n print(three_articles)\n\n\n formatted_articles = [f\"{STOCK}: {up_down}{stock_diff}%\\nHeadline: {article['title']}. \\nBrief: {article['description']}\" for article in three_articles]\n print(formatted_articles)\n client = Client(os.getenv('TWILIO_SID'), os.getenv('TWILIO_AUTH_TOKEN'))\n\n for article in formatted_articles:\n message = client.messages.create(\n body=article,\n from_=\"+19124945522\",\n to=os.getenv('MY_NUMBER') \n )\n","repo_name":"bomsolim/stock-sms-alert","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"72419689209","text":"# -*- coding: utf-8 -*-\nimport logging\nimport sys\n\nimport utool\nimport utool as ut\n\nfrom wbia.guitool import guitool_main\nfrom wbia.guitool.__PYQT__ import QtWidgets # NOQA\nfrom wbia.guitool.__PYQT__ import QtCore, QtGui\nfrom wbia.guitool.guitool_decorators import slot_\n\nut.noinject(__name__)\n\n\n# For some reason QtCore.Qt.ALT doesn't work right\nALT_KEY = 16777251\n\n\ndef make_option_dict(options, shortcuts=True):\n \"\"\"helper for popup menu callbacks\"\"\"\n keys = ut.take_column(options, 0)\n values = ut.take_column(options, 1)\n if shortcuts:\n shortcut_keys = [key[key.find('&') + 1] if '&' in key else None for key in keys]\n try:\n ut.assert_unique(shortcut_keys, name='shortcut_keys', ignore=[None])\n except AssertionError:\n print('shortcut_keys = {!r}'.format(shortcut_keys))\n print('options = {!r}'.format(ut.repr2(options)))\n raise\n shortcut_dict = {\n sc_key: val\n # sc_key: (make_option_dict(val, shortcuts=True)\n # if isinstance(val, list) else val)\n for (sc_key, val) in zip(shortcut_keys, values)\n if sc_key is not None and not isinstance(val, list)\n }\n return shortcut_dict\n else:\n ut.assert_unique(keys, name='option_keys')\n fulltext_dict = {\n key: (\n make_option_dict(val, shortcuts=False) if isinstance(val, list) else val\n )\n for (key, val) in zip(keys, values)\n if key is not None\n }\n return fulltext_dict\n\n\ndef find_used_chars(name_list):\n \"\"\"Move to guitool\"\"\"\n used_chars = []\n for name in name_list:\n index = name.find('&')\n if index == -1 or index + 1 >= len(name):\n continue\n char = name[index + 1]\n used_chars.append(char)\n return used_chars\n\n\ndef make_word_hotlinks(name_list, used_chars=[], after_colon=False):\n \"\"\"Move to guitool\n\n Args:\n name_list (list):\n used_chars (list): (default = [])\n\n Returns:\n list: hotlinked_name_list\n\n CommandLine:\n python -m wbia.guitool.guitool_misc --exec-make_word_hotlinks\n\n Example:\n >>> # DISABLE_DOCTEST\n >>> from wbia.guitool.guitool_misc import * # NOQA\n >>> name_list = ['occlusion', 'occlusion:large', 'occlusion:medium', 'occlusion:small', 'lighting', 'lighting:shadowed', 'lighting:overexposed', 'lighting:underexposed']\n >>> used_chars = []\n >>> hotlinked_name_list = make_word_hotlinks(name_list, used_chars)\n >>> result = ('hotlinked_name_list = %s' % (str(hotlinked_name_list),))\n >>> print(result)\n \"\"\"\n seen_ = set(used_chars)\n hotlinked_name_list = []\n for name in name_list:\n added = False\n if after_colon:\n split_chars = name.split(':')\n offset = len(':'.join(split_chars[:-1])) + 1\n avail_chars = split_chars[-1]\n else:\n offset = 0\n avail_chars = name\n for count, char in enumerate(avail_chars, start=offset):\n char = char.upper()\n if char not in seen_:\n added = True\n seen_.add(char)\n linked_name = name[:count] + '&' + name[count:]\n hotlinked_name_list.append(linked_name)\n break\n if not added:\n # Cannot hotlink this name\n hotlinked_name_list.append(name)\n return hotlinked_name_list\n\n\nclass BlockContext(object):\n def __init__(self, widget):\n self.widget = widget\n self.was_blocked = None\n\n def __enter__(self):\n self.was_blocked = self.widget.blockSignals(True)\n\n def __exit__(self, type_, value, trace):\n if trace is not None:\n print('[BlockContext] Error in context manager!: ' + str(value))\n return False # return a falsey value on error\n self.widget.blockSignals(self.was_blocked)\n\n\n# Qt object that will send messages (as signals) to the frontend gui_write slot\nclass GUILoggingSender(QtCore.QObject):\n write_ = QtCore.pyqtSignal(str)\n\n def __init__(self, write_slot):\n QtCore.QObject.__init__(self)\n self.write_.connect(write_slot)\n\n def write_gui(self, msg):\n self.write_.emit(str(msg))\n\n\nclass GUILoggingHandler(logging.StreamHandler):\n \"\"\"\n A handler class which sends messages to to a connected QSlot\n \"\"\"\n\n def __init__(self, write_slot):\n super(GUILoggingHandler, self).__init__()\n self.sender = GUILoggingSender(write_slot)\n\n def emit(self, record):\n try:\n msg = self.format(record) + '\\n'\n self.sender.write_.emit(msg)\n except (KeyboardInterrupt, SystemExit):\n raise\n except Exception:\n self.handleError(record)\n\n\nclass QLoggedOutput(QtWidgets.QTextEdit):\n def __init__(self, parent=None, visible=True):\n super(QLoggedOutput, self).__init__(parent)\n # QtWidgets.QTextEdit.__init__(self, parent)\n self.setAcceptRichText(False)\n self.setReadOnly(True)\n self.setVisible(visible)\n self.logging_handler = None\n if visible:\n self._initialize_handler()\n\n def setVisible(self, flag):\n if flag and self.logging_handler is None:\n # Make sure handler is initialized on first go\n self._initialize_handler()\n super(QLoggedOutput, self).setVisible(flag)\n\n def _initialize_handler(self):\n self.logging_handler = GUILoggingHandler(self.gui_write)\n utool.add_logging_handler(self.logging_handler)\n\n @slot_(str)\n def gui_write(outputEdit, msg_):\n # Slot for teed log output\n app = guitool_main.get_qtapp()\n # Write msg to text area\n outputEdit.moveCursor(QtGui.QTextCursor.End)\n # TODO: Find out how to do backspaces in textEdit\n msg = str(msg_)\n if msg.find('\\b') != -1:\n msg = msg.replace('\\b', '') + '\\n'\n outputEdit.insertPlainText(msg)\n if app is not None:\n app.processEvents()\n\n @slot_()\n def gui_flush(outputEdit):\n app = guitool_main.get_qtapp()\n if app is not None:\n app.processEvents()\n\n\ndef get_cplat_tab_height():\n if sys.platform.startswith('darwin'):\n tab_height = 21\n else:\n tab_height = 30\n return tab_height\n\n\ndef get_view_selection_as_str(view):\n \"\"\"\n References:\n http://stackoverflow.com/questions/3135737/copying-part-of-qtableview\n \"\"\"\n model = view.model()\n selection_model = view.selectionModel()\n qindex_list = selection_model.selectedIndexes()\n qindex_list = sorted(qindex_list)\n # print('[guitool] %d cells selected' % len(qindex_list))\n if len(qindex_list) == 0:\n return\n copy_table = []\n previous = qindex_list[0]\n\n def astext(data):\n \"\"\"Helper which casts model data to a string\"\"\"\n if not isinstance(data, str):\n text = repr(data)\n else:\n text = str(data)\n return text.replace('\\n', '').replace(',', '')\n\n #\n for ix in range(1, len(qindex_list)):\n text = astext(model.data(previous))\n copy_table.append(text)\n qindex = qindex_list[ix]\n\n if qindex.row() != previous.row():\n copy_table.append('\\n')\n else:\n copy_table.append(', ')\n previous = qindex\n\n # Do last element in list\n text = astext(model.data(qindex_list[-1]))\n copy_table.append(text)\n # copy_table.append('\\n')\n copy_str = str(''.join(copy_table))\n return copy_str\n\n\ndef set_qt_object_names(dict_):\n \"\"\"\n Hack to set qt object names from locals, vars, or general dict context\n \"\"\"\n for key, val in dict_.items():\n if hasattr(val, 'setObjectName'):\n val.setObjectName(key)\n","repo_name":"WildMeOrg/wildbook-ia","sub_path":"wbia/guitool/guitool_misc.py","file_name":"guitool_misc.py","file_ext":"py","file_size_in_byte":7850,"program_lang":"python","lang":"en","doc_type":"code","stars":61,"dataset":"github-code","pt":"77"}
+{"seq_id":"29425527419","text":"def divisores(numero):\n resultado=[]\n n=2\n while n 1:\n p.append(n)\n return p\n \na = factorization(int(input()))\nb = []\na.reverse()\nfor i in a:\n if i not in b:\n print(f'{i}^{a.count(i)}')\n b.append(i)","repo_name":"Noname-a/Py","sub_path":"lesson4.2.py","file_name":"lesson4.2.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"4222177554","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Calculating Priors to be used for Calibration Source Spectra\n# \n# Tim Molteno tim@elec.ac.nz\n# \n# A mini project on calculating the uncertainties in the source spectral parameters. The Perley and Butler catalogs are typically 0.5 - 1.5% accurate (Oleg, Personal Communication). What I'd like to do for inference is decide on a prior for the spectral parameters $I_0$ and $\\{a_i\\}$.\n# \n# \n# ## Part 2: Inference from original data\n# \n# This is tricky. The original data is referred to in [CASA Docs https://casadocs.readthedocs.io/en/stable/notebooks/memo-series.html#Flux-Calibrator-Models]. However exactly how this is done for each source is a bit opaque.\n# \n# In this part, we use the actual measurement data and estimates of likelihood to infer a source model with quantified uncertainty. We'll use the source J1939-6342, also known as 1934-638 in the B1950. The parameters of this source are determined (apparently) be references 1,3,4,5,6,8.\n# \n# Standards are: \n# * (1) Perley-Butler 2010, \n# * (2) Perley-Butler 2013, \n# * (3) Perley-Taylor 99, \n# * (4) Perley-Taylor 95\n# * (5) Perley 90, \n# * (6) Baars,\n# * (7) Scaife-Heald 2012, \n# * (8) Stevens-Reynolds 2016 [https://ui.adsabs.harvard.edu/link_gateway/2016ApJ...821...61P/doi:10.3847/0004-637X/821/1/61]\n# \n# The real source of data for J1939-6342 appears to be Reynolds [Reynolds, J. E. A revised flux scale for the AT Compact Array. AT Memo 39.3/040, 1994. https://archive-gw-1.kat.ac.za/public/meerkat/A-Revised-Flux-Scale-for-the-AT-Compact-Array.pdf] in the range 408MHz - 8.6GHz. And from [Partridge, B., et al. \"Absolute calibration of the radio astronomy flux density scale at 22 to 43 GHz using Planck.\" The Astrophysical Journal 821.1 (2016): 61.] in the higher frequency ranges.\n# \n\n# In[3]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport json\nimport os\nimport arviz as az\nfrom specfit import inference\nfrom specfit import posterior_helper\nimport h5py\nimport specfit\n\n\n# The following coefficients are from J.E. Reynolds.\n\n# In[2]:\n\n\nsrc = { 'name': 'J1939-6342',\n 'nu0': 1e6,\n 'a': [-30.7667, 26.4908, -7.0977, 0.605334]}\nname = src['name']\nnu0 = src['nu0']\na_array = src['a']\n\n\n# In[3]:\n\n\ndef log_flux(w, logw, a):\n logS = a[0]\n for i in range(1,len(a)):\n logS += a[i]*logw**i\n \n return logS\n\ndef flux(nu, a, nu0):\n w = nu/nu0\n logw = np.log(w)\n \n logS = log_flux(w, logw, a)\n return np.exp(logS)\n\n\n# In[4]:\n\n\nfig, ax0 = plt.subplots(nrows=1, sharex=True)\nnu = np.linspace(0.5e9, 10e9, 100)\n\nf = flux(nu, src['a'],src['nu0'])\nax0.loglog(nu/1e9, f, '-', label=src['name'])\nax0.grid(True)\n# ax0.yaxis.set_major_formatter(mpl.ticker.ScalarFormatter())\n#ax0.set_xscale(\"log\", nonpositive='clip')\n#ax0.set_yscale(\"log\", nonpositive='clip')\nax0.set_xlabel(\"Frequency (GHz)\")\nax0.set_ylabel(\"Flux (Jy)\")\nplt.title(f\"Polynomial Model Source Spectrum\")\nax0.legend();\nplt.tight_layout()\nplt.savefig('source_original_spectrum.pdf')\n\n\n# ## Original Data\n# \n# We'll reconstruct the fit from the original data of Reynolds (1994). A discussion of this data is avaialable [here](https://www.narrabri.atnf.csiro.au/observing/users_guide/html_old_20090512/Flux_Density_Measurements.html)\n\n# In[5]:\n\n\nimport pymc as pm\nimport pytensor.tensor as tt\n\n\n# In[6]:\n\n\ndefault_percent_uncertainty = 5.0\n\n# AT Compact Array using the calibrator 3C286 as the reference. \n# The total flux was estimated by using only the shortest interferometer spacings or\n# by extrapolating the flux density to zero spacing (eg McConnell & McKay 1994). \nd_atca = default_percent_uncertainty / 100\n\n# Single dish using parkes and Hydra A (occasionally Virgo A as reference)\nd_parkes = default_percent_uncertainty / 100 \nd_jer = default_percent_uncertainty / 100 ## J.E. Reynolds 1994 Tidbinbilla single dish using parkes and Hydra A (occasionally Virgo A as reference)\n\n# The Molonglo Reference Catalogue (MRC) at 408MHz is on the scale of Wyllie (1969) \nd_mrc = default_percent_uncertainty / 100 \n\n# MOST (Campbell-Wilson & Hunstead 1994) The MOST flux scale at 843MHz is essentially an \n# interpolation between the Wyllie 408MHz scale and the scale of the Parkes Catalogue.\n# See Hunstead (1991) for further details.\nd_most = default_percent_uncertainty / 100 \n\norig_measured_data = np.array(\n [[0.408, 6.24, d_mrc],\n [0.843, 13.65, d_most],\n [1.380, 14.96, d_atca],\n [1.413, 14.87, d_parkes],\n [1.612, 14.47, d_parkes],\n [1.660, 14.06, d_parkes],\n [1.665, 14.21, d_jer],\n [2.295, 11.95, d_jer],\n [2.378, 11.75, d_atca],\n [4.800, 5.81, d_atca],\n [4.800, 5.76, d_atca],\n [4.835, 5.72, d_atca],\n [4.850, 5.74, d_parkes],\n [8.415, 2.99, d_atca],\n [8.420, 2.97, d_jer],\n [8.640, 2.81, d_atca],\n [8.640, 2.81, d_atca]])\n\norig_measured_data = orig_measured_data.T\n\n\n# In[46]:\n\n\nnu = orig_measured_data[0]*1e9\nmeasured_data = orig_measured_data[1]\npercent = orig_measured_data[2]\nsigma = measured_data*percent\n\nnew_d = np.array([nu/1e9, measured_data, sigma]).T\n#print(f\"Original Data:\\n{np.array2string(new_d, separator=', ', precision=4)}\")\n\nmin_freq = nu[0]\nmax_freq = nu[-1]\n\n#nu, measured_data\n\n\n# In[8]:\n\n\nfig, ax0 = plt.subplots(nrows=1, sharex=True, figsize=(8,6))\nax0.set_xscale(\"log\", nonpositive='clip')\nax0.set_yscale(\"log\", nonpositive='clip')\nax0.errorbar(nu/1e9, measured_data, yerr=sigma, fmt='.')\nax0.grid(True)\nax0.set_title('Flux Measurements J1939-6342')\nax0.set_xlabel(\"Frequency (GHz)\")\nax0.set_ylabel(\"Flux (Jy)\")\nfig.tight_layout()\nplt.savefig('j1939_measurements.pdf')\n\n\n# ## Choosing priors\n# \n# These need to be chosen carefully. I0 is the value of the flux at $\\nu = \\nu_0$, and in this case we choose $\\nu_0$ to be one of the data points close to the usual choice.\n\n# In[9]:\n\n\nnu0 = 1.0e9 # nu[3];\n\n\norder=4\nwith pm.Model() as model:\n \n # Choose priors\n a_1 = [ pm.Normal(f\"a[{i}]\", mu=0, sigma=2.5) for i in range(order) ]\n print(a_1)\n brightness_1 = flux(nu, a_1, nu0)\n\n # likelihood_1 = pm.Normal(\"likelihood\", mu=brightness_1, sigma=sigma, observed=measured_data)\n likelihood_1 = pm.StudentT(\"likelihood\", nu=5, mu=brightness_1, sigma=sigma, observed=measured_data)\n\n\n# In[10]:\n\n\nwith model:\n prior_checks = pm.sample_prior_predictive(samples=50, return_inferencedata=False)\n\nprint(\"test\")\nprint(prior_checks.keys())\n_, ax = plt.subplots()\n\nax.set_xscale(\"log\", nonpositive='clip')\nax.set_yscale(\"log\", nonpositive='clip')\n\nfor a0, a1, a2, a3 in zip( prior_checks[\"a[0]\"],\n prior_checks[\"a[1]\"],\n prior_checks[\"a[2]\"],\n prior_checks[\"a[3]\"]\n ):\n b = flux(nu, [a0, a1, a2, a3], nu0)\n ax.plot(nu/1e9, b, c=\"k\", alpha=0.4)\nax.plot(nu/1e9, measured_data, c=\"b\", alpha=1, label=\"J1939-6342\")\n\nax.set_xlabel(\"Frequency (GHz)\")\nax.set_ylabel(\"Flux (Jy)\")\nax.set_title(\"Prior predictive checks\");\nax.grid(True)\nax.legend()\nplt.tight_layout()\nplt.savefig(\"original_prior_predictive.pdf\")\n\n\n# Now sample from the model, producing a chain...\n\n# In[11]:\n\n\nidata_j1939 = inference.run_or_load(model, fname = \"idata_j1939.nc\",\n n_samples = 5000, n_tune=3000, n_chains=4)\n\n\n# ## Results\n# \n# \n\n# In[12]:\n\n\nstats = pm.summary(idata_j1939)\nprint(stats.to_string())\n\n\n# In[13]:\n\n\naz.plot_pair(\n idata_j1939,\n var_names=['a['],\n kind=\"hexbin\",\n filter_vars=\"like\",\n marginals=True,\n figsize=(12, 12),\n );\nplt.savefig('posterior_pairs_J1939.pdf')\n\n\n# The covariance of the parameters is clearly significant. We can estimate this numerically.\n\n# In[14]:\n\n\na_cov, a_corr, names = posterior_helper.chain_covariance(idata_j1939)\nnp.set_printoptions(precision=4, suppress=False)\na_cov\nstats, names = posterior_helper.get_stats(idata_j1939)\n\nwith h5py.File('calibrator_catalogue.hdf5', 'a') as f:\n grp = f.create_group(\"J1939-6342\")\n ds_mean = grp.create_dataset(\"mean\", data=stats[0])\n ds_sdev = grp.create_dataset(\"sdev\", data=stats[1])\n ds_cov = grp.create_dataset(\"cov\", data=a_cov)\n ds_cor = grp.create_dataset(\"corr\", data=a_corr)\n\n# In[15]:\n\nofile = open(\"j1939.tex\", 'w')\n\nposterior_helper.full_column(outfile=ofile, all_names=[\"J1939-6342\"], idata=idata_j1939, freq=nu) # outfile, all_names, idata, freq\n\n\n# ### Posterior Predictive Sampling\n# \n# Sanity check to see that we are producing reasonable spectra.\n\n# In[18]:\n\n\nRANDOM_SEED=123\nwith model:\n ppc = pm.sample_posterior_predictive(\n idata_j1939, random_seed=RANDOM_SEED, return_inferencedata=False\n )\n\n\n# In[19]:\n\n\n#ppc\n#az.plot_ppc(az.from_pymc3(posterior_predictive=ppc, model=model));\n\n\n# In[20]:\n\n\n_, ax = plt.subplots()\nax.plot(nu, measured_data, \"o\", ms=4, alpha=0.4, label=\"Data\")\naz.plot_hdi(\n nu,\n ppc[\"likelihood\"],\n ax=ax,\n fill_kwargs={\"alpha\": 0.8, \"color\": \"#a1dab4\", \"label\": \"Outcome 94% HDI\"},\n)\n\nax.set_xlabel(\"Frequency (GHz)\")\nax.set_ylabel(\"Flux (Jy)\")\nax.set_title(\"Posterior predictive checks\")\nax.legend(ncol=2, fontsize=10);\nplt.savefig('posterior_predictive_j1939.pdf')\n\n\n# ## Validation against usual fit\n# \n# Now have a look at the new spectral fit, taken by using the mean of the posterior parameters, against the polynomial of Reynolds (1994).\n\n# In[21]:\n\n\na = [ idata_j1939.posterior.mean().get(f\"a[{i}]\").values.tolist() for i in range(order)]\n\n\n# In[22]:\n\n\nprint(f\"The mean value nu0 = {nu0} and a={a}, i0={10**a[0]}\")\n\n\n# Now form the spectrum from the mean posterior values and compare it to the Reynolds model (using the Perley butler source spectral characteristics)\n\n# In[23]:\n\n\nnu_new = np.linspace(0.4e9, 10e9, 1000)\nb_new = flux(nu_new, a, nu0)\nb_pb = flux(nu_new, src['a'],src['nu0'])\n\n\n# In[24]:\n\n\n_, ax = plt.subplots()\n\nax.set_xscale(\"log\", nonpositive='clip')\nax.set_yscale(\"log\", nonpositive='clip')\nax.plot(nu_new, b_pb, c=\"k\", alpha=0.4, label=\"Reynolds (1994)\")\nax.plot(nu_new, b_new, '-.', c=\"g\", alpha=1, label=\"This work\")\nax.plot(nu_new, np.abs(b_new-b_pb), c=\"r\", alpha=1, label='difference $\\Delta S$')\nax.plot(nu, measured_data, 'o', c=\"b\", alpha=1, label=\"Measurements\")\n\nax.legend()\nax.set_xlabel(\"Frequency (GHz)\")\nax.set_ylabel(\"Flux (Jy)\")\nax.set_ylim((0.001, 20))\nax.grid(True)\nax.set_title(\"Comparison of Models\");\nplt.savefig('model_comparison.pdf')\n\n\n# In[25]:\n\n\nds =(np.abs(b_new - b_pb))\nnp.percentile(ds, [0.05, 0.5, 0.95, 0.99, 1])\n\n\n# In[26]:\n\n\nimport matplotlib as mpl\n\ndef mean_val(key):\n return idata_j1939.posterior[key].mean().values.tolist()\n\na_mean = [mean_val(f\"a[{i}]\") for i in range(order)]\n\n\nfig, ax = plt.subplots()\n\n\nax.set_xscale(\"log\", nonpositive='clip')\nax.set_yscale(\"log\")\nfor n in np.geomspace(min_freq, max_freq, 50):\n for i in range(100):\n a = posterior_helper.get_random_sample(idata_j1939)\n b_test = flux(n, a, nu0)\n\n if False:\n b_ref = flux(n, a_mean, nu0)\n ax.plot(n/1e9, 1000*(b_ref-b_test), '.', c=\"k\", alpha=0.05)\n else:\n ax.plot(n/1e9, b_test, '.', c=\"k\", alpha=0.05)\n\nax.set_xlabel(\"Frequency (GHz)\")\nax.set_ylabel(\"Flux (Jy))\")\nax.set_title(\"Posterior Spectrum PDF (J1939-6342)\")\nax.grid(True);\nfig.tight_layout()\nplt.savefig('posterior_spectrum_j1939.pdf')\n\n\n# In[27]:\n\n\n## Now sample from a multivariate gaussian of the polynomial model\norder=4\nmean = [ idata_j1939.posterior.mean().get(f\"a[{i}]\").values.tolist() for i in range(order)]\na_cov, a_corr, names = posterior_helper.chain_covariance(idata_j1939)\nprint(mean)\nprint(a_cov)\nsamples_cov = np.random.multivariate_normal(mean, a_cov, 100)\n\ndiag_cov = np.zeros_like(a_cov)\ndiag_cov[np.diag_indices(a_cov.shape[0])] = np.diag(a_cov)\nprint(diag_cov)\nsamples_diag = np.random.multivariate_normal(mean, diag_cov, 100)\nfig, ax = plt.subplots(2, sharex=True, sharey=True, figsize=(7,7))\nax0, ax1 = ax\n\nax0.set_xscale(\"log\", nonpositive='clip')\nax0.set_yscale(\"log\")\n\nfifth = []\nfiftieth = []\nninetyfifth = []\n\nnu = np.geomspace(min_freq, max_freq, 50)\n\nfor n in nu:\n fluxes = np.array([flux(n, a, nu0) for a in samples_cov])\n for s in fluxes:\n ax0.plot(n/1e9, s, '.', c=\"k\", alpha=0.05)\nax0.set_title(\"Posterior with covariance\")\nax0.grid(True);\nax0.set_ylabel(\"Flux (Jy))\")\n\nfor n in nu:\n fluxes = np.array([flux(n, a, nu0) for a in samples_diag])\n for s in fluxes:\n ax1.plot(n/1e9, s, '.', c=\"k\", alpha=0.05)\nax1.set_title(\"Posterior without covariance\")\nax1.grid(True);\nax1.set_xlabel(\"Frequency (GHz)\")\nax1.set_ylabel(\"Flux (Jy))\")\n \n# b_test = flux(n, a, nu0)\n\n# if False:\n# b_ref = flux(n, a_mean, nu0)\n# ax.plot(n/1e9, 1000*(b_ref-b_test), '.', c=\"k\", alpha=0.05)\n# else:\n# ax.plot(n/1e9, b_test, '.', c=\"k\", alpha=0.1)\n\n#fig.set_title(\"Posterior Spectrum PDF (J1939-6342)\")\nfig.tight_layout()\nplt.savefig('posterior_spectrum_model_j1939.pdf')\n\n\n# ## Discussion\n# \n# The new polynomial fit is fairly accurate, within 50 $\\mu$Jy. Of more importance is that the uncertainty in the polynomial coefficients can be quantified, and mapped through to uncertainty in the spectrum. This allows the parameters of the model to be used as priors for a Bayesian calibration.\n\n# ## Northern Sky Calibrators\n# \n# Table 9\n# Adopted Spectral Flux Densities of Steady Sources\n# \n# Notes. The derived flux density values, based on the Mars emission model for frequencies between 1 and 50 GHz. The quoted errors are derived from the dispersion of the values over the various sessions. The values for 3C123, 3C286, and 3C295 at 327.5 MHz are derived from their ratios to 3C196, whose flux density is taken to be 46.8 Jy (Scaife & Heald 2012).\n# \n\n# In[28]:\n\n\n# Freq., 3C123, , 3C196, , 3C286, , 3C295, , N_obs\n# (GHz), S(Jy), sigma(Jy), S(Jy), sigma(Jy), S(Jy), sigma(Jy), S(Jy), sigma(Jy)\n\ncsv_data = '''0.3275, 145.0, 4.3, 46.8, 1.4, 26.1, 0.8, 60.8, 1.8, 14\n1.015, 66.2, 4.3, 20.1, 4.8, 18.4, 4.3, 30.8, 7.3, 1\n1.275, 46.6, 3.2, 13.3, 2.0, 13.8, 2.0, 21.5, 3.0, 1\n1.465, 47.8, 0.5, 14.1, 0.2, 15.0, 0.2, 22.2, 0.5, 4\n1.865, 38.7, 0.6, 11.3, 0.2, 13.2, 0.2, 17.9, 0.3, 2\n2.565, 28.9, 0.3, 8.16, 0.1, 10.9, 0.2, 12.8, 0.2, 2\n3.565, 21.4, 0.8, 6.22, 0.2, 9.5, 0.1, 9.62, 0.2, 3\n4.535, 16.9, 0.2, 4.55, 0.06, 7.68, 0.1, 6.96, 0.09, 7\n4.835, 16.0, 0.2, 4.22, 0.1, 7.33, 0.2, 6.45, 0.15, 1\n4.885, 15.88, 0.1, 4.189, 0.025, 7.297, 0.046, 6.37, 0.04, 11\n6.135, 12.81, 0.15, 3.318, 0.05, 6.49, 0.15, 4.99, 0.05, 2\n6.885, 11.20, 0.14, 2.85, 0.05, 5.75, 0.05, 4.21, 0.05, 3\n7.465, 11.01, 0.2, 2.79, 0.05, 5.70, 0.10, 4.13, 0.07, 1\n8.435, 9.20, 0.04, 2.294, 0.010, 5.059, 0.021, 3.319, 0.014, 11\n8.485, 9.10, 0.15, 2.275, 0.03, 5.045, 0.07, 3.295, 0.05, 1\n8.735, 8.86, 0.05, 2.202, 0.011, 4.930, 0.024, 3.173, 0.016, 10\n11.06, 6.73, 0.15, 1.64, 0.03, 4.053, 0.08, 2.204, 0.05, 1\n12.890, , , 1.388, 0.025, 3.662, 0.070, 1.904, 0.04, 1\n14.635, 5.34, 0.05, 1.255, 0.020, 3.509, 0.040, 1.694, 0.04, 1\n14.715, 5.02, 0.05, 1.206, 0.020, 3.375, 0.040, 1.630, 0.03, 1\n14.915, 5.132, 0.025, 1.207, 0.004, 3.399, 0.016, 1.626, 0.008, 7\n14.965, 5.092, 0.028, 1.198, 0.007, 3.387, 0.015, 1.617, 0.007, 11\n17.422, 4.272, 0.07, 0.988, 0.02, 2.980, 0.04, 1.311, 0.025, 1\n18.230, , , 0.932, 0.020, 2.860, 0.045, 1.222, 0.05, 1\n18.485, 4.090, 0.055, 0.947, 0.015, 2.925, 0.045, 1.256, 0.020, 1\n18.585, 3.934, 0.055, 0.926, 0.015, 2.880, 0.04, 1.221, 0.015, 1\n20.485, 3.586, 0.055, 0.820, 0.010, 2.731, 0.05, 1.089, 0.015, 1\n22.460, 3.297, 0.022, 0.745, 0.003, 2.505, 0.016, 0.952, 0.005, 13\n22.835, 3.334, 0.06, 0.760, 0.010, 2.562, 0.05, 0.967, 0.015, 1\n24.450, 2.867, 0.03, 0.657, 0.017, 2.387, 0.03, 0.861, 0.020, 2\n25.836, 2.697, 0.06, 0.620, 0.017, 2.181, 0.06, 0.770, 0.02, 1\n26.485, 2.716, 0.05, 0.607, 0.017, 2.247, 0.05, 0.779, 0.020, 1\n28.450, 2.436, 0.06, 0.568, 0.015, 2.079, 0.05, 0.689, 0.020, 2\n29.735, 2.453, 0.05, 0.529, 0.015, 2.011, 0.05, 0.653, 0.020, 1\n36.435, 1.841, 0.17, 0.408, 0.005, 1.684, 0.02, 0.484, 0.015, 3\n43.065, , , 0.367, 0.015, 1.658, 0.08, 0.442, 0.020, 1\n43.340, 1.421, 0.055, 0.342, 0.005, 1.543, 0.024, 0.398, 0.006, 13\n48.350, 1.269, 0.12, 0.289, 0.005, 1.449, 0.04, 0.359, 0.013, 4\n48.565, , , 0.272, 0.015, 1.465, 0.1, 0.325, 0.025, 1\n'''\n\n'''\n# In[29]:\n\n\nimport csv\nimport io\nimport numpy as np\nbuff = io.StringIO(csv_data)\n\ndef parse(x):\n try:\n return float(x)\n except:\n return None\n \nreader = csv.reader(buff)\nlines = []\nfor row in reader:\n \n line = [parse(x) for x in row]\n lines.append(line)\n\n\ndef cleanup(line, sigma, freq):\n good = np.where(np.isnan(line) == False)\n return line[good], sigma[good], freq[good]\n\nlines = np.array(lines, dtype=np.float64).T\nfrequency = lines[0]*1e9\nS_3C123 = lines[1]\nsigma_3C123 = lines[2]\n\nS_3C196 = lines[3]\nsigma_3C196 = lines[4]\n\nS_3C286 = lines[5]\nsigma_3C286 = lines[6]\n\nS_3C295 = lines[7]\nsigma_3C295 = lines[8]\n\nmin_freq = frequency[0]\nmax_freq = frequency[-1]\n\nS_3C123, sigma_3C123, f_3C123 = cleanup(S_3C123, sigma_3C123, frequency)\n\n\n# In[30]:\n\n\n\ndef dataplot(name, freq, mu, sigma):\n fig, ax = plt.subplots()\n\n ax.set_xscale(\"log\", nonpositive='clip')\n ax.set_yscale(\"log\", nonpositive='clip')\n ax.errorbar(freq/1e9, mu, yerr=sigma, fmt='.', label=\"Perley & Butler\")\n\n ax.set_xlabel(\"Frequency (GHz)\")\n ax.set_ylabel(\"Flux (Jy)\")\n ax.grid(True)\n ax.set_title(f\"Flux Measurements: {name}\");\n fig.tight_layout()\n plt.savefig(f\"source_{name}_spectrum.pdf\")\n \ndef spectral_inference(name, freq, mu, sigma, order, nu0):\n dataplot(name, freq, mu, sigma)\n with pm.Model() as _model:\n _a = [ pm.Normal(f\"a[{i}]\", mu=0, sigma=2.5) for i in range(order) ]\n _brightness = flux(freq, _a, nu0)\n _likelihood = pm.Normal(\"likelihood\", mu=_brightness, sigma=sigma, observed=mu)\n _idata = posterior_helper.run_or_load(_model, fname = f\"idata_{name}.nc\")\n \n posterior_helper.full_column(name, _idata, freq)\n\n \nS_3C286, f_3C123\n\n\n# In[31]:\n\n\nnu0 = 1e9\nspectral_inference(\"3C123\", f_3C123, S_3C123, sigma_3C123, order=4, nu0=nu0)\n\n\n# In[32]:\n\n\nspectral_inference(\"3C196\", frequency, S_3C196, sigma_3C196, order=4, nu0=nu0)\n\n\n# In[33]:\n\n\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots()\n\nax.set_xscale(\"log\", nonpositive='clip')\nax.set_yscale(\"log\", nonpositive='clip')\nax.errorbar(frequency/1e9, S_3C286, yerr=sigma_3C286, fmt='.', label=\"Perley & Butler\")\n\n#ax.legend()\nax.set_xlabel(\"Frequency (GHz)\")\nax.set_ylabel(\"Flux (Jy)\")\nax.grid(True)\nax.set_title(\"Flux Measurements 3C286\");\nfig.tight_layout()\nplt.savefig('source_3c286_spectrum.pdf')\n\n\n# In[34]:\n\n\nnu0 = 1e9\norder=4\n\n \nwith pm.Model() as model_3c286:\n \n a_1 = [ pm.Normal(f\"a[{i}]\", mu=0, sigma=2.5) for i in range(order) ]\n\n brightness_1 = flux(frequency, a_1, nu0)\n\n likelihood_1 = pm.Normal(\"likelihood\", mu=brightness_1, sigma=sigma_3C286, observed=S_3C286)\n \nwith pm.Model() as model_3c295:\n \n a_1 = [ pm.Normal(f\"a[{i}]\", mu=0, sigma=2.5) for i in range(order) ]\n\n brightness_1 = flux(frequency, a_1, nu0)\n\n likelihood_1 = pm.Normal(\"likelihood\", mu=brightness_1, sigma=sigma_3C295, observed=S_3C295)\n\n\n# In[35]:\n\n\nidata_3c286 = posterior_helper.run_or_load(model_3c286, fname = \"idata_3c286.nc\")\nidata_3c295 = posterior_helper.run_or_load(model_3c295, fname = \"idata_3c295.nc\")\n\n\n# In[36]:\n\n\nstats = pm.summary(idata_3c286)\nprint(stats.to_string())\n\n\n# In[37]:\n\n\nstats = pm.summary(idata_3c295)\nprint(stats.to_string())\n\n\n# In[38]:\n\n\naz.plot_pair(\n idata_3c286,\n var_names=['a['],\n kind=\"hexbin\",\n filter_vars=\"like\",\n marginals=True,\n figsize=(12, 12),\n );\nplt.savefig('posterior_pairs_3c286.pdf')\n\n\n# In[39]:\n\n\nposterior_helper.idata_2_latex(idata_3c286)\n\n\n# This should be compared to the values provided by Perley & Butler (2017) of\n# \n# 1.2515 ± 0.0048 \t−0.4605 ± 0.0163 \t−0.1715 ± 0.0208 \t0.0336 ± 0.0082\n\n# In[40]:\n\n\na_cov, a_corr, names = posterior_helper.chain_covariance(idata_3c286)\nnp.set_printoptions(precision=4, suppress=False)\nprint(\"Covariance\")\nprint(a_cov)\nprint(\"Correlation\")\nprint(a_corr)\n\n\n# In[41]:\n\nofile = open(\"3C286.tex\", 'w')\n\nposterior_helper.full_column(ofile, \"3C286\", idata_3c286, frequency)\n\n\n# In[42]:\n\n\nposterior_helper.full_column(ofile, \"3C295\", idata_3c295, frequency)\n\n\n# In[43]:\n\n\na_cov, a_corr, names = posterior_helper.chain_covariance(idata_3c286)\n\n\n# In[44]:\n\n\ndef mean_val(key):\n return idata_3c286.posterior[key].mean().values.tolist()\n\na_mean = [mean_val(f\"a[{i}]\") for i in range(order)]\n\n\n_, ax = plt.subplots()\n\n\nax.set_xscale(\"log\", nonpositive='clip')\nax.set_yscale(\"log\")\nfor n in np.geomspace(min_freq, max_freq, 50):\n for i in range(100):\n a = posterior_helper.get_random_sample(idata_3c286)\n b_test = flux(n, a, nu0)\n\n if False:\n b_ref = flux(n, a_mean, nu0)\n ax.plot(n/1e9, 1000*(b_ref-b_test), '.', c=\"k\", alpha=0.05)\n else:\n ax.plot(n/1e9, b_test, '.', c=\"k\", alpha=0.1)\n\nax.set_xlabel(\"Frequency (GHz)\")\nax.set_ylabel(\"Flux (Jy))\")\nax.set_title(\"Posterior Spectrum PDF (3C286)\")\nax.grid(True);\nplt.savefig('posterior_spectrum_3c286.pdf')\n\n\n# ## \n\n'''\n","repo_name":"tmolteno/specfit","sub_path":"examples/SourceOriginal.py","file_name":"SourceOriginal.py","file_ext":"py","file_size_in_byte":21281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"23102031325","text":"def print_formatted(num):\n max_indent = len(bin(num).replace('0b', ''))\n \n for number in range(1, num):\n decimal = str(number).rjust(max_indent)\n octal = oct(number).replace(\"0o\", \"\").rjust(max_indent)\n hexadecimal = hex(number).replace(\"0x\", \"\").upper().rjust(max_indent)\n # binary = \" \" * (max_indent - len(bin(number).replace(\"0b\",\"\"))) + bin(number).replace(\"0b\", \"\")\n binary = bin(number).replace(\"0b\",\"\")\n print(decimal + \" \" + octal + \" \" + hexadecimal + \" \" + binary.rjust(max_indent))\n\nif __name__ == \"__main__\":\n n = int(input())\n\n print_formatted(n)","repo_name":"nssathish/hackerrank-python","sub_path":"math_table2.py","file_name":"math_table2.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"1994131256","text":"import inspect\nimport logging\nimport sys\nfrom collections.abc import Callable\nfrom contextlib import contextmanager\nfrom importlib import import_module\nfrom typing import Any, Dict, Generator, List, Optional, Tuple, Type, Union\n\nfrom rich.console import Console\nfrom rich.table import Table\n\nfrom mmengine.config.utils import MODULE2PACKAGE\nfrom mmengine.utils import get_object_from_string, is_seq_of\nfrom .default_scope import DefaultScope\n\n\nclass Registry:\n \"\"\"A registry to map strings to classes or functions.\n\n Registered object could be built from registry. Meanwhile, registered\n functions could be called from registry.\n\n Args:\n name (str): Registry name.\n build_func (callable, optional): A function to construct instance\n from Registry. :func:`build_from_cfg` is used if neither ``parent``\n or ``build_func`` is specified. If ``parent`` is specified and\n ``build_func`` is not given, ``build_func`` will be inherited\n from ``parent``. Defaults to None.\n parent (:obj:`Registry`, optional): Parent registry. The class\n registered in children registry could be built from parent.\n Defaults to None.\n scope (str, optional): The scope of registry. It is the key to search\n for children registry. If not specified, scope will be the name of\n the package where class is defined, e.g. mmdet, mmcls, mmseg.\n Defaults to None.\n locations (list): The locations to import the modules registered\n in this registry. Defaults to [].\n New in version 0.4.0.\n\n Examples:\n >>> # define a registry\n >>> MODELS = Registry('models')\n >>> # registry the `ResNet` to `MODELS`\n >>> @MODELS.register_module()\n >>> class ResNet:\n >>> pass\n >>> # build model from `MODELS`\n >>> resnet = MODELS.build(dict(type='ResNet'))\n >>> @MODELS.register_module()\n >>> def resnet50():\n >>> pass\n >>> resnet = MODELS.build(dict(type='resnet50'))\n\n >>> # hierarchical registry\n >>> DETECTORS = Registry('detectors', parent=MODELS, scope='det')\n >>> @DETECTORS.register_module()\n >>> class FasterRCNN:\n >>> pass\n >>> fasterrcnn = DETECTORS.build(dict(type='FasterRCNN'))\n\n >>> # add locations to enable auto import\n >>> DETECTORS = Registry('detectors', parent=MODELS,\n >>> scope='det', locations=['det.models.detectors'])\n >>> # define this class in 'det.models.detectors'\n >>> @DETECTORS.register_module()\n >>> class MaskRCNN:\n >>> pass\n >>> # The registry will auto import det.models.detectors.MaskRCNN\n >>> fasterrcnn = DETECTORS.build(dict(type='det.MaskRCNN'))\n\n More advanced usages can be found at\n https://mmengine.readthedocs.io/en/latest/advanced_tutorials/registry.html.\n \"\"\"\n\n def __init__(self,\n name: str,\n build_func: Optional[Callable] = None,\n parent: Optional['Registry'] = None,\n scope: Optional[str] = None,\n locations: List = []):\n from .build_functions import build_from_cfg\n self._name = name\n self._module_dict: Dict[str, Type] = dict()\n self._children: Dict[str, 'Registry'] = dict()\n self._locations = locations\n self._imported = False\n\n if scope is not None:\n assert isinstance(scope, str)\n self._scope = scope\n else:\n self._scope = self.infer_scope()\n\n # See https://mypy.readthedocs.io/en/stable/common_issues.html#\n # variables-vs-type-aliases for the use\n self.parent: Optional['Registry']\n if parent is not None:\n assert isinstance(parent, Registry)\n parent._add_child(self)\n self.parent = parent\n else:\n self.parent = None\n\n # self.build_func will be set with the following priority:\n # 1. build_func\n # 2. parent.build_func\n # 3. build_from_cfg\n self.build_func: Callable\n if build_func is None:\n if self.parent is not None:\n self.build_func = self.parent.build_func\n else:\n self.build_func = build_from_cfg\n else:\n self.build_func = build_func\n\n def __len__(self):\n return len(self._module_dict)\n\n def __contains__(self, key):\n return self.get(key) is not None\n\n def __repr__(self):\n table = Table(title=f'Registry of {self._name}')\n table.add_column('Names', justify='left', style='cyan')\n table.add_column('Objects', justify='left', style='green')\n\n for name, obj in sorted(self._module_dict.items()):\n table.add_row(name, str(obj))\n\n console = Console()\n with console.capture() as capture:\n console.print(table, end='')\n\n return capture.get()\n\n @staticmethod\n def infer_scope() -> str:\n \"\"\"Infer the scope of registry.\n\n The name of the package where registry is defined will be returned.\n\n Returns:\n str: The inferred scope name.\n\n Examples:\n >>> # in mmdet/models/backbone/resnet.py\n >>> MODELS = Registry('models')\n >>> @MODELS.register_module()\n >>> class ResNet:\n >>> pass\n >>> # The scope of ``ResNet`` will be ``mmdet``.\n \"\"\"\n from ..logging import print_log\n\n # `sys._getframe` returns the frame object that many calls below the\n # top of the stack. The call stack for `infer_scope` can be listed as\n # follow:\n # frame-0: `infer_scope` itself\n # frame-1: `__init__` of `Registry` which calls the `infer_scope`\n # frame-2: Where the `Registry(...)` is called\n module = inspect.getmodule(sys._getframe(2))\n if module is not None:\n filename = module.__name__\n split_filename = filename.split('.')\n scope = split_filename[0]\n else:\n # use \"mmengine\" to handle some cases which can not infer the scope\n # like initializing Registry in interactive mode\n scope = 'mmengine'\n print_log(\n 'set scope as \"mmengine\" when scope can not be inferred. You '\n 'can silence this warning by passing a \"scope\" argument to '\n 'Registry like `Registry(name, scope=\"toy\")`',\n logger='current',\n level=logging.WARNING)\n\n return scope\n\n @staticmethod\n def split_scope_key(key: str) -> Tuple[Optional[str], str]:\n \"\"\"Split scope and key.\n\n The first scope will be split from key.\n\n Return:\n tuple[str | None, str]: The former element is the first scope of\n the key, which can be ``None``. The latter is the remaining key.\n\n Examples:\n >>> Registry.split_scope_key('mmdet.ResNet')\n 'mmdet', 'ResNet'\n >>> Registry.split_scope_key('ResNet')\n None, 'ResNet'\n \"\"\"\n split_index = key.find('.')\n if split_index != -1:\n return key[:split_index], key[split_index + 1:]\n else:\n return None, key\n\n @property\n def name(self):\n return self._name\n\n @property\n def scope(self):\n return self._scope\n\n @property\n def module_dict(self):\n return self._module_dict\n\n @property\n def children(self):\n return self._children\n\n @property\n def root(self):\n return self._get_root_registry()\n\n @contextmanager\n def switch_scope_and_registry(self, scope: Optional[str]) -> Generator:\n \"\"\"Temporarily switch default scope to the target scope, and get the\n corresponding registry.\n\n If the registry of the corresponding scope exists, yield the\n registry, otherwise yield the current itself.\n\n Args:\n scope (str, optional): The target scope.\n\n Examples:\n >>> from mmengine.registry import Registry, DefaultScope, MODELS\n >>> import time\n >>> # External Registry\n >>> MMDET_MODELS = Registry('mmdet_model', scope='mmdet',\n >>> parent=MODELS)\n >>> MMCLS_MODELS = Registry('mmcls_model', scope='mmcls',\n >>> parent=MODELS)\n >>> # Local Registry\n >>> CUSTOM_MODELS = Registry('custom_model', scope='custom',\n >>> parent=MODELS)\n >>>\n >>> # Initiate DefaultScope\n >>> DefaultScope.get_instance(f'scope_{time.time()}',\n >>> scope_name='custom')\n >>> # Check default scope\n >>> DefaultScope.get_current_instance().scope_name\n custom\n >>> # Switch to mmcls scope and get `MMCLS_MODELS` registry.\n >>> with CUSTOM_MODELS.switch_scope_and_registry(scope='mmcls') as registry:\n >>> DefaultScope.get_current_instance().scope_name\n mmcls\n >>> registry.scope\n mmcls\n >>> # Nested switch scope\n >>> with CUSTOM_MODELS.switch_scope_and_registry(scope='mmdet') as mmdet_registry:\n >>> DefaultScope.get_current_instance().scope_name\n mmdet\n >>> mmdet_registry.scope\n mmdet\n >>> with CUSTOM_MODELS.switch_scope_and_registry(scope='mmcls') as mmcls_registry:\n >>> DefaultScope.get_current_instance().scope_name\n mmcls\n >>> mmcls_registry.scope\n mmcls\n >>>\n >>> # Check switch back to original scope.\n >>> DefaultScope.get_current_instance().scope_name\n custom\n \"\"\" # noqa: E501\n from ..logging import print_log\n\n # Switch to the given scope temporarily. If the corresponding registry\n # can be found in root registry, return the registry under the scope,\n # otherwise return the registry itself.\n with DefaultScope.overwrite_default_scope(scope):\n # Get the global default scope\n default_scope = DefaultScope.get_current_instance()\n # Get registry by scope\n if default_scope is not None:\n scope_name = default_scope.scope_name\n try:\n import_module(f'{scope_name}.registry')\n except (ImportError, AttributeError, ModuleNotFoundError):\n if scope in MODULE2PACKAGE:\n print_log(\n f'{scope} is not installed and its '\n 'modules will not be registered. If you '\n 'want to use modules defined in '\n f'{scope}, Please install {scope} by '\n f'`pip install {MODULE2PACKAGE[scope]}.',\n logger='current',\n level=logging.WARNING)\n else:\n print_log(\n f'Failed to import `{scope}.registry` '\n f'make sure the registry.py exists in `{scope}` '\n 'package.',\n logger='current',\n level=logging.WARNING)\n root = self._get_root_registry()\n registry = root._search_child(scope_name)\n if registry is None:\n # if `default_scope` can not be found, fallback to argument\n # `registry`\n print_log(\n f'Failed to search registry with scope \"{scope_name}\" '\n f'in the \"{root.name}\" registry tree. '\n f'As a workaround, the current \"{self.name}\" registry '\n f'in \"{self.scope}\" is used to build instance. This '\n 'may cause unexpected failure when running the built '\n f'modules. Please check whether \"{scope_name}\" is a '\n 'correct scope, or whether the registry is '\n 'initialized.',\n logger='current',\n level=logging.WARNING)\n registry = self\n # If there is no built default scope, just return current registry.\n else:\n registry = self\n yield registry\n\n def _get_root_registry(self) -> 'Registry':\n \"\"\"Return the root registry.\"\"\"\n root = self\n while root.parent is not None:\n root = root.parent\n return root\n\n def import_from_location(self) -> None:\n \"\"\"import modules from the pre-defined locations in self._location.\"\"\"\n if not self._imported:\n # Avoid circular import\n from ..logging import print_log\n\n # avoid BC breaking\n if len(self._locations) == 0 and self.scope in MODULE2PACKAGE:\n print_log(\n f'The \"{self.name}\" registry in {self.scope} did not '\n 'set import location. Fallback to call '\n f'`{self.scope}.utils.register_all_modules` '\n 'instead.',\n logger='current',\n level=logging.DEBUG)\n try:\n module = import_module(f'{self.scope}.utils')\n except (ImportError, AttributeError, ModuleNotFoundError):\n if self.scope in MODULE2PACKAGE:\n print_log(\n f'{self.scope} is not installed and its '\n 'modules will not be registered. If you '\n 'want to use modules defined in '\n f'{self.scope}, Please install {self.scope} by '\n f'`pip install {MODULE2PACKAGE[self.scope]}.',\n logger='current',\n level=logging.WARNING)\n else:\n print_log(\n f'Failed to import {self.scope} and register '\n 'its modules, please make sure you '\n 'have registered the module manually.',\n logger='current',\n level=logging.WARNING)\n else:\n # The import errors triggered during the registration\n # may be more complex, here just throwing\n # the error to avoid causing more implicit registry errors\n # like `xxx`` not found in `yyy` registry.\n module.register_all_modules(False) # type: ignore\n\n for loc in self._locations:\n import_module(loc)\n print_log(\n f\"Modules of {self.scope}'s {self.name} registry have \"\n f'been automatically imported from {loc}',\n logger='current',\n level=logging.DEBUG)\n self._imported = True\n\n def get(self, key: str) -> Optional[Type]:\n \"\"\"Get the registry record.\n\n If `key`` represents the whole object name with its module\n information, for example, `mmengine.model.BaseModel`, ``get``\n will directly return the class object :class:`BaseModel`.\n\n Otherwise, it will first parse ``key`` and check whether it\n contains a scope name. The logic to search for ``key``:\n\n - ``key`` does not contain a scope name, i.e., it is purely a module\n name like \"ResNet\": :meth:`get` will search for ``ResNet`` from the\n current registry to its parent or ancestors until finding it.\n\n - ``key`` contains a scope name and it is equal to the scope of the\n current registry (e.g., \"mmcls\"), e.g., \"mmcls.ResNet\": :meth:`get`\n will only search for ``ResNet`` in the current registry.\n\n - ``key`` contains a scope name and it is not equal to the scope of\n the current registry (e.g., \"mmdet\"), e.g., \"mmcls.FCNet\": If the\n scope exists in its children, :meth:`get` will get \"FCNet\" from\n them. If not, :meth:`get` will first get the root registry and root\n registry call its own :meth:`get` method.\n\n Args:\n key (str): Name of the registered item, e.g., the class name in\n string format.\n\n Returns:\n Type or None: Return the corresponding class if ``key`` exists,\n otherwise return None.\n\n Examples:\n >>> # define a registry\n >>> MODELS = Registry('models')\n >>> # register `ResNet` to `MODELS`\n >>> @MODELS.register_module()\n >>> class ResNet:\n >>> pass\n >>> resnet_cls = MODELS.get('ResNet')\n\n >>> # hierarchical registry\n >>> DETECTORS = Registry('detector', parent=MODELS, scope='det')\n >>> # `ResNet` does not exist in `DETECTORS` but `get` method\n >>> # will try to search from its parents or ancestors\n >>> resnet_cls = DETECTORS.get('ResNet')\n >>> CLASSIFIER = Registry('classifier', parent=MODELS, scope='cls')\n >>> @CLASSIFIER.register_module()\n >>> class MobileNet:\n >>> pass\n >>> # `get` from its sibling registries\n >>> mobilenet_cls = DETECTORS.get('cls.MobileNet')\n \"\"\"\n # Avoid circular import\n from ..logging import print_log\n\n if not isinstance(key, str):\n raise TypeError(\n 'The key argument of `Registry.get` must be a str, '\n f'got {type(key)}')\n\n scope, real_key = self.split_scope_key(key)\n obj_cls = None\n registry_name = self.name\n scope_name = self.scope\n\n # lazy import the modules to register them into the registry\n self.import_from_location()\n\n if scope is None or scope == self._scope:\n # get from self\n if real_key in self._module_dict:\n obj_cls = self._module_dict[real_key]\n elif scope is None:\n # try to get the target from its parent or ancestors\n parent = self.parent\n while parent is not None:\n if real_key in parent._module_dict:\n obj_cls = parent._module_dict[real_key]\n registry_name = parent.name\n scope_name = parent.scope\n break\n parent = parent.parent\n else:\n # import the registry to add the nodes into the registry tree\n try:\n import_module(f'{scope}.registry')\n print_log(\n f'Registry node of {scope} has been automatically '\n 'imported.',\n logger='current',\n level=logging.DEBUG)\n except (ImportError, AttributeError, ModuleNotFoundError):\n print_log(\n f'Cannot auto import {scope}.registry, please check '\n f'whether the package \"{scope}\" is installed correctly '\n 'or import the registry manually.',\n logger='current',\n level=logging.DEBUG)\n # get from self._children\n if scope in self._children:\n obj_cls = self._children[scope].get(real_key)\n registry_name = self._children[scope].name\n scope_name = scope\n else:\n root = self._get_root_registry()\n\n if scope != root._scope and scope not in root._children:\n # If not skip directly, `root.get(key)` will recursively\n # call itself until RecursionError is thrown.\n pass\n else:\n obj_cls = root.get(key)\n\n if obj_cls is None:\n # Actually, it's strange to implement this `try ... except` to\n # get the object by its name in `Registry.get`. However, If we\n # want to build the model using a configuration like\n # `dict(type='mmengine.model.BaseModel')`, which can\n # be dumped by lazy import config, we need this code snippet\n # for `Registry.get` to work.\n try:\n obj_cls = get_object_from_string(key)\n except Exception:\n raise RuntimeError(f'Failed to get {key}')\n\n if obj_cls is not None:\n # For some rare cases (e.g. obj_cls is a partial function), obj_cls\n # doesn't have `__name__`. Use default value to prevent error\n cls_name = getattr(obj_cls, '__name__', str(obj_cls))\n print_log(\n f'Get class `{cls_name}` from \"{registry_name}\"'\n f' registry in \"{scope_name}\"',\n logger='current',\n level=logging.DEBUG)\n\n return obj_cls\n\n def _search_child(self, scope: str) -> Optional['Registry']:\n \"\"\"Depth-first search for the corresponding registry in its children.\n\n Note that the method only search for the corresponding registry from\n the current registry. Therefore, if we want to search from the root\n registry, :meth:`_get_root_registry` should be called to get the\n root registry first.\n\n Args:\n scope (str): The scope name used for searching for its\n corresponding registry.\n\n Returns:\n Registry or None: Return the corresponding registry if ``scope``\n exists, otherwise return None.\n \"\"\"\n if self._scope == scope:\n return self\n\n for child in self._children.values():\n registry = child._search_child(scope)\n if registry is not None:\n return registry\n\n return None\n\n def build(self, cfg: dict, *args, **kwargs) -> Any:\n \"\"\"Build an instance.\n\n Build an instance by calling :attr:`build_func`.\n\n Args:\n cfg (dict): Config dict needs to be built.\n\n Returns:\n Any: The constructed object.\n\n Examples:\n >>> from mmengine import Registry\n >>> MODELS = Registry('models')\n >>> @MODELS.register_module()\n >>> class ResNet:\n >>> def __init__(self, depth, stages=4):\n >>> self.depth = depth\n >>> self.stages = stages\n >>> cfg = dict(type='ResNet', depth=50)\n >>> model = MODELS.build(cfg)\n \"\"\"\n return self.build_func(cfg, *args, **kwargs, registry=self)\n\n def _add_child(self, registry: 'Registry') -> None:\n \"\"\"Add a child for a registry.\n\n Args:\n registry (:obj:`Registry`): The ``registry`` will be added as a\n child of the ``self``.\n \"\"\"\n\n assert isinstance(registry, Registry)\n assert registry.scope is not None\n assert registry.scope not in self.children, \\\n f'scope {registry.scope} exists in {self.name} registry'\n self.children[registry.scope] = registry\n\n def _register_module(self,\n module: Type,\n module_name: Optional[Union[str, List[str]]] = None,\n force: bool = False) -> None:\n \"\"\"Register a module.\n\n Args:\n module (type): Module to be registered. Typically a class or a\n function, but generally all ``Callable`` are acceptable.\n module_name (str or list of str, optional): The module name to be\n registered. If not specified, the class name will be used.\n Defaults to None.\n force (bool): Whether to override an existing class with the same\n name. Defaults to False.\n \"\"\"\n if not callable(module):\n raise TypeError(f'module must be Callable, but got {type(module)}')\n\n if module_name is None:\n module_name = module.__name__\n if isinstance(module_name, str):\n module_name = [module_name]\n for name in module_name:\n if not force and name in self._module_dict:\n existed_module = self.module_dict[name]\n raise KeyError(f'{name} is already registered in {self.name} '\n f'at {existed_module.__module__}')\n self._module_dict[name] = module\n\n def register_module(\n self,\n name: Optional[Union[str, List[str]]] = None,\n force: bool = False,\n module: Optional[Type] = None) -> Union[type, Callable]:\n \"\"\"Register a module.\n\n A record will be added to ``self._module_dict``, whose key is the class\n name or the specified name, and value is the class itself.\n It can be used as a decorator or a normal function.\n\n Args:\n name (str or list of str, optional): The module name to be\n registered. If not specified, the class name will be used.\n force (bool): Whether to override an existing class with the same\n name. Defaults to False.\n module (type, optional): Module class or function to be registered.\n Defaults to None.\n\n Examples:\n >>> backbones = Registry('backbone')\n >>> # as a decorator\n >>> @backbones.register_module()\n >>> class ResNet:\n >>> pass\n >>> backbones = Registry('backbone')\n >>> @backbones.register_module(name='mnet')\n >>> class MobileNet:\n >>> pass\n\n >>> # as a normal function\n >>> class ResNet:\n >>> pass\n >>> backbones.register_module(module=ResNet)\n \"\"\"\n if not isinstance(force, bool):\n raise TypeError(f'force must be a boolean, but got {type(force)}')\n\n # raise the error ahead of time\n if not (name is None or isinstance(name, str) or is_seq_of(name, str)):\n raise TypeError(\n 'name must be None, an instance of str, or a sequence of str, '\n f'but got {type(name)}')\n\n # use it as a normal method: x.register_module(module=SomeClass)\n if module is not None:\n self._register_module(module=module, module_name=name, force=force)\n return module\n\n # use it as a decorator: @x.register_module()\n def _register(module):\n self._register_module(module=module, module_name=name, force=force)\n return module\n\n return _register\n","repo_name":"open-mmlab/mmengine","sub_path":"mmengine/registry/registry.py","file_name":"registry.py","file_ext":"py","file_size_in_byte":26900,"program_lang":"python","lang":"en","doc_type":"code","stars":853,"dataset":"github-code","pt":"77"}
+{"seq_id":"12996403528","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 1 02:19:04 2020\n\n@author: Mostafa Atalla\n\"\"\"\n\n\"\"\"\nPseudocode for the problem:\n 1 - start using the first letter of the word\n 2 - Check if the following letter has higher index:\n if yes, accumulate this letter to the first and continue\n if not, start the loop again with the following letter\n store the accumulated words in a list\n \n 3- check the word with the most number of letters \n return it\n \n\n\"\"\"\ns = 'abcdefghijklmnopqrstuvwxyz'\n\nalphabet='abcdefghijklmnopqrstuvwxyz'\n\n\ndef alphabet_index(alphabet_letter):\n index=alphabet.index(alphabet_letter)\n return index\n\n\nsub_string_list=[]\nsub_string=s[0]\nidx=0\nfor idx in range(len(s)-1):\n first_char_idx = alphabet_index(s[idx])\n second_char_idx = alphabet_index(s[idx+1])\n if second_char_idx >= first_char_idx:\n sub_string+=s[idx+1]\n else:\n sub_string_list.append(sub_string)\n sub_string=s[idx+1]\nsub_string_list.append(sub_string)\n\n\nlongest_string=sub_string_list[0]\nfor string in sub_string_list:\n if len(string) > len(longest_string):\n longest_string = string\n\nprint(\"Longest substring in alphabetical order is: \"+str(longest_string))\n ","repo_name":"MostafaAtalla/edx-Intro-to-Computer-Science-using-Python---MIT","sub_path":"Problem set1/problem3.py","file_name":"problem3.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"1277574501","text":"import numpy as np\n\n\ndef train_test_split_index(data, test_size = 0.2):\n '''\n compute index of rows to be split between train and test set, based on incident number.\n\n input :\n data : full cleaned dataset (dataframe)\n test_size : percentage of incidents to be allocated to test set\n\n returns :\n tts_index_test : index of rows to be allocated to test set\n tts_index_train : index of rows to be allocated to train set\n\n '''\n\n # build sorted incidents list\n tts_inc_list = data['IncidentNumber'].unique().tolist()\n tts_inc_list.sort()\n\n # Total des véhicules et incidents pour juger de la répartition train / test\n # tts_nb_pump = df.shape[0]\n\n # size of incidents list to be allocated to test set\n tts_nb_inc = len(tts_inc_list)\n tts_test_size_nb = np.int64(tts_nb_inc * test_size)\n\n # list of incidents to be allocated to test set (select random sample of 'test_size_nb' elements from the list, without replacement)\n tts_inc_test_list = list(np.random.choice(tts_inc_list, tts_test_size_nb, replace= False))\n\n # save and returns the index (since IncidentNumber will be removed from variables later)\n tts_index_test = data[data['IncidentNumber'].isin(tts_inc_test_list)].index\n tts_index_train = data[~data['IncidentNumber'].isin(tts_inc_test_list)].index\n\n return tts_index_test, tts_index_train\n\n\ndef train_test_split_incident(target, features, tts_index_test, tts_index_train):\n '''\n split dataset into train and test set based on incident ref\n (so that all vehicles attending an incident are or in test, or in train, not both)\n\n input :\n target : target variable (to be predicted by model)\n features : features to predict target\n tts_index_test : index of data to be allocated to test set\n tts_index_train : index of data to be allocated to train set\n \n returns :\n X_train, X_test, y_train, y_test\n \n '''\n\n X_train = features.loc[tts_index_train]\n X_test = features.loc[tts_index_test]\n y_train = target.loc[tts_index_train]\n y_test = target.loc[tts_index_test]\n\n return X_train, X_test, y_train, y_test\n","repo_name":"QuentinFontenay/MLOPS-LondonPump","sub_path":"entrainement/training/train_test.py","file_name":"train_test.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"73144530810","text":"import numpy as np\nimport pygame\nfrom colors import *\nfrom settings import *\n\n\nclass FractalFern:\n\n def __init__(self):\n self.width = WIDTH\n self.height = HEIGHT\n self.x_off = X_OFF\n self.y_off = Y_OFF\n self.game_win_width = GAMEWIN_WIDTH\n self.game_win_height = GAMEWIN_HEIGHT\n self.fps = FPS\n self.clock = None\n self.win = None\n self.game_win = None\n self.title_font = None\n self.is_paused = True\n\n def win_init(self):\n pygame.init()\n pygame.font.init()\n\n self.win = pygame.display.set_mode((self.width, self.height))\n pygame.display.set_caption('Barnsley Fern')\n\n game_win_rect = pygame.Rect(self.x_off, self.y_off, self.game_win_width, self.game_win_height)\n self.game_win = self.win.subsurface(game_win_rect)\n\n self.win.fill(MID_BLACK)\n self.game_win.fill(BLACK)\n\n self.title_font = pygame.font.SysFont(TITLE_FONT, FONT_SIZE)\n title = self.title_font.render(TITLE, 1, GOLD)\n w, h = title.get_size()\n blit_X = (self.width - w) // 2\n blit_Y = (self.y_off - h) // 2\n self.win.blit(title, (blit_X, blit_Y))\n\n self.clock = pygame.time.Clock()\n pygame.display.update()\n\n @staticmethod\n def close():\n pygame.font.quit()\n pygame.quit()\n\n def draw(self):\n pass\n\n def run(self):\n if not pygame.display.init():\n self.win_init()\n\n run = True\n while run:\n self.clock.tick(self.fps)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n\n if event.type == pygame.KEYDOWN:\n keys = pygame.key.get_pressed()\n if keys[pygame.K_SPACE]:\n self.is_paused = not self.is_paused\n\n if keys[pygame.K_ESCAPE]:\n pass\n\n FractalFern.close()\n\n\nif __name__ == '__main__':\n fractal = FractalFern()\n fractal.run()\n\n","repo_name":"Deadshot96/barnsley-fern-replicated","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"36797103840","text":"import RPi.GPIO as GPIO\nimport time\nimport Constants\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\n\nclass DCMotor():\n def __init__(self, pin1, pin2,pinPWM=None, pwmFreq=None,dutyCycle=None):\n self.pin1=pin1\n self.pin2=pin2\n \n self.isPWMOpen=False\n\n GPIO.setup(self.pin1,GPIO.OUT)\n GPIO.setup(self.pin2,GPIO.OUT)\n\n if pinPWM!=None:\n self.pinPWM=pinPWM\n GPIO.setup(self.pinPWM,GPIO.OUT)\n self.pwm = GPIO.PWM(self.pinPWM,pwmFreq)\n self.pwm.start(dutyCycle)\n self.isPWMOpen=True\n\n def turnLeft(self):\n GPIO.output(self.pin1,1)\n GPIO.output(self.pin2,0)\n\n def turnRight(self):\n GPIO.output(self.pin1,0)\n GPIO.output(self.pin2,1)\n\n def stop(self):\n GPIO.output(self.pin1,0)\n GPIO.output(self.pin2,0)\n \n if isPWMOpen:\n GPIO.output(self.pinPWM,0)\n self.pwm.stop()\n\n def turnLeftWithDelays(self,risingTime,follingTime):\n GPIO.output(self.pin1,1)\n GPIO.output(self.pin2,0)\n time.sleep(risingTime)\n GPIO.output(self.pin1,0)\n time.sleep(follingTime)\n\n def turnRightWithDelays(self,risingTime,follingTime):\n GPIO.output(self.pin1,0)\n GPIO.output(self.pin2,1)\n time.sleep(risingTime)\n GPIO.output(self.pin2,0)\n time.sleep(follingTime)\n \n def _test(self):\n print(\"Starting DC motor tests\")\n print(\"Will turn 5 times right and left and each turn will take 2 sec\")\n\n for i in range(0,5):\n self.turnLeft()\n time.sleep(2)\n self.turnRight()\n time.sleep(2)\n self.stop()\n\n def _testTurnWithDelay(self):\n for i in range(0,10):\n self.turnLeftWithDelay(0.05,0.2)\n for i in range(0,10):\n self.turnRightWithDelay(0.05,0.2)\n\n self.stop()\n print(\"DC motor tests done. Did you see movements?\")\n\ndef dcMotorModuleTest():\n dcMotor = DCMotor(Constants.GPIO_PIN_DC_1,Constants.GPIO_PIN_DC_2,Constants.GPIO_PIN_DC_PWM,200,15)\n\n print(\"FirstTest\")\n dcMotor._test()\n \nif __name__==\"__main__\":\n dcMotorModuleTest()\n","repo_name":"GTU-Projects/CSE495_WildAnimalTrap_2017","sub_path":"Raspberry/modules/dcMotor.py","file_name":"dcMotor.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"27761076347","text":"import os\nimport sys\nimport argparse\nimport http.server\nimport socketserver\nimport pathlib\n\nTEST_PATH = os.path.dirname(os.path.abspath(__file__)) + \"/test\"\nROOT_PATH = os.path.dirname(os.path.abspath(__file__)) + \"/serve_root\"\nBUILD_PATH = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + '/../../../pyodide/dist')\n\nassert os.path.isfile(BUILD_PATH + \"/pyodide.js\"), \"Pyodide dist dir not found\"\n\n\nclass Handler(http.server.SimpleHTTPRequestHandler):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, directory=args[2].root_dir, **kwargs)\n def end_headers(self):\n self.send_header('Access-Control-Allow-Origin', '*')\n super().end_headers()\n def translate_path(self, path):\n if self.path.startswith('/build'):\n if self.path == '/build' or self.path == '/build/':\n return self.server.build_dir\n else:\n return self.server.build_dir + path[len('/build'):]\n elif self.path.startswith('/test'):\n if self.path == '/test' or self.path == '/test/':\n return self.server.test_dir\n else:\n return self.server.test_dir + path[len('/test'):]\n else:\n return super().translate_path(path)\n\n\nclass Server(socketserver.TCPServer):\n def __init__(self, host_port_tuple, streamhandler, root_dir, build_dir, test_dir):\n super().__init__(host_port_tuple, streamhandler)\n self.root_dir = root_dir\n self.build_dir = build_dir\n self.test_dir = test_dir\n\n\nHandler.extensions_map['.wasm'] = 'application/wasm'\n\n\ndef make_parser(parser):\n parser.description = ('Start a server with the supplied '\n 'build_dir, test_dir, root_dir, and port.')\n parser.add_argument('--root_dir', action='store', type=str,\n default=ROOT_PATH, help='set the server root path')\n parser.add_argument('--build_dir', action='store', type=str,\n default=BUILD_PATH, help='set the Pyodide build directory containing WASM files')\n parser.add_argument('--test_dir', action='store', type=str,\n default=TEST_PATH, help='set the Pyodide directory containing test files')\n parser.add_argument('--port', action='store', type=int,\n default=8000, help='set the PORT number')\n return parser\n\n\ndef server(port, root_dir, build_dir, test_dir):\n httpd = Server(('', port), Handler, root_dir, build_dir, test_dir)\n return httpd\n\n\ndef main(args):\n root_dir = args.root_dir\n build_dir = args.build_dir\n test_dir = args.test_dir\n port = args.port\n httpd = server(port, root_dir, build_dir, test_dir)\n \n print(\"serving from {0} at localhost:\".format(build_dir) + str(port))\n try:\n httpd.serve_forever()\n except KeyboardInterrupt:\n print(\"\\n...shutting down http server\")\n httpd.shutdown()\n sys.exit()\n\n\nif __name__ == \"__main__\":\n parser = make_parser(argparse.ArgumentParser())\n args = parser.parse_args()\n main(args)\n","repo_name":"robotraconteur/robotraconteur_pyodide","sub_path":"testing/pyodide_test/serve.py","file_name":"serve.py","file_ext":"py","file_size_in_byte":3071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"31031465484","text":"## read all luts and set up rgi\n## QV 2020-01-15\ndef import_luts(pressures = [500, 1013, 1100], base_luts = ['PONDER-LUT-201704-MOD1', 'PONDER-LUT-201704-MOD2']):\n import scipy.interpolate\n import numpy as np\n import acolite as ac\n\n lut_dict = {}\n ## run through luts\n for lut in base_luts:\n ## run through pressures\n for ip, pr in enumerate(pressures):\n lutid = '{}-{}mb'.format(lut, '{}'.format(pr).zfill(4))\n\n lutdir = '{}/{}'.format(ac.config['pp_data_dir'], 'LUT')\n lut_data, lut_meta = ac.aerlut.import_lut(lutid,lutdir, override=0)\n\n ## set up lut dimensions\n if ip == 0:\n # lut data is par, wave, azi, thv, ths, wind, tau\n lut_dim = [[i for i in pressures]] + [[i for i in range(len(lut_meta['par']))]]\n lut_dim += [lut_meta[k] for k in ['wave', 'azi', 'thv', 'ths', 'tau']]\n lutd = []\n lut_dict[lut] = {'meta':lut_meta, 'dim':lut_dim}\n\n lutd.append(lut_data)\n lut_dict[lut]['lut'] = np.stack(lutd)\n\n ## set up LUT interpolator\n lut_dict[lut]['rgi'] = scipy.interpolate.RegularGridInterpolator(lut_dict[lut]['dim'],\n lut_dict[lut]['lut'][:,:,:,:,:,:,0,:],\n bounds_error=False, fill_value=np.nan)\n return(lut_dict)\n","repo_name":"peterpan83/acolite","sub_path":"acolite/aerlut/import_luts.py","file_name":"import_luts.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"77"}
+{"seq_id":"20301633833","text":"import os\nfrom bs4 import BeautifulSoup\nimport json\nimport utils\n\nif False:\n from gui import App\n\n\ndef download(root, gui: \"App\" = None):\n error_list = []\n total_count = 0\n skipped_count = 0\n processed_count = 0\n\n attachments_path = os.path.join(root, \"Resources\", \"attachments\")\n\n html_file_count = 0\n for path, subdirs, files in os.walk(root):\n for name in files:\n if name.endswith(\".html\"):\n html_file_count += 1\n\n current_file_idx = 0\n for path, subdirs, files in os.walk(root):\n for name in files:\n if name.endswith(\".html\"):\n current_file_idx += 1\n fpath = os.path.join(path, name)\n print(\"Loading:\", fpath)\n\n setGuiFileDownloaderInfo(gui, week=\"Searching\", topic=\"All html files\", filename=\"\", url=\"\", output=\"\",\n eta=\"\", speed=\"\", dl_size=\"\", file_size=\"\", progress=0, current_no=0,\n total_files=0)\n\n f = open(fpath, \"r\", encoding='utf-8')\n html_text = f.read()\n f.close()\n soup = BeautifulSoup(html_text, 'html.parser')\n # print(soup.get_text)\n attachment_tags = soup.find_all('a', {\"class\": \"cml-asset-link\"})\n asset_containers = soup.find_all('div', {\"class\": \"asset-container\"})\n\n print(len(attachment_tags) + len(asset_containers), \"attachment(s) found\")\n file_modified = False\n\n current_file_total_count = len(attachment_tags) + len(asset_containers)\n total_count += current_file_total_count\n\n new_attachment_href = \"../../Resources\"\n\n if fpath.find(\"{}Resources{}\".format(os.path.sep, os.path.sep)) >= 0:\n new_attachment_href = \"../Resources\"\n\n if len(asset_containers) == 0:\n # Update GUI Progress\n dl_size = \"{} of {}\".format(0, 0)\n setGuiFileDownloaderInfo(gui, week=\"Loading\", topic=\"\", filename=name, url=\"\", output=fpath,\n dl_size=dl_size, file_size=\"\", progress=100, current_no=current_file_idx,\n total_files=html_file_count)\n\n for idx, asset_container in enumerate(asset_containers):\n attachment_tag = asset_container.find('a')\n attach_filename = asset_container.find(\"span\", {\"class\": \"asset-name\"}).text\n attach_filename = utils.getFormattedFileName(attach_filename)\n # print(link.get(\"href\"))\n attach_href = attachment_tag.get('href')\n\n # Update GUI Progress\n progress = (idx + 1) / current_file_total_count * 100\n dl_size = \"{} of {}\".format(idx + 1, current_file_total_count)\n setGuiFileDownloaderInfo(gui, week=\"Loading\", topic=\"\", filename=name, url=attach_href,\n output=fpath, dl_size=dl_size, file_size=\"\", progress=progress,\n current_no=current_file_idx, total_files=html_file_count)\n\n print(\"Attachment {}/{}:\".format(idx + 1, len(asset_containers)), end=\" \")\n if attach_href.find(new_attachment_href) >= 0:\n print(\"Already processed. Skipping...\")\n skipped_count += 1\n continue\n elif attach_href == \"\":\n error_list.append({\"error\": \"blank href\", \"path\": fpath})\n print(\"Error: Blank href\")\n continue\n try:\n attah_filename = utils.downloadFile(attach_href, attachments_path, attach_filename)\n file_modified = True\n processed_count += 1\n attachment_tag['href'] = new_attachment_href + \"/attachments/\" + attah_filename\n except Exception as e:\n print(\"Error:\", e)\n error_list.append({\"error\": \"url\", \"url\": attach_href, \"path\": fpath})\n continue\n\n if len(attachment_tags) == 0:\n # Update GUI Progress\n dl_size = \"{} of {}\".format(0, 0)\n setGuiFileDownloaderInfo(gui, week=\"Loading\", topic=\"\", filename=name, url=\"\", output=fpath,\n dl_size=dl_size, file_size=\"\", progress=100, current_no=current_file_idx,\n total_files=html_file_count)\n\n for idx, attachment_tag in enumerate(attachment_tags):\n attach_href = attachment_tag.get('href')\n attach_filename = attachment_tag.text\n attach_filename = utils.getFormattedFileName(attach_filename)\n\n # Update GUI Progress\n progress = (len(asset_containers) + idx + 1) / current_file_total_count * 100\n dl_size = \"{} of {}\".format(len(asset_containers) + idx + 1, current_file_total_count)\n setGuiFileDownloaderInfo(gui, week=\"Loading\", topic=\"\", filename=name, url=attach_href,\n output=fpath, dl_size=dl_size, file_size=\"\", progress=progress,\n current_no=current_file_idx, total_files=html_file_count)\n\n print(\"Attachment {}/{}:\".format(idx+1, len(attachment_tags)), end=\" \")\n if attach_href.find(new_attachment_href) >= 0:\n print(\"Already processed. Skipping...\")\n skipped_count += 1\n continue\n elif attach_href == \"\":\n error_list.append({\"error\": \"blank href\", \"path\": fpath})\n print(\"Error: Blank href\")\n continue\n try:\n attah_filename = utils.downloadFile(attach_href, attachments_path, attach_filename)\n file_modified = True\n processed_count += 1\n attachment_tag['href'] = new_attachment_href + \"/attachments/\" + attah_filename\n except Exception as e:\n print(\"Error:\", e)\n error_list.append({\"error\": \"url\", \"url\": attach_href, \"path\": fpath})\n continue\n\n if file_modified:\n utils.savePlainFile(fpath, str(soup))\n print()\n\n print(\"Total:\", total_count, \"attachment(s)\")\n print(\"Processed:\", processed_count, \"attachment(s)\")\n print(\"Skipped:\", skipped_count, \"attachment(s)\")\n print(\"Errors:\", len(error_list))\n print(error_list)\n\n # setGuiFileDownloaderInfo(gui, week=\"Success\", topic=\"Attachment processing finished successfully!\")\n\n with open(\"data/attach_errors.json\", \"w\") as out_file:\n json.dump(error_list, out_file)\n\n# GUI Functions\ndef setGuiFileDownloaderInfo(gui, week=None, topic=None, filename=None, url=None, output=None, eta=None,\n speed=None, dl_size=None, file_size=None, progress=None, current_no=0, total_files=0):\n if gui is not None:\n gui.setFileDownloaderInfo(week=week, topic=topic, filename=filename, url=url, output=output, eta=eta,\n speed=speed, dl_size=dl_size, file_size=file_size, progress=progress,\n current_no=current_no, total_files=total_files)\n","repo_name":"asnbd/coursera-download","sub_path":"attachment_downloader.py","file_name":"attachment_downloader.py","file_ext":"py","file_size_in_byte":7786,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"77"}
+{"seq_id":"39005518566","text":"import cv2\nimport numpy as np\nfrom tensorflow.keras.applications import MobileNetV2\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\n\ndef calculate_similarity(original_image_path, new_image_path):\n # 读取原始图像和待识别的图像\n original_image = cv2.imread(original_image_path)\n new_image = cv2.imread(new_image_path)\n\n # 调整图像尺寸为模型输入大小\n model_input_size = (224, 224)\n original_image = cv2.resize(original_image, model_input_size)\n new_image = cv2.resize(new_image, model_input_size)\n\n # 对图像进行预处理\n original_image = preprocess_input(original_image)\n new_image = preprocess_input(new_image)\n\n # 加载预训练的MobileNet模型\n model = MobileNetV2(weights='imagenet', include_top=False)\n\n # 提取原始图像和待识别图像的特征向量\n original_features = model.predict(np.expand_dims(original_image, axis=0))\n new_features = model.predict(np.expand_dims(new_image, axis=0))\n\n # 计算特征向量之间的余弦相似度\n original_features = original_features.reshape(-1)\n new_features = new_features.reshape(-1)\n similarity = np.dot(original_features, new_features) / (np.linalg.norm(original_features) * np.linalg.norm(new_features))\n\n return similarity\n\n# 调用方法并输出相似度\noriginal_image_path = \"D:\\\\download\\\\Video\\\\tao\\\\imgs\\\\247.jpg\"\nnew_image_path = \"D:\\\\download\\\\Video\\\\tao\\\\imgs\\\\290.jpg\"\nsimilarity = calculate_similarity(original_image_path, new_image_path)\nprint(\"相似度:\", similarity)","repo_name":"sexyflaw/Image-Similarity","sub_path":"src/util/aitest.py","file_name":"aitest.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"38891494735","text":"import pytest\nfrom app import schemas\n\n\ndef test_get_all_posts(client, test_posts):\n res = client.get('/posts')\n print(res.json())\n\n def validate(post):\n return schemas.PostResponse(**post)\n posts_list = list(map(validate, res.json()))\n assert len(posts_list) == len(test_posts)\n assert res.status_code == 200\n\n\ndef test_users_get_one_post(client, test_posts):\n res = client.get(f'/posts/{test_posts[0].id}')\n \n post = schemas.PostResponse(**res.json())\n\n assert post.title == test_posts[0].title\n assert post.content == test_posts[0].content\n assert post.id == test_posts[0].id\n\n\n@pytest.mark.parametrize(\n 'title, content, published',\n [\n ('New Title', 'added new title', True),\n ('Something', 'Here is something interesting', False),\n ('Interesting title', 'Nice one ', False)\n ]\n )\ndef test_create_posts(authorized_client, title, content, published):\n res = authorized_client.post(\n '/posts',\n json={'title': title, 'content': content, 'published': published}\n )\n post = schemas.PostResponse(**res.json())\n\n assert res.status_code == 201\n assert post.title == title\n assert post.content == content\n assert post.published == published\n\n\ndef test_delete_post(authorized_client, test_posts):\n res = authorized_client.delete(\n f'/posts/{test_posts[0].id}'\n )\n\n assert res.status_code == 204\n\n\ndef test_delete_post_non_exist(authorized_client):\n res = authorized_client.delete('/posts/808080808')\n\n assert res.status_code == 404\n\n\ndef test_update_post(authorized_client, test_posts):\n data = {\n 'title': 'Update Title',\n 'content': 'Update content'\n }\n res = authorized_client.put(\n f'/posts/{test_posts[0].id}',\n json=data\n )\n\n post = schemas.PostResponse(**res.json())\n\n assert post.title == data['title']\n assert post.content == data['content']\n assert post.id == test_posts[0].id\n\n\ndef test_update_post_non_exist(authorized_client):\n data = {\n 'title': 'Update Title',\n 'content': 'Update content'\n }\n res = authorized_client.put(\n '/posts/980090',\n json=data\n )\n\n assert res.status_code == 404\n","repo_name":"prototypid/FastApi-Backend","sub_path":"tests/test_posts_routes.py","file_name":"test_posts_routes.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"38391738462","text":"import pandas as pd \nimport numpy as np \nimport matplotlib.pyplot as plt\nimport seaborn as sns \nimport os\n\nimport data \nfrom utils import read_json \n\nINPUT_PATH = 'data/'\nMETRICS = ['mape', 'vape']\n\ndef read_target(df, station, aggregation):\n data = df[station]\n\n if aggregation == 'day':\n forecast_window = 7\n elif aggregation == 'hour':\n forecast_window = 24\n elif aggregation == 'month':\n forecast_window = 12\n elif aggregation == '15mins':\n forecast_window = 8\n else:\n raise KeyError ('aggregation parameter is one of [day, hour, month, 15 mins]')\n\n shift_list = []\n col_list = []\n for i in range(forecast_window):\n shift_list.append(data.shift(-i))\n col_list.append('forecast_period_' + str(i + 1))\n target = pd.concat(shift_list, axis = 1)\n target.columns = col_list\n target = np.array(target.dropna())\n assert target.shape[1] == forecast_window\n return target\n\ndef read_prediction(model, aggregation, station):\n path = os.path.join('output', model, 'results', aggregation , station + '.json' )\n prediction = read_json(path)\n prediction = np.array(prediction['prediction'])\n return np.expm1(prediction)\n\ndef APE(target, predicted):\n return np.abs((target - predicted) / target)\n\ndef mape(target, predicted, axis = None):\n return np.mean(APE(target, predicted), axis = axis)\n\ndef maape(target, predicted, axis = None):\n ape = APE(target, predicted)\n return np.mean(np.arctan(ape), axis = axis)\n\ndef vape(target, predicted, axis = None):\n return np.var(APE(target, predicted), axis = axis)\n\ndef plot_before_after(pre, post, metric_name):\n\n fig, axs = plt.subplots(nrows=1, ncols=1, figsize = (10,10))\n axs.scatter(pre, post, color=\"g\")\n axs.plot([0, 1], [0, 1])\n axs.set_ylabel('Post COVID-19 \\n [Jun 2019 - Feb 2020]')\n axs.set_xlabel('Pre COVID-19 \\n [Jun 2019 - Feb 2020]')\n axs.set_title(metric_name, fontsize = 50)\n return None\n\n\ndef plot_evolution(metrics, metric_name):\n plt.plot(x = 'Date', y = 'MAPE')\n plt.ylabel(metric_name)\n plt.title('Evolution of ' + metric_name)\n plt.axvline(578, color = 'r')\n return None\n\ndef run_regression(pre, post, metric_name):\n\n for metric in METRICS:\n pre_name = 'pre_' + metric\n post_name = 'post_' + metric\n x = sm.add_constant(results[pre_name].rename('pre-COVID 19 metric'), prepend=False)\n\n return regression\n\n## FIX ME \ndef linear_regression(results, metrics):\n\n models_list = []\n\n for metric in metrics:\n pre_name = 'pre_' + metric\n post_name = 'post_' + metric\n x = sm.add_constant(results[pre_name].rename('pre-COVID 19 metric'), prepend=False)\n model = sm.OLS(results[post_name], x).fit()\n models_list.append(model)\n\n ols_results = summary_col(models_list,stars=True, info_dict = {\"N\":lambda x:(x.nobs)},\n model_names = metrics, float_format='%.3f')\n\n return ols_results\n\n\ndef results(model, aggregation, metric):\n #read data\n train, test = data.split_data(INPUT_PATH, train_date = (2018, 8, 1), aggreagation = aggregation)\n stations = set(train.columns[train.columns.str.contains(\"\\(\")])\n\n #For each station\n w_metric = []\n s_pre_metric = []\n s_post_metric = []\n for station in stations:\n target = read_target(test, station, aggregation)\n prediction = read_prediction(station)\n ## FIX ME: Check 572 is the actual split of the data\n pre_target = target[:578,:]\n pre_prediction = prediction[:578,:]\n post_target = target[578:,:]\n post_prediction = prediction[578:,:]\n\n # METRICS\n window_metric = metric(target, prediction, axis = 1)\n pre_station_metric = metric(pre_target, pre_prediction)\n post_station_metric = metric(post_target, post_prediction)\n w_metric.append(window_metric)\n s_pre_metric.append(pre_station_metric)\n s_post_metric.append(post_station_metric)\n \n plot_before_after(s_pre_metric, s_post_metric)\n plot_evolution(w_metric)\n regression = run_regression(s_pre_metric, s_post_metric)\n\n return regression\n\n## -------------------------- tests ------------------------------------\nmodel = 'arima'\naggregation = 'day'\nmetric = 'mape'\nstation = \"(02000) cabecera autopista norte\"\ntrain, test = data.split_data(INPUT_PATH, train_date = (2018, 8, 1), aggreagation = aggregation)\n\ntarget = read_target(test, station, aggregation = aggregation)[:-1,:]\nprint(target.shape)\nprediction = read_prediction(model, aggregation, station)[:target.shape[0],:]\nprint(prediction)\n\n# m = maape(target, prediction)\n# print (m)","repo_name":"jdcaicedo251/transit_demand_prediction","sub_path":"results_plots.py","file_name":"results_plots.py","file_ext":"py","file_size_in_byte":4667,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"23653422145","text":"#!/usr/bin/env python3.9\n# -*- coding: utf-8 -*-\n# ############################################################################\n#\n# hudint.py\n# 27/07/2023 (c) Juan M. Casillas \n#\n# Python Overlay 2.0 (VideoSync) main program. This program creates a HUD\n# overlay based on the telemetry of FIT or GPX files. See \n# https://github.com/juanmcasillas/VideoSync for more info about it Project\n# started on 07/07/2016 !s\n#\n# ############################################################################\n\n##\n## don't forget to save the .dll into site-packages,\n## and add site-packages to the PATH\n## set PATH=%PATH%;C:\\Python27\\Lib\\site-packages\n##\n## see this for inspiration\n## https://www.youtube.com/watch?v=tuSntvYjThU\n\n## Only TCX & FIT files are supported. GPX only support ATEMP & HR\n## extensions\n## 24.0 \n## 75 \n##\n## TCX and FIT files support\n## Cadence\n## HR\n## POWER\n##\n## NO TCX PARSER AVAILABLE FOR NOW :(\n##\n## INTEGRATED VERSION (RENDERED) with GAUGES.\n##\n\n## install xcode, and xcode-command-line-tools (xcode 5.1.1 for 10.8.5)\n## install brew (dependencies)\n## compile opencv3\n##\n##cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local \\\n##\t-D PYTHON2_PACKAGES_PATH=/usr/lib/python2.7/site-packages \\\n##\t-D PYTHON2_LIBRARY=/Library/Frameworks/Python.framework/Versions/2.7/bin \\\n##\t-D PYTHON2_INCLUDE_DIR=/Library/Frameworks/Python.framework/Headers \\\n##\t-D INSTALL_C_EXAMPLES=OFF -D INSTALL_PYTHON_EXAMPLES=OFF \\\n##\t-D BUILD_EXAMPLES=OFF ..\n## export DYLD_FALLBACK_LIBRARY_PATH=/usr/local/lib:$DYLD_FALLBACK_LIBRARY_PATH\n## export PYTHONPATH=/usr/lib/python2.7/site-packages:$PYTHONPATH\n\n\n## 07/July/2016 BASIC Skel running. Features\n## - create merged video with audio * done 08/07/16\n## - create composite layer (for FCP, for example) * partial\n## - Drop shadows on text * done 08/07/16\n## - Optimize map drawing\n## - Basic interface (speed, slope, elev ...)\n## - Advanced (Bike information)\n\nimport sys\n\nfrom collections import namedtuple\nimport subprocess\nimport tempfile\nimport os\nimport os.path\nfrom manager import HRMManager\nfrom mapper import *\n\nimport gpxpy \nimport gpxtoolbox\nfrom metrics import *\nfrom helpers import *\n\nfrom collections import deque\nimport numpy as np\nimport argparse\nimport imutils\nimport cv2\n\nimport math\nimport datetime\nimport time\nimport timecode\nimport pygame\nimport gauges\nimport pytz\n\n# experimental gopro2gpx\n\nfrom gopro2gpx import gopro2gpx\n\nfrom engine import Engine\nfrom baseconfig import BaseConfig\n\nclass ClipInfo:\n def __init__(self, video_file, stream, offset=0, duration=0):\n \n ffmhelper = FFMPEGAdapter()\n\n self.video_file = video_file\n json_metadata = ffmhelper.GetJsonMetadata(self.video_file,tag=\"format\") \n \n #metadata = metaDataFile(self.video_file)\n #self.duration_m = metadata.get('duration')\n #self.creation_date = metadata.get('creation_date')\n #\n #\n \n self.duration_m = float(json_metadata[\"duration\"])\n # creation date in the go_pro file, is in Localtime,\n # so figure out the current localtime, and do the\n # trick to convert to UTC.\n self.local_tz = datetime.datetime.utcnow().astimezone().tzinfo\n self.creation_date = datetime.datetime.fromisoformat(json_metadata[\"tags\"][\"creation_time\"])\n self.creation_date = self.creation_date.replace(tzinfo=self.local_tz)\n self.creation_date = self.creation_date.astimezone(pytz.UTC)\n \n self.width = int(stream.get(cv2.CAP_PROP_FRAME_WIDTH ))\n self.height = int(stream.get(cv2.CAP_PROP_FRAME_HEIGHT ))\n self.frames = stream.get(cv2.CAP_PROP_FRAME_COUNT )\n self.fps = stream.get(cv2.CAP_PROP_FPS )\n self.length = self.frames / self.fps\n self.offset = float(offset)\n self.duration = float(duration)\n # distance in msecs from start. Changes each time we \n # read a frame.\n #self.msec = stream.get(cv2.CAP_PROP_POS_MSEC )\n # Metadata DATETIME is in LOCALTIME format.\n self.start_time = self.creation_date + timedelta(seconds=self.offset)\n \n \n\n # adjust crop_duration value\n if self.duration > 0:\n self.crop_duration = self.duration\n if self.crop_duration > self.duration_m-self.offset:\n self.crop_duration = self.duration_m-self.offset\n else: \n self.crop_duration = self.duration_m-self.offset\n \n \n self.gpx_info = None\n\n def show_video_info(self):\n print(\"Video Information -[B]--------------------------------------------- \")\n print(\"File: \\t%s\" % self.video_file)\n print(\"WIDTH: \\t%d\" % self.width)\n print(\"HEIGHT: \\t%d\" % self.height)\n print(\"FPS: \\t%f\" % self.fps)\n print(\"FRAMES: \\t%d\" % self.frames)\n print(\"LENGTH(FPS): \\t%3.2f\"% (self.frames * (1.0/self.fps)))\n \n print(\"LENGTH: \\t%f s\" % self.length)\n print(\"Duration: \\t%s\" % self.duration_m)\n print(\"CDate: \\t%s\" % self.creation_date)\n print(\"Offset: \\t%s s\" % self.offset)\n print(\"Duration: \\t%s s\" % self.duration)\n print(\"Start_Time: \\t%s\" % self.start_time)\n print(\"Crop Duration:\\t%s s\" % self.crop_duration)\n print(\"Video Information -[E]--------------------------------------------- \")\n\n def show_gpx_info(self):\n\n print(\"GPX Information -[B]----------------------------------------------- \")\n print(\"File: \\t%s\" % self.gpx_info.gpx_file)\n print(\"Mode: \\t%s\" % self.gpx_info.gpx_mode)\n print(\"start range: \\t%s\" % self.gpx_info.start_time)\n print(\"end range: \\t%s\" % self.gpx_info.end_time)\n print(\"len range: \\t%d\" % self.gpx_info.points_len)\n print(\"len (all): \\t%d\" % self.gpx_info.points_all)\n print(\"start (all): \\t%s\" % self.gpx_info.start_time_all)\n print(\"end (all): \\t%s\" % self.gpx_info.end_time_all)\n print(\"duration (all): \\t%s\" % (self.gpx_info.end_time_all - self.gpx_info.start_time_all))\n print(\"GPX Information -[E]----------------------------------------------- \")\n\n\n# ############################################################################\n#\n# MAIN\n#\n# ############################################################################\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-o\", \"--offset\", help=\"Offset in seconds from Video Start\", action=\"store\", default=0)\n parser.add_argument(\"-d\", \"--duration\", help=\"Duration in seconds from Video Start or offset\", action=\"store\", default=0)\n parser.add_argument(\"-v\", \"--verbose\", help=\"Show data about file and processing\", action=\"count\")\n parser.add_argument(\"-l\", \"--layer\", help=\"Create a layer to use in Final Cut (Overlay)\", action=\"store_true\")\n parser.add_argument(\"-s\", \"--show\", help=\"Show frames during encoding\", action=\"store_true\")\n parser.add_argument(\"-x\", \"--small\", help=\"Generate fast, small, low quality video\", action=\"store_true\")\n parser.add_argument(\"-i\", \"--only-info\", help=\"Show info then exit\", action=\"store_true\", default=False)\n parser.add_argument(\"-c\", \"--no-cache\", help=\"Don't use file cache\", action=\"store_true\", default=False)\n parser.add_argument(\"-g\", \"--gopro\", help=\"Read the GPX data from goproFile\", action=\"store_true\", default=False)\n parser.add_argument(\"-f\", \"--fix-gopro\", help=\"Remove all tracks and process only video (gopro Fix)\", action=\"store_true\", default=False)\n\n parser.add_argument(\"-t\", \"--title\", help=\"Title to write\")\n parser.add_argument(\"config_file\", help=\"XML configuration file\")\n parser.add_argument(\"gpx_file\", help=\"GPX 1.1 file [fit|gpx]\")\n parser.add_argument(\"video_file\", help=\"Video to be tagged\")\n parser.add_argument(\"output_file\", help=\"Generated video with HUD info\")\n args = parser.parse_args()\n\n hrmmanager = HRMManager(verbose=args.verbose)\n ffmpeg_helper = FFMPEGAdapter()\n\n if not args.fix_gopro:\n stream = cv2.VideoCapture(args.video_file)\n else:\n # remove first all the tracks, leave only the video\n # use the no sound video as source.\n #\n f_name = ffmpeg_helper.GetOnlyVideoTrack(args.video_file, cache=not args.no_cache)\n stream = cv2.VideoCapture(f_name)\n print(\"Using %s as input stream (fix-Gopro=True)\" % f_name)\n \n clip_info = ClipInfo(args.video_file, stream, offset=args.offset, duration=args.duration)\n\n clip_info.show_video_info()\n\n # Video Loaded. Now, I have to load the GPX file and get the points in\n # the interval marked for video. Do some trick to match the current\n # video to the GPX (I have no real data).\n # autodectect file, and get the parser acording to extension\n\n if args.gopro:\n if args.verbose > 1:\n print(\"Running Gopro2GPX first\")\n\n file_name, file_extension = os.path.splitext(args.video_file)\n gopro_args = EmptyClass()\n gopro_args.verbose = args.verbose\n gopro_args.outputfile = file_name # adds automatically .gpx\n gopro_args.files = [ args.video_file ]\n gopro_args.binary = False\n gopro_args.skip = True\n gopro2gpx.main_core(gopro_args)\n args.gpx_file = \"%s.gpx\" % file_name\n\n if args.verbose > 1:\n print(\"Done. Mapped file to %s\" % args.gpx_file)\n\n\n fname,fext = os.path.splitext(args.gpx_file)\n mode = fext.lower().replace('.','')\n gpx_points,gpx_info,gpx_map_points = hrmmanager.GetTimeRange(mode,\n args.gpx_file, \n clip_info.start_time, \n clip_info.crop_duration,\n clip_info.creation_date)\n\n clip_info.gpx_info = gpx_info \n clip_info.show_gpx_info()\n\n if args.only_info:\n exit(0)\n\n # TODO: check if video is in range from GPX data.\n\n if not gpx_points:\n print((\"Error, can't guess type for %s. Can't parse it. Ensure is FIT or GPX file.\" % args.gpx_file))\n sys.exit(1)\n\n data_series = CreateSeries(gpx_points)\n data_series = Smooth(data_series, [ \"slope\", \"speed\" ],len(gpx_points) )\n \n # save dump for testing\n if False:\n gpx_item = GPXItem(gpx_points)\n gpxtxt = gpx_item.CreateGPX11(gpx_points)\n f = open(\"salida.gpx\", \"w+\")\n f.write(gpxtxt)\n f.close()\n\n if False:\n print(data_series[0].header())\n for i in data_series:\n print(i)\n sys.exit(0)\n \n # init things\n\n engine = Engine((clip_info.width, clip_info.height), clip_info.fps)\n pygame.init()\n pygame.font.init()\n #screen=pygame.display.set_mode([width,height]) #small screen\n #screen=pygame.display.set_mode([320,200]) #small screen\n screen = pygame.display.set_mode([clip_info.width,clip_info.height],pygame.SRCALPHA,32)\n\n #engine.CreateFonts()\n #engine.CreateGauges() ## some customization for KM/H, units, etc.\n engine.ReadConfigFromFile(args.config_file)\n engine.Init()\n\n #engine.title.update(args.title)\n\n # set title (create a gauge called TITLE)\n #text = engine.fonts.default.render(\"HUD v 1.0\", 1, prefs.colors.foreground)\n #textpos = text.get_rect(centerx=background.get_width()/2)\n\n # create the output video\n # AUDIO IS DISCARDED SO LETS WORK WITH FFMPEG TO ADD THE AUDIO LAYER IF NEEDED\n\n\n fourcc = cv2.VideoWriter_fourcc(*'X264') # DIVX, XVID, MJPG, X264, WMV1, WMV2, AVC1 (works: XVID)\n ostream = cv2.VideoWriter(args.output_file,fourcc, clip_info.fps, (clip_info.width,clip_info.height))\n\n #\n # POINT INFO:\n # BEGIN [ POINTS ] END\n # BEGIN and END points are inserted to do some nice calculations\n #\n\n gpx_index = 0\n gpx_point = gpx_points[gpx_index]\n gpx_point_prev = gpx_points[gpx_index]\n\n\n # set the current_time\n\n current_time = clip_info.creation_date # the begining of the clip, instead start_date\n frame_counter = 0\n\n # if we want to create a matte (-l) for FCP.\n\n if args.layer:\n # match the openCV frame format\n background_surface_np = np.zeros( (clip_info.height, clip_info.width, 4), np.uint8 )\n\n\n # begin calculate things #################################################\n # TODO this create the elevation and OSM map. If not found, don't use\n\n\n do_osm = False\n do_altgraph = False\n\n #\n #\n\n for item in engine.config.elements:\n \n if type(item) == type(gauges.OSMMapGauge()):\n do_osm = True\n if type(item) == type(gauges.AltGraphGauge()):\n do_altgraph = True\n \n if do_osm:\n osmmaps = engine.GetItemsByName(\"osmmap\")\n for i in osmmaps:\n i.set_points(gpx_points)\n i.CreateMap()\n\n if do_altgraph:\n altgraph = engine.GetItemsByName(\"altgraph\")\n for i in altgraph:\n i.set_points(gpx_points)\n i.CreateMap()\n\n\n distance = 0.0\n delta = 0\n\n #\n # if instrumentation, don't read all the frames. Read first one,\n # extract delta, and work on it (to speed up the things a little)\n # also don't copy audio\n #\n\n metrics = BaseConfig()\n\n metrics.slope = None\n metrics.elevation = None\n metrics.distance = None\n metrics.speed = None\n metrics.title = args.title\n #metrics.time = datetime.datetime.now().timetuple()\n metrics.time = datetime.datetime.now()\n metrics.cadence = None\n metrics.temp = None\n metrics.hr = None\n metrics.power = None\n metrics.position_index = 0\n metrics.current_position = gpx_points[0]\n metrics.bearing = None\n\n\n\n delta = 0.0\n while True:\n \n # grab the current frame\n # if we are viewing a video and we did not grab a frame,\n # then we have reached the end of the video\n \n if not args.layer:\n (grabbed, frame) = stream.read()\n if args.video_file and not grabbed:\n break\n\n\n # time pointers explained.\n # get the frame delta interval\n\n # clip_info.creation_date\n # | clip_info.offset\n # | | \n # v v\n # B---------x---------------------------------x-----E\n # [ clip_info.crop_duration in seconds ]\n # ^ ^\n # | | current_time (adding the delta from the beginning)\n # clip_info.start_time\n #\n # 1) wait to delta is equal to offset (in seconds)\n # 2) while current time < clip_info.start_time + duration, do the work\n # 3) end.\n\n if not args.layer:\n delta = stream.get(cv2.CAP_PROP_POS_MSEC) # current position of the file relative to the start.\n else: \n delta += (1.0/clip_info.fps) * 1000\n \n tdelta = datetime.timedelta(milliseconds=delta)\n current_time = clip_info.creation_date + tdelta # absolute pointer from the begining of the video.\n \n frame_time = (frame_counter % clip_info.fps) * 1.0/clip_info.fps #between 0.x and 0 (when frame change happens)\n \n # skip the offset and calculate duration\n\n if datetime.timedelta(milliseconds=delta).total_seconds() < clip_info.offset:\n if args.verbose >3:\n print(\"CROPPING: Skipping frame %3.3f\" % tdelta.total_seconds())\n continue\n \n if current_time > clip_info.start_time + datetime.timedelta(seconds=clip_info.crop_duration):\n if args.verbose >3:\n print(\"CROPPING: duration reached, exit\")\n break\n\n # print(\"Current Time:%s , UTC: %s\" % (current_time, gpxtoolbox.utc_to_local(gpx_point.time) ))\n # if current_time > gpxtoolbox.utc_to_local(gpx_point.time):\n if current_time > gpx_point.time:\n #\n # move point. If last one, stick to it if it is the same, skip it ahead\n #\n \n if gpx_index + 1 < len(gpx_points):\n \n gpx_index += 1\n gpx_point = gpx_points[gpx_index]\n gpx_point_prev = gpx_points[gpx_index-1]\n\n distance += Distance(gpx_point_prev, gpx_point)\n\n # update graphics engine with data.\n # engine.Update(metrics)\n # sys.exit(0)\n \n if engine.config.interpolate:\n metrics.slope = Interpolate( gpx_point_prev.time , data_series[gpx_index-1].slope, gpx_point.time , data_series[gpx_index].slope, frame_time )\n metrics.elevation = Interpolate( gpx_point_prev.time , gpx_point_prev.elevation, gpx_point.time , gpx_point.elevation, frame_time ) \n # this fucking shit brokes everything jumping back and forth\n \n metrics.distance = distance + DistanceI(gpx_point_prev, gpx_point, current_time, \"#\" )\n \n metrics.speed = Interpolate( gpx_point_prev.time , data_series[gpx_index-1].speed, gpx_point.time , data_series[gpx_index].speed, frame_time )\n metrics.bearing = Interpolate( gpx_point_prev.time , data_series[gpx_index-1].bearing, gpx_point.time , data_series[gpx_index].bearing, frame_time )\n else:\n\n metrics.slope = data_series[gpx_index].slope\n metrics.elevation = gpx_point.elevation\n metrics.distance = distance\n metrics.speed = data_series[gpx_index].speed\n metrics.bearing = data_series[gpx_index].bearing\n\n \n metrics.time = current_time.astimezone(clip_info.local_tz)\n # should be previous ?\n metrics.position_index = gpx_index\n metrics.current_position = gpx_point\n \n\n if gpx_point.extensions[0]:\n\n for ext_item in [ \"cadence\", \"temperature\", \"hr\", \"power\"]:\n\n if ext_item in list(gpx_point.extensions[0].keys()):\n \n if engine.config.interpolate:\n metrics.__dict__[ext_item] = Interpolate( gpx_point_prev.time , gpx_point_prev.extensions[0][ext_item],\n gpx_point.time , gpx_point.extensions[0][ext_item],\n frame_time )\n else:\n metrics.__dict__[ext_item] = gpx_point.extensions[0][ext_item]\n \n\n # update graphics engine with data.\n # test, doesn't change metrics.__dict__['power'] = frame_counter\n # print(\"-\" * 80)\n engine.Update(metrics)\n ##engine.Print()\n\n\n\n # \n #\n # annotate with PYGAME the required information.\n # set here the graphics, etc.\n #\n if args.layer:\n sf = pygame.image.frombuffer(background_surface_np.tobytes(), background_surface_np.shape[1::-1], \"BGRA\")\n #sf = cvimage_to_pygame(background_surface_np)\n else:\n sf = cvimage_to_pygame(frame)\n\n\n # print(\"=\" * 80)\n # print(metrics)\n # print(\"=\" * 80)\n\n # prepare overlay to be written\n engine.Draw(sf)\n\n # move to window\n frame = pygame_to_cvimage(sf)\n\n # write the data output\n ostream.write(frame)\n\n # show the frame to our screen and increment the frame counter\n\n if not args.layer:\n if args.show:\n cv2.imshow(\"Frame\", frame)\n #key = cv2.waitKey(1) & 0xFF\n key = cv2.pollKey()\n\n # if the 'q' key is pressed, stop the loop\n if key == ord(\"q\"):\n break\n \n\n\n if frame_counter % clip_info.fps == 0 and frame_counter >0:\n print((\"FPS: %s frames: %08d/%d distance: %05.2f elevation: %05.2f speed: %05.2f slope: %05.2f\" % (\n current_time, frame_counter, clip_info.frames, \n metrics.distance, metrics.elevation, metrics.speed, metrics.slope)))\n\n frame_counter += 1\n ### end while\n\n # cleanup the camera and close any open windows\n\n ostream.release()\n stream.release()\n cv2.destroyAllWindows()\n pygame.quit()\n \n # create and restore the file\n ffmpeg_helper.CopyAudioStream(args.video_file, args.output_file, \n offset=clip_info.offset, \n duration=clip_info.crop_duration, \n fps=clip_info.fps)\n\n if args.small:\n ffmpeg_helper.GenerateLowRes(args.video_file, args.output_file, cache=not args.no_cache)\n \n # blend things\n # C:\\software\\ffmpeg\\ffmpeg -ss 0 -t 5 -i .\\samples\\Fresnedillas-Robledo-ROAD\\video2.mp4 -i .\\samples\\Fresnedillas-Robledo-ROAD\\output.avi -filter_complex \"[0:v] format=rgba [bg]; [1:v] format=rgba [fg]; [bg][fg] blend=all_mode='multiply':all_opacity=1, format=rgba\" .\\samples\\Fresnedillas-Robledo-ROAD\\xxx.avi","repo_name":"juanmcasillas/VideoSync","sub_path":"hudint.py","file_name":"hudint.py","file_ext":"py","file_size_in_byte":21349,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"6468453984","text":"# we are trying to print the day of the week of a given date. The date format is M/D/Y\n# there's a weekday() function within the calendar module for this tasks\n# we need to use the input data as args for the weekday() function\n# when a string such as 05 is converted using the int() method, the 0 is removed\n# this function returns the day of the week as an index, eg 0 for Monday and 1 for Tuesday\nimport calendar\ndate = input().split()\ndays_of_the_week = [\"MONDAY\", \"TUESDAY\", \"WEDNESDAY\", \"THURSDAY\", \"FRIDAY\", \"SATURDAY\", \"SUNDAY\"]\nmonth, day, year = int(date[0]), int(date[1]), int(date[2])\nprint(days_of_the_week[calendar.weekday(year, month, day)])","repo_name":"ramogi4960/Hackerrank-challenges","sub_path":"calenda module.py","file_name":"calenda module.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"40366384069","text":"#!/usr/bin/env python3\n\nimport sys\nimport socket\nimport struct\n\n\nclass Protocol(object):\n def __init__(self):\n self.buffer = []\n\n def add(self,button,color,delay=0):\n self.buffer.append((button,color,delay))\n\n def get(self,data,sz):\n pass\n\n def commit(self):\n res = self.generate()\n self.buffer = []\n return res\n\n\nclass BinaryProtocol(Protocol):\n def generate(self):\n res = b\"\"\n for button,color,delay in self.buffer:\n res += struct.pack(\" 0:\n self.sock.sendto(struct.pack(\" 0:\n self.sock.send(struct.pack(\"'\n elif layer_type == 'LSTM':\n rnn_layer_type = f'RTNeural::LSTMLayerT'\n dense_layer_type_1 = f'RTNeural::DenseT'\n activation_layer_type = f'RTNeural::SigmoidActivationT'\n dense_layer_type_2 = f'RTNeural::DenseT'\n model_type = f'RTNeural::ModelT'\n model_type_alias = f'ModelType_{layer_type}_{rnn_dim}_{io_dim}'\n model_variant_types.append(model_type_alias)\n\n model_variant_using_declarations.append(f'using {model_type_alias} = {model_type};\\n')\n model_type_checkers.append(f'''inline bool is_model_type_{model_type_alias} (const nlohmann::json& model_json) {{\n const auto rnn_layer_type = model_json.at (\"layers\").at (0).at (\"type\").get();\n const auto is_layer_type_correct = rnn_layer_type == \"{layer_type.lower()}\";\n const auto rnn_dim = model_json.at (\"layers\").at (0).at (\"shape\").back().get();\n const auto is_rnn_dim_correct = rnn_dim == {rnn_dim};\n const auto io_dim = model_json.at (\"in_shape\").back().get();\n const auto is_io_dim_correct = io_dim == {io_dim};\n return is_layer_type_correct && is_rnn_dim_correct && is_io_dim_correct;\n}}\\n\\n''')\n\n\nwith open(\"src/model_variant.hpp\", \"w\") as header_file:\n header_file.write('#include \\n')\n header_file.write('#include \\n')\n header_file.write('\\n')\n\n header_file.write('struct NullModel { static constexpr int input_size = 0; static constexpr int output_size = 0; };\\n')\n header_file.writelines(model_variant_using_declarations)\n header_file.write(f'using ModelVariantType = std::variant;\\n')\n header_file.write('\\n')\n\n header_file.writelines(model_type_checkers)\n \n header_file.write('inline bool custom_model_creator (const nlohmann::json& model_json, ModelVariantType& model) {\\n')\n if_statement = 'if'\n for type_checker, alias in zip(model_type_checkers, model_variant_types):\n header_file.write(f' {if_statement} (is_model_type_{alias} (model_json)) {{\\n')\n header_file.write(f' model.emplace<{alias}>();\\n')\n header_file.write(f' return true;\\n')\n header_file.write(' }\\n')\n if_statement = 'else if'\n header_file.write(f' model.emplace();\\n')\n header_file.write(f' return false;\\n')\n header_file.write('}\\n')\n\n","repo_name":"jatinchowdhury18/RTNeural-Variant","sub_path":"python/generate_variant_hpp.py","file_name":"generate_variant_hpp.py","file_ext":"py","file_size_in_byte":2977,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"77"}
+{"seq_id":"23149453334","text":"#!/usr/bin/python3\r\n# -*- coding: utf-8 -*-\r\n# __author__ = '__JonPan__'\r\n\r\nfrom flask import jsonify, g\r\n\r\nfrom app.libs.redprint import RedPrint\r\nfrom app.libs.auths import auth\r\nfrom app.models.user import User\r\nfrom app.models.base import db\r\n\r\nfrom app.libs.error_handle import DeleteSuccess\r\n\r\napi = RedPrint('user')\r\n\r\n\r\n@api.route('/', methods=['GET'])\r\n@auth.login_required\r\ndef super_get_user(uid):\r\n user = User.query.filter_by(id=uid).first_or_404()\r\n return jsonify(user)\r\n\r\n\r\n@api.route('/', methods=['GET'])\r\ndef super_del_user(uid):\r\n pass\r\n\r\n\r\n@api.route('', methods=['GET'])\r\n@auth.login_required\r\ndef get_user():\r\n uid = g.user.uid\r\n user = User.query.filter_by(id=uid).first_or_404()\r\n return jsonify(user)\r\n\r\n\r\n@api.route('', methods=['DELETE'])\r\n@auth.login_required\r\ndef delete_user():\r\n # 删除只能删除自己,g变量是线程隔离的,所以每个请求会对应自己的uid\r\n uid = g.user.uid\r\n with db.auto_commit():\r\n user = User.query.filter_by(id=uid).first_or_404()\r\n user.delete()\r\n return DeleteSuccess()\r\n\r\n","repo_name":"Panlq/Py-Project","sub_path":"Web-Pro/yushu2/app/api/v1/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"77"}
+{"seq_id":"42460140256","text":"\"\"\"Defines classes and related functions that are used to process files.\"\"\"\nimport hashlib\nimport logging\nimport re\nimport string\nimport time\nimport uuid\nimport zlib\nimport os\n\nfrom boltons import iterutils\nimport boto3\nimport botocore.client\nfrom google.cloud.storage import Client\nimport inflection\nimport interruptingcow\nimport magic\nimport requests\nimport swiftclient\nimport yara\nimport glob\n\nfrom server import strelka_pb2\nfrom shared import conf\nfrom shared import errors\n\ngcs_client = None\ns3_client = None\nswift_client = None\ncompiled_magic = None\ncompiled_yara = None\n\n\ndef ensure_bytes(value):\n \"\"\"Converts value to bytes.\n\n Converts bytearray and str to bytes. Scanners may create\n child files that are one of these types, this method is used on\n every file object to ensure the file data is always bytes.\n\n Args:\n value: Value that needs conversion to bytes.\n\n Returns:\n A byte representation of value.\n \"\"\"\n if isinstance(value, bytearray):\n return bytes(value)\n elif isinstance(value, str):\n return value.encode('utf-8')\n return value\n\n\ndef ensure_utf8(value):\n \"\"\"Converts value to UTF-8 encoded string.\n\n Recursively converts bytes, bytearrays, and uuids to str. Scanners\n may output metadata that is one of these types and they need to be\n converted to str to be encoded as JSON, so this method is used on\n every metadata dictionary.\n\n Args:\n value: Value that needs recursive conversion to a UTF-8 encoded\n string.\n\n Returns:\n A UTF-8 encoded string representation of value.\n \"\"\"\n def visit(path, key, value):\n if isinstance(value, (bytes, bytearray)):\n value = str(value, encoding=\"UTF-8\", errors=\"replace\")\n elif isinstance(value, uuid.UUID):\n value = str(value)\n return key, value\n\n return iterutils.remap(value, visit=visit)\n\n\ndef normalize_whitespace(text):\n \"\"\"Normalizes whitespace in text.\n\n Scanners that parse text generally need the whitespace normalized,\n otherwise metadata parsed from the text may be unreliable. This function\n normalizes whitespace characters to a single space. This can also be used\n on scanner metadata.\n\n Args:\n text: Text that needs whitespace normalized.\n\n Returns:\n Text with whitespace normalized.\n \"\"\"\n if isinstance(text, bytes):\n text = re.sub(br\"\\s+\", b\" \", text)\n text = re.sub(br\"(^\\s+|\\s+$)\", b\"\", text)\n elif isinstance(text, str):\n text = re.sub(r\"\\s+\", \" \", text)\n text = re.sub(r\"(^\\s+|\\s+$)\", \"\", text)\n return text\n\n\ndef protobuf_to_file_object(task):\n \"\"\"Converts protobuf strelka_pb2.FileRequest to StrelkaFile.\n\n Args:\n task: Task received by the worker from the broker.\n\n Returns:\n Instance of StrelkaFile derived from task.\n \"\"\"\n file_request = strelka_pb2.FileRequest()\n file_request.ParseFromString(task)\n\n flavors = [flavor for flavor in file_request.flavors]\n metadata = {key: value for (key, value) in file_request.metadata.items()}\n\n if file_request.data:\n return StrelkaFile(data=zlib.decompress(file_request.data),\n filename=file_request.filename,\n source=file_request.source,\n external_flavors=flavors,\n external_metadata=metadata)\n elif file_request.location:\n location = {key:\n value for (key, value) in file_request.location.items()}\n return StrelkaFile(location=location,\n filename=file_request.filename,\n source=file_request.source,\n external_flavors=flavors,\n external_metadata=metadata)\n\n\nclass StrelkaFile(object):\n \"\"\"Class that defines files distributed through the system.\n\n Attributes:\n data: Byte string that contains the file content. This is a\n read-only attribute.\n location: Dictionary that contains details on where to retrieve a\n remote file. Files will be retrieved if data is None and location\n contains data. See README for more details. This is a read-only\n attribute.\n hash: SHA256 hash of data. This is a read-only attribute.\n uid: UUID that is used to uniquely identify the file. This is a\n read-only attribute.\n filename: String that contains the name of the file.\n depth: Integer that represents how deep the file was embedded in a\n root file.\n source: String that describes where the file originated.\n scanner_list: List of scanners that were assigned to the file during\n distribution.\n external_flavors: List of flavors assigned to the file when the file\n was created.\n external_metadata: Dictionary of external metadata related to\n the file.\n parent_uid: UUID of the parent file.\n root_uid: UUID of the root file.\n parent_hash: SHA256 hash of the parent file.\n root_hash: SHA256 hash of the root file.\n flags: List of flags that are appended during scanning.\n metadata: Dictionary of metadata that is appended during scanning.\n \"\"\"\n def __init__(self,\n data=None,\n location=None,\n filename=None,\n depth=None,\n parent_uid=None,\n root_uid=None,\n parent_hash=None,\n root_hash=None,\n source=None,\n scanner_list=None,\n external_flavors=None,\n external_metadata=None):\n \"\"\"Initializes file object.\"\"\"\n self._data = data or b\"\"\n self._location = location or {}\n if self._location and not self._data:\n type = self._location.get(\"type\")\n bucket = self._location.get(\"bucket\")\n object = self._location.get(\"object\")\n\n try:\n if type == \"amazon\":\n self._data = self.retrieve_from_amazon(bucket, object)\n elif type == \"google\":\n self._data = self.retrieve_from_google(bucket, object)\n elif type == \"openstack\":\n self._data = self.retrieve_from_openstack(bucket, object)\n elif type == \"http\":\n self._data = self.retrieve_from_http(object)\n\n except Exception:\n logging.exception(\"File: exception while creating file from\"\n f\" location {self._location} (see traceback\"\n \" below)\")\n\n self._data = ensure_bytes(self._data)\n self._hash = hashlib.sha256(self._data).hexdigest()\n self._size = len(self._data)\n self._uid = uuid.uuid4()\n self.filename = filename or \"\"\n self.depth = depth or 0\n self.source = source or \"\"\n self.scanner_list = scanner_list or []\n self.external_flavors = external_flavors or []\n self.external_metadata = external_metadata or {}\n self.parent_uid = parent_uid or \"\"\n self.parent_hash = parent_hash or \"\"\n if self.depth == 0:\n self.root_uid = self.uid\n self.root_hash = self.hash\n else:\n self.root_uid = root_uid or \"\"\n self.root_hash = root_hash or \"\"\n self.flags = []\n self._flavors = {\"external\": ensure_utf8(self.external_flavors),\n \"mime\": ensure_utf8(self.taste_mime()),\n \"yara\": ensure_utf8(self.taste_yara())}\n self.metadata = {}\n self.append_metadata({\"externalMetadata\": self.external_metadata})\n\n @property\n def data(self):\n return self._data\n\n @property\n def flavors(self):\n return self._flavors\n\n @property\n def hash(self):\n return self._hash\n\n @property\n def location(self):\n return self._location\n\n @property\n def size(self):\n return self._size\n\n @property\n def uid(self):\n return self._uid\n\n def append_metadata(self, meta_dictionary):\n \"\"\"Merges scanner metadata with file object metadata.\"\"\"\n self.metadata = {**self.metadata, **ensure_utf8(meta_dictionary)}\n\n def retrieve_from_amazon(self, bucket, object):\n \"\"\"Retrieves file from Amazon S3.\n\n Args:\n bucket: Bucket to retrieve file from.\n object: File object to retrieve.\n\n Returns:\n A byte string containing the file content.\n \"\"\"\n global s3_client\n if s3_client is None:\n s3_client = boto3.client(\"s3\",\n aws_access_key_id=conf.remote_cfg[\"aws_access_key_id\"],\n aws_secret_access_key=conf.remote_cfg[\"aws_secret_access_key\"],\n config=botocore.client.Config(\n connect_timeout=conf.remote_cfg[\"remote_timeout\"],\n read_timeout=conf.remote_cfg[\"remote_timeout\"],\n region_name=conf.remote_cfg[\"aws_default_region\"],\n retries={\"max_attempts\": conf.remote_cfg[\"remote_retries\"]}\n ))\n return s3_client.get_object(Bucket=bucket, Key=object)['Body'].read()\n\n def retrieve_from_google(self, bucket, object):\n \"\"\"Retrieves file from Google Cloud Storage.\n\n Args:\n bucket: Bucket to retrieve file from.\n object: File object to retrieve.\n\n Returns:\n A byte string containing the file content.\n \"\"\"\n global gcs_client\n if gcs_client is None:\n gcs_client = Client.from_service_account_json(conf.remote_cfg[\"google_application_credentials\"])\n return gcs_client.get_bucket(bucket).get_blob(object).download_as_string()\n\n def retrieve_from_http(self, url):\n \"\"\"Retrieves file from HTTP server.\n\n Args:\n url: URL where file is hosted.\n\n Returns:\n A byte string containing the file content.\n \"\"\"\n retry_counter = 0\n while retry_counter < conf.remote_cfg[\"remote_retries\"] + 1:\n if retry_counter != 0:\n time.sleep(retry_counter * 5)\n\n try:\n response = requests.get(url,\n allow_redirects=True,\n stream=True,\n auth=(conf.remote_cfg[\"http_basic_user\"],\n conf.remote_cfg[\"http_basic_pass\"]),\n timeout=conf.remote_cfg[\"remote_timeout\"],\n verify=conf.remote_cfg[\"http_verify\"])\n if response.status_code == 200:\n return response.raw.read()\n elif response.status_code:\n return b\"\"\n except requests.exceptions.ConnectTimeout:\n retry_counter += 1\n\n def retrieve_from_openstack(self, container, object):\n \"\"\"Retrieves file from OpenStack Swift.\n\n Args:\n container: Container to retrieve file from.\n object: File object to retrieve.\n\n Returns:\n A byte string containing the file content.\n \"\"\"\n global swift_client\n if swift_client is None:\n swift_client = swiftclient.Connection(auth_version=conf.remote_cfg[\"st_auth_version\"],\n authurl=conf.remote_cfg[\"os_auth_url\"],\n user=conf.remote_cfg[\"os_username\"],\n key=conf.remote_cfg[\"os_password\"],\n cert=conf.remote_cfg[\"os_cert\"],\n cacert=conf.remote_cfg[\"os_cacert\"],\n retries=conf.remote_cfg[\"remote_retries\"],\n timeout=conf.remote_cfg[\"remote_timeout\"])\n os_options = {\"user_domain_name\": conf.remote_cfg[\"os_user_domain_name\"],\n \"project_domain_name\": conf.remote_cfg[\"os_project_domain_name\"],\n \"project_name\": conf.remote_cfg[\"os_project_name\"]}\n if not all(value is None for value in os_options.values()):\n swift_client.os_options = os_options\n (response_headers,\n object_data) = swift_client.get_object(container,\n object)\n return object_data\n\n def taste_mime(self):\n \"\"\"Tastes file data with libmagic.\n\n Tastes file data with libmagic and appends the MIME type to the\n file object.\n\n Args:\n magic_file: Location of the MIME database used to taste files.\n Defaults to system default.\n \"\"\"\n try:\n global compiled_magic\n if compiled_magic is None:\n distro_cfg = conf.scan_cfg.get(\"distribution\", {})\n taste_mime_db = distro_cfg.get(\"taste_mime_db\", None)\n compiled_magic = magic.Magic(magic_file=taste_mime_db,\n mime=True)\n mime_type = compiled_magic.from_buffer(self._data)\n return [mime_type]\n\n except magic.MagicException:\n self.flags.append(\"StrelkaFile::magic_exception\")\n logging.exception(f\"Exception while tasting with magic\"\n \" (see traceback below)\")\n\n def taste_yara(self):\n \"\"\"Taste files with YARA.\n\n Tastes file data with YARA and appends the matches to the file object.\n Whitespace is stripped from the leftside of the file data to increase\n the reliability of YARA matching.\n\n Args:\n taste_yara_rules: Location of the directory of YARA files that contains\n rules used to taste files.\n \"\"\"\n try:\n global compiled_yara\n if compiled_yara is None:\n distro_cfg = conf.scan_cfg.get(\"distribution\", {})\n taste_yara_dir = distro_cfg.get(\"taste_yara_rules\",\n \"etc/strelka/taste/\")\n\n if os.path.isdir(taste_yara_dir):\n yara_filepaths = {}\n globbed_yara_paths = glob.iglob(f\"{taste_yara_dir}/**/*.yar*\", recursive=True)\n for (idx, entry) in enumerate(globbed_yara_paths):\n yara_filepaths[f\"namespace_{idx}\"] = entry\n compiled_yara = yara.compile(filepaths=yara_filepaths)\n\n else:\n compiled_yara = yara.compile(filepath=taste_yara_dir)\n\n encoded_whitespace = string.whitespace.encode()\n stripped_data = self._data.lstrip(encoded_whitespace)\n yara_matches = compiled_yara.match(data=stripped_data)\n return [match.rule for match in yara_matches]\n\n except (yara.Error, yara.TimeoutError) as YaraError:\n self.flags.append(\"StrelkaFile::yara_scan_error\")\n logging.exception(\"Exception while tasting with YARA directory\"\n f\" {taste_yara_dir} (see traceback below)\")\n\n\nclass StrelkaScanner(object):\n \"\"\"Class that defines scanners used in the system.\n\n Each scanner inherits this class and overrides methods within the class\n to perform their scanning functions.\n\n Attributes:\n scanner_name: String that contains the scanner class name.\n This is referenced in flags and child filenames.\n scanner_timeout: Amount of time (in seconds) that a scanner can spend\n scanning a file. Can be overridden on a per-scanner basis\n (see scan_wrapper).\n Defaults to 600 seconds / 5 minutes.\n close_timeout: Amount of time (in seconds) that a scanner can spend\n closing itself.\n Defaults to 30 seconds.\n metadata_key: String that contains the scanner's metadata key. This is\n used to identify the scanner's metadata in the scan results.\n file_object: Instance of File that will be scanned by the scanner.\n options: Dictionary of options associated with the scanner that was\n assigned when the file was distributed.\n metadata: Dictionary where scanner metadata is stored.\n children: List where scanner child files are stored.\n \"\"\"\n def __init__(self):\n \"\"\"Initializes scanner.\"\"\"\n distro_cfg = conf.scan_cfg.get(\"distribution\", {})\n self.scanner_name = self.__class__.__name__\n self.scanner_timeout = distro_cfg.get(\"scanner_timeout\", 600)\n self.close_timeout = distro_cfg.get(\"close_timeout\", 30)\n metadata_key = self.scanner_name.replace(\"Scan\", \"\", 1) + \"Metadata\"\n self.metadata_key = inflection.camelize(metadata_key, False)\n self.init()\n\n def init(self):\n \"\"\"Method to be overridden by scanner initialization.\"\"\"\n pass\n\n def close(self):\n \"\"\"Method to be overridden by scanner closing code.\"\"\"\n pass\n\n def close_wrapper(self):\n \"\"\"Calls close method with timeout and error handling.\n\n Raises:\n errors.DistributionTimeout: Timeout occurred during distribution\n that halted the close.\n Exception: Unknown exception occurred.\n \"\"\"\n try:\n with interruptingcow.timeout(self.close_timeout,\n exception=errors.CloseTimeout):\n self.close()\n\n except errors.DistributionTimeout:\n raise\n except errors.CloseTimeout:\n pass\n except errors.QuitWorker:\n logging.info(f\"{self.scanner_name}: shutdown while closing\")\n raise\n except Exception:\n logging.exception(f\"{self.scanner_name}: exception while closing\"\n \"(see traceback below)\")\n\n def scan(self,\n file_object,\n options):\n \"\"\"Method to be overridden by scanner processing code.\"\"\"\n pass\n\n def scan_wrapper(self,\n file_object,\n options):\n \"\"\"Sets up scan attributes and calls scan method.\n\n Scanning code is wrapped in interruptingcow and try/except to handle\n timeout and error handling. The file object is always appended with\n metadata, regardless of whether the scanner completed successfully,\n timed out, or hit an exception.\n\n Returns:\n Children files, whether they exist or not.\n\n Raises:\n errors.DistributionTimeout: Timeout occurred during distribution\n that halted the scan.\n errors.ScannerTimeout: Timeout occurred during scan that halted\n the scan.\n Exception: Unknown exception occurred.\n \"\"\"\n self.metadata = {}\n self.children = []\n self.scanner_timeout = options.get(\"scanner_timeout\",\n self.scanner_timeout)\n\n try:\n with interruptingcow.timeout(self.scanner_timeout,\n exception=errors.ScannerTimeout):\n self.scan(file_object, options)\n\n except errors.DistributionTimeout:\n raise\n except errors.ScannerTimeout:\n file_object.flags.append(f\"{self.scanner_name}::timed_out\")\n except errors.QuitWorker:\n logging.info(f\"{self.scanner_name}: shutdown while scanning file\"\n f\" with hash {file_object.hash} and uid\"\n f\" {file_object.uid}\")\n raise\n except Exception:\n logging.exception(f\"{self.scanner_name}: exception while scanning\"\n f\" file with hash {file_object.hash} and uid\"\n f\" {file_object.uid} (see traceback below)\")\n\n file_object.append_metadata({self.metadata_key: self.metadata})\n return self.children\n","repo_name":"seclab-int-dev-group/strelka","sub_path":"server/objects.py","file_name":"objects.py","file_ext":"py","file_size_in_byte":20385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"77"}
+{"seq_id":"10314917263","text":"import numpy as np\nimport cv2\nimport pandas as pd\nimport glob\nfrom pathlib import Path\n\ndesiredLeftEye = np.array([44, 64])\ndesiredRightEye = np.array([84, 64])\ndesiredFaceWidth = desiredFaceHeight = 128\n\n\ndef getEyeAngleAndDistance(rightEye, leftEye):\n dY = rightEye[0][1] - leftEye[0][1]\n dX = rightEye[0][0] - leftEye[0][0]\n angle = np.degrees(np.arctan2(dY, dX))\n dist = np.sqrt((dX ** 2) + (dY ** 2))\n return angle, dist\n\n\ndf = pd.read_csv('cats.csv')\nfor image in glob.iglob('./*.jpg', recursive=True):\n p = Path(image)\n name = p.name\n image = cv2.imread(image)\n cv2.imshow('original', image)\n leftEye = df[df['file'] == name][['x1', 'y1']].to_numpy()\n rightEye = df[df['file'] == name][['x2', 'y2']].to_numpy()\n angle, dist = getEyeAngleAndDistance(rightEye, leftEye)\n desiredDist = (desiredRightEye[0] - desiredLeftEye[0])\n # desiredDist *= desiredFaceWidth\n scale = desiredDist / dist\n center = ((leftEye[0][0] + rightEye[0][0]) / 2, (leftEye[0][1] + rightEye[0][1]) / 2)\n M = cv2.getRotationMatrix2D(center, angle, scale)\n tX = desiredFaceWidth * 0.5\n tY = desiredLeftEye[1]\n M[0, 2] += (tX - center[0])\n M[1, 2] += (tY - center[1])\n (w, h) = (desiredFaceWidth, desiredFaceHeight)\n rotated = cv2.warpAffine(image, M, (w, h), cv2.INTER_LINEAR)\n # cv2.imshow('processed', rotated)\n # cv2.waitKey(0)\n cv2.imwrite(f'{name}_128.jpg', rotated)","repo_name":"varrek/pythonLearning","sub_path":"linear_algebra_for_ds/affine_transformations/align_cats_eyes.py","file_name":"align_cats_eyes.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"45211563766","text":"import shutil\nimport tempfile\n\nfrom django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.test import Client, TestCase, override_settings\nfrom django.urls import reverse\n\nfrom posts.forms import PostForm\nfrom posts.models import Group, Post\n\nUser = get_user_model()\n\n\nTEMP_MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR)\n\n\n@override_settings(MEDIA_ROOT=TEMP_MEDIA_ROOT)\nclass PostCreateFormTests(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.group = Group.objects.create(\n title='Тестовый заголовок',\n description='Тестовое описание',\n slug='test_slug'\n )\n cls.author = User.objects.create_user(username='SomeName')\n cls.post = Post.objects.create(\n author=cls.author,\n text='Тестовый пост',\n )\n cls.form = PostForm()\n\n @classmethod\n def tearDownClass(cls):\n super().tearDownClass()\n shutil.rmtree(TEMP_MEDIA_ROOT, ignore_errors=True)\n\n def setUp(self):\n self.authorized_client = Client()\n self.authorized_client.force_login(PostCreateFormTests.author)\n\n def test_form_create(self):\n \"\"\"Проверяем создание нового поста авторизированным поьзователем.\n После, автор перенаправляется на страницу поста /profile/\n \"\"\"\n post_count = Post.objects.count()\n small_gif = (\n b'\\x47\\x49\\x46\\x38\\x39\\x61\\x01\\x00'\n b'\\x01\\x00\\x00\\x01\\x00\\x21\\xf9\\x04'\n b'\\x01\\x0a\\x00\\x01\\x00\\x2c\\x00\\x00'\n b'\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02'\n b'\\x02\\x4c\\x01\\x00\\x3b'\n )\n uploaded = SimpleUploadedFile(\n name='small.gif',\n content=small_gif,\n content_type='image/gif'\n )\n form_data = {\n 'group': self.group.id,\n 'text': self.post.text,\n 'image': uploaded,\n }\n response = self.authorized_client.post(reverse('posts:post_create'),\n data=form_data,\n follow=True)\n self.assertRedirects(response, reverse('posts:profile',\n kwargs={'username': self.author}))\n self.assertEqual(Post.objects.count(), post_count + 1)\n self.assertTrue(Post.objects.filter(\n text=self.post.text,\n group=PostCreateFormTests.group,\n image='posts/small.gif').exists())\n\n def test_form_edit(self):\n \"\"\"\n Проверяем возможность редактирование поста через форму на странице\n \"\"\"\n form_data = {\n 'text': self.post.text,\n 'group': self.group.id\n }\n group = PostCreateFormTests.group\n test_post = Post.objects.create(\n text=self.post.text,\n author=PostCreateFormTests.author,\n group=group\n )\n test_post_id = test_post.id\n posts_count_before = Post.objects.count()\n path = self.authorized_client.post(\n reverse(\n 'posts:post_edit', kwargs={'post_id': self.post.id}\n ),\n data=form_data,\n follow=True\n )\n self.assertRedirects(path, reverse('posts:post_detail', kwargs={\n 'post_id': self.post.id}))\n edited_post = Post.objects.get(id=test_post_id)\n self.assertEqual(Post.objects.count(), posts_count_before)\n self.assertEqual(edited_post.text, form_data['text'])\n self.assertEqual(edited_post.group, self.group)\n self.assertEqual(edited_post.author, PostCreateFormTests.author)\n","repo_name":"UraeviIya/hw05_final","sub_path":"yatube/posts/tests/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":3911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"5169781273","text":"import bpy\n\nbl_info = {\n \"name\": \"Swap Vertex Groups\",\n \"description\": \"Swaps vertices between user-selected vertex groups.\",\n \"version\": (1, 1),\n \"blender\": (2, 80, 0),\n \"category\": \"Rigging\",\n \"location\": \"Properties > Object Data > Swap Vertex Groups\",\n \"doc_url\": \"https://github.com/soir20/blender-swap-vertex-groups/\",\n \"tracker_url\": \"https://github.com/soir20/blender-swap-vertex-groups/issues/\",\n \"support\": \"COMMUNITY\",\n}\n\n\ndef get_object_pose(obj):\n if obj is None:\n return None\n\n pose = obj.pose\n parent = obj.parent\n\n while pose is None and parent is not None:\n pose = parent.pose\n parent = parent.parent\n\n return pose\n\n\nclass SwapVertexGroupsOperator(bpy.types.Operator):\n \"\"\"Swaps the active object's vertices between the selected vertex groups\"\"\"\n bl_idname = \"swap_vert_group.swap\"\n bl_label = \"Swap Vertex Groups\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n @classmethod\n def poll(self, context):\n pose = get_object_pose(context.object)\n return pose is not None and len(pose.bones) > 0 and context.object.type == \"MESH\"\n\n def execute(self, context):\n obj = context.object\n original_mode = obj.mode\n pose = get_object_pose(obj)\n bones = [] if pose is None else pose.bones\n\n bpy.ops.object.mode_set(mode=\"OBJECT\")\n\n group1_name = bones[obj.selected_vertex_group1].name\n group2_name = bones[obj.selected_vertex_group2].name\n\n if group1_name == group2_name:\n self.report({\"INFO\"}, f\"Cannot swap group {group1_name} with itself\")\n return {\"CANCELLED\"}\n\n # Create group 1 and group 2 if needed.\n if group1_name not in obj.vertex_groups:\n obj.vertex_groups.new(name=group1_name)\n\n if group2_name not in obj.vertex_groups:\n obj.vertex_groups.new(name=group2_name)\n\n group1 = obj.vertex_groups[group1_name]\n group2 = obj.vertex_groups[group2_name]\n\n # Swap weights.\n num_vertices_changed = 0\n num_vertices_by_group = {}\n for vertex in obj.data.vertices:\n weights = {}\n\n # Get the weights to assign for group1 and group2.\n for group_elm in vertex.groups:\n weight = group_elm.weight\n\n group_name = obj.vertex_groups[group_elm.group].name\n num_vertices_by_group[group_name] = num_vertices_by_group.get(group_name, 0) + 1\n\n if not obj.swap_selected_only or vertex.select:\n if group_name == group1_name:\n group1.remove([vertex.index])\n num_vertices_by_group[group1_name] = num_vertices_by_group.get(group_name, 0) - 1\n weights[group2] = weight\n elif group_name == group2_name:\n group2.remove([vertex.index])\n num_vertices_by_group[group2_name] = num_vertices_by_group.get(group_name, 0) - 1\n weights[group1] = weight\n\n # Assign the new weights.\n for (group, weight) in weights.items():\n group.add([vertex.index], weight, \"ADD\")\n num_vertices_by_group[group.name] = num_vertices_by_group.get(group.name, 0) + 1\n\n if len(weights) > 0:\n num_vertices_changed += 1\n\n # Remove empty group1.\n if num_vertices_by_group.get(group1_name, 0) == 0:\n obj.vertex_groups.remove(group1)\n\n # Remove empty group2.\n if num_vertices_by_group.get(group2_name, 0) == 0:\n obj.vertex_groups.remove(group2)\n\n bpy.ops.object.mode_set(mode=original_mode)\n\n self.report({\"INFO\"}, f\"Swapped vertex groups for {num_vertices_changed} vertices\")\n\n return {\"FINISHED\"}\n\n\nclass VERTEX_GROUPS_UL_selector(bpy.types.UIList):\n # The draw_item function is called for each item of the collection that is visible in the list.\n # data is the RNA object containing the collection,\n # item is the current drawn item of the collection,\n # icon is the \"computed\" icon for the item (as an integer, because some objects like materials or textures\n # have custom icons ID, which are not available as enum items).\n # active_data is the RNA object containing the active property for the collection (i.e. integer pointing to the\n # active item of the collection).\n # active_propname is the name of the active property (use \"getattr(active_data, active_propname)\").\n # index is index of the current item in the collection.\n # flt_flag is the result of the filtering process for this item.\n # Note: as index and flt_flag are optional arguments, you do not have to use/declare them here if you don\"t\n # need them.\n def draw_item(self, context, layout, data, item, icon, active_data, active_propname):\n # draw_item must handle the three layout types... Usually \"DEFAULT\" and \"COMPACT\" can share the same code.\n if self.layout_type in {\"DEFAULT\", \"COMPACT\"}:\n # You should always start your row layout by a label (icon + text), or a non-embossed text field,\n # this will also make the row easily selectable in the list! The latter also enables ctrl-click rename.\n # We use icon_value of label, as our given icon is an integer value, not an enum ID.\n # Note \"data\" names should never be translated!\n layout.prop(item, \"name\", text=\"\", emboss=False, icon_value=icon)\n # \"GRID\" layout type should be as compact as possible (typically a single icon!).\n elif self.layout_type in {\"GRID\"}:\n layout.alignment = \"CENTER\"\n layout.label(text=\"\", icon_value=icon)\n\n\nclass SwapVertexGroupsPanel(bpy.types.Panel):\n \"\"\"Panel to select vertex groups that will be swapped\"\"\"\n bl_label = \"Swap Vertex Groups\"\n bl_idname = \"DATA_PT_swap_vertex_groups\"\n bl_space_type = \"PROPERTIES\"\n bl_region_type = \"WINDOW\"\n bl_context = \"data\"\n bl_options = {\"DEFAULT_CLOSED\"}\n\n def draw(self, context):\n obj = context.object\n pose = get_object_pose(obj)\n\n self.draw_list(obj, pose, \"Group 1\", \"first\", \"selected_vertex_group1\")\n self.draw_list(obj, pose, \"Group 2\", \"second\", \"selected_vertex_group2\")\n\n row = self.layout.row()\n row.prop(obj, \"swap_selected_only\")\n row = self.layout.row()\n row.operator(SwapVertexGroupsOperator.bl_idname)\n\n def draw_list(self, obj, pose, group_name, list_id, active_index_property):\n layout = self.layout\n\n split_factor = 0.3\n split = layout.split(factor=split_factor)\n col = split.column()\n col.alignment = \"RIGHT\"\n col.label(text=group_name)\n col = split.column()\n col.template_list(\"VERTEX_GROUPS_UL_selector\", list_id, pose, \"bones\", obj,\n active_index_property)\n\n\ndef register():\n bpy.types.Object.selected_vertex_group1 = bpy.props.IntProperty(name=\"First selected vertex group\")\n bpy.types.Object.selected_vertex_group2 = bpy.props.IntProperty(name=\"Second selected vertex group\")\n\n # This is not an operator property because the redo panel does not display from the object data panel.\n bpy.types.Object.swap_selected_only = bpy.props.BoolProperty(name=\"Swap selected vertices only\")\n\n bpy.utils.register_class(SwapVertexGroupsOperator)\n bpy.utils.register_class(VERTEX_GROUPS_UL_selector)\n bpy.utils.register_class(SwapVertexGroupsPanel)\n\n\ndef unregister():\n del bpy.types.Object.selected_vertex_group1\n del bpy.types.Object.selected_vertex_group2\n del bpy.types.Object.swap_selected_only\n bpy.utils.unregister_class(SwapVertexGroupsOperator)\n bpy.utils.unregister_class(VERTEX_GROUPS_UL_selector)\n bpy.utils.unregister_class(SwapVertexGroupsPanel)\n\n\nif __name__ == \"__main__\":\n register()\n","repo_name":"soir20/blender-swap-vertex-groups","sub_path":"swap_vertex_groups.py","file_name":"swap_vertex_groups.py","file_ext":"py","file_size_in_byte":7900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"4686721724","text":"import time\n\nimport paramiko\nssh_client=paramiko.SSHClient()\nssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #use for accept authentication of ssh\n\n# ssh_client.connect(hostname='192.168.75.10',username='pawan',password='cisco',port=22)\n\nswitch={\n 'hostname':'192.168.75.10',\n 'port': 22,\n 'username':'pawan',\n 'password':'cisco'\n}\n\nprint(f\"Connecting to {switch['hostname']}\")\na=ssh_client.connect(**switch)\n\nshell=ssh_client.invoke_shell()\nshell.send('terminal len 0\\n')\nshell.send('sh ver | i up \\n')\nshell.send('sh ip int brief\\n')\nshell.send('sh run\\n')\n\ntime.sleep(5)\noutput=shell.recv(10000)\noutput=output.decode()\nprint(output)\n\nif ssh_client.get_transport().is_active() == True: #True/False\n print(\"closing connection\")\n\n\n\n","repo_name":"pawanmann/NetworkAutomation","sub_path":"Paramiko lab/paramiko lab1.py","file_name":"paramiko lab1.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"17507778265","text":"'''\nFunction:\n 大吼一声发条微博\nAuthor:\n Charles\n微信公众号:\n Charles的皮卡丘\n'''\nimport os\nimport re\nimport time\nimport random\nimport struct\nimport pyaudio\nfrom DecryptLogin import login\n\n\n'''自动发微博'''\nclass WeiboSender():\n def __init__(self, username, password):\n self.nickname, self.uid, self.session = self.login(username, password)\n self.uid = re.findall(r'uid%3D(\\d+)', self.session.cookies.get('ALC'))[0]\n self.headers = {\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'\n }\n '''外部调用'''\n def run(self):\n while True:\n # 输入���博路径\n weibodir = input('请输入想要发送的微博路径(例如: ./weibo, 里面的weibo.md文件里写微博内容, pictures文件夹里放配图) ——> ')\n # 解析微博\n text, pictures = self.parseWeibo(weibodir)\n # 大吼一声确定是该微博\n self.logging('微博内容为: %s\\n配图数量为: %s' % (text, len(pictures)))\n self.logging('如果您确认想发这条微博, 请在30s内对着电脑大吼一声')\n stream = pyaudio.PyAudio().open(\n format=pyaudio.paInt16, \n channels=1, \n rate=int(pyaudio.PyAudio().get_device_info_by_index(0)['defaultSampleRate']), \n input=True, \n frames_per_buffer=1024\n )\n is_send_flag = False\n start_t = time.time()\n while True:\n time.sleep(0.1)\n audio_data = stream.read(1024)\n k = max(struct.unpack('1024h', audio_data))\n # --声音足够大, 发送这条微博\n if k > 8000:\n is_send_flag = True\n break\n # --时间到了还没有足够大的声音, 不发这条微博\n if (time.time() - start_t) > 30:\n break\n # 发送微博\n if is_send_flag:\n self.logging('大吼成功! 准备开始发送该条微博~')\n if self.sendWeibo(text, pictures):\n self.logging('微博发送成功!')\n '''发微博'''\n def sendWeibo(self, text, pictures):\n # 上传图片\n pic_id = []\n url = 'https://picupload.weibo.com/interface/pic_upload.php'\n params = {\n 'data': '1',\n 'p': '1',\n 'url': 'weibo.com/u/%s' % self.uid,\n 'markpos': '1',\n 'logo': '1',\n 'nick': '@%s' % self.nickname,\n 'marks': '1',\n 'app': 'miniblog',\n 's': 'json',\n 'pri': 'null',\n 'file_source': '1'\n }\n for picture in pictures:\n res = self.session.post(url, headers=self.headers, params=params, data=picture)\n res_json = res.json()\n if res_json['code'] == 'A00006':\n pid = res_json['data']['pics']['pic_1']['pid']\n pic_id.append(pid)\n time.sleep(random.random()+0.5)\n # 发微博\n url = 'https://www.weibo.com/aj/mblog/add?ajwvr=6&__rnd=%d' % int(time.time() * 1000)\n data = {\n 'title': '',\n 'location': 'v6_content_home',\n 'text': text,\n 'appkey': '',\n 'style_type': '1',\n 'pic_id': '|'.join(pic_id),\n 'tid': '',\n 'pdetail': '',\n 'mid': '',\n 'isReEdit': 'false',\n 'gif_ids': '',\n 'rank': '0',\n 'rankid': '',\n 'pub_source': 'page_2',\n 'topic_id': '',\n 'updata_img_num': str(len(pictures)),\n 'pub_type': 'dialog'\n }\n headers = self.headers.copy()\n headers.update({'Referer': 'http://www.weibo.com/u/%s/home?wvr=5' % self.uid})\n res = self.session.post(url, headers=headers, data=data)\n is_success = False\n if res.status_code == 200:\n is_success = True\n return is_success\n '''待发送微博内容解析'''\n def parseWeibo(self, weibodir):\n text = open(os.path.join(weibodir, 'weibo.md'), 'r', encoding='utf-8').read()\n pictures = []\n for filename in sorted(os.listdir(os.path.join(weibodir, 'pictures'))):\n if filename.split('.')[-1].lower() in ['jpg', 'png']:\n pictures.append(open(os.path.join(weibodir, 'pictures', filename), 'rb').read())\n if len(pictures) > 9:\n self.logging('一条微博最多只能有9张配图, 程序现在将自动剔除多出的图片', 'Warning')\n pictures = pictures[:9]\n return text, pictures\n '''模拟登录'''\n def login(self, username, password):\n client = login.Client()\n weibo = client.weibo(reload_history=True)\n infos_return, session = weibo.login(username, password, 'mobile')\n return infos_return.get('nick'), infos_return.get('uid'), session\n '''logging'''\n def logging(self, msg, tip='INFO'):\n print(f'[{time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())} {tip}]: {msg}')","repo_name":"CharlesPikachu/DecryptLogin","sub_path":"examples/DecryptLoginExamples/crawlers/weibosender/weibosender.py","file_name":"weibosender.py","file_ext":"py","file_size_in_byte":5227,"program_lang":"python","lang":"en","doc_type":"code","stars":2738,"dataset":"github-code","pt":"77"}
+{"seq_id":"72046012088","text":"def sign(x):\n if x > 0:\n return 'positive'\n elif x < 0:\n return 'negative'\n else:\n return 'zero'\n\n\nfor x in [-1, 0, 1]:\n print(sign(x))\n# Prints \"negative\", \"zero\", \"positive\"\n\n\"\"\"\nOutput\nnegative\nzero\npositive\n\"\"\"\n","repo_name":"vamsi/python-programming-modern-approach","sub_path":"code/15_intro_scientific_python/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"77"}
+{"seq_id":"70392830968","text":"from collections import defaultdict\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tkinter as tk\nfrom tkinter import messagebox\nimport random\n\nclass GrafoPonderado:\n def __init__(self):\n self.lista_adj = {}\n self.num_nos = 0\n self.num_arestas = 0\n self.grafo = nx.Graph()\n\n def adicionar_no(self, node):\n if node in self.lista_adj:\n print(f\"AVISO: No {node} já existe\")\n return\n self.lista_adj[node] = {}\n self.num_nos += 1\n\n def adicionar_aresta(self, no1, no2, peso):\n if no1 not in self.lista_adj:\n self.adicionar_no(no1)\n if no2 not in self.lista_adj:\n self.adicionar_no(no2)\n\n self.lista_adj[no1][no2] = peso\n self.lista_adj[no2][no1] = peso\n self.num_arestas += 1\n\n def adicionar_nos(self, nos):\n for no in nos:\n self.adicionar_no(no)\n\n def adicionar_aresta_bidimensional(self, no1, no2, peso):\n self.adicionar_aresta(no1, no2, peso)\n self.adicionar_aresta(no2, no1, peso)\n\n def remove_aresta(self, no1, no2):\n try:\n peso = self.lista_adj[no1].pop(no2)\n self.lista_adj[no2].pop(no1)\n self.num_arestas -= 1\n print(f\"Removida a aresta {no1} -> {no2} com peso {peso}\")\n except KeyError:\n print(f\"WARN: Aresta {no1} -> {no2} não existe\")\n\n def remove_no(self, no):\n if no in self.lista_adj:\n for no2 in self.lista_adj[no]:\n self.lista_adj[no2].pop(no)\n self.num_arestas -= 1\n self.num_arestas -= len(self.lista_adj[no])\n self.num_nos -= 1\n self.lista_adj.pop(no)\n print(f\"Removido o nó {no}\")\n else:\n print(f\"WARN: Nó {no} não existe\")\n\n def __str__(self):\n saida = \"\"\n for no in self.lista_adj:\n saida += str(no) + \" -> \" + str(self.lista_adj[no]) + \"\\n\"\n return saida\n\n def ler_arquivo(self, nome_arquivo):\n file = open(nome_arquivo, 'r', encoding='utf-8')\n i = 0\n for linha in file:\n i += 1\n if i == 1:\n continue\n #print(f\"Linha lida: {linha}\") \n conteudo = linha.strip().split(\"\\t\")\n u = conteudo[0]\n v = conteudo[1]\n w = conteudo[2]\n self.adicionar_aresta(u, v, w)\n file.close()\n \n def grafo_resultado_votos_iguais(self, data):\n votos_iguais = defaultdict(int)\n num_nos = set()\n num_arestas = 0\n grafo = GrafoPonderado()\n\n for i, linha1 in enumerate(data):\n id_votacao1 = linha1[0]\n voto1 = linha1[3]\n deputado1 = linha1[6]\n num_nos.add(deputado1)\n \n for j in range(i + 1, len(data)):\n linha2 = data[j]\n id_votacao2 = linha2[0]\n voto2 = linha2[3]\n deputado2 = linha2[6]\n num_nos.add(deputado2)\n \n if id_votacao1 == id_votacao2 and voto1 == voto2:\n if (deputado1, deputado2) not in votos_iguais:\n num_arestas += 1\n votos_iguais[(deputado1, deputado2)] += 1\n #salvando\n nome_arquivo = 'resultados_votos_iguais.txt'\n\n with open(nome_arquivo, 'w') as arquivo:\n arquivo.write(f\" {len(num_nos)}\")\n arquivo.write(f\" {num_arestas}\\n\")\n for (deputado1, deputado2), contagem in votos_iguais.items():\n arquivo.write(f\"{deputado1} {deputado2} {contagem}\\n\")\n\n\n def calculate_normalized_weight(valor, votes):\n return valor / int(votes) \n\n def criar_grafo_votacoes_iguais(ano, partido, grafo_saida_txt, threshold, png_output_filename, heatmap_output_filename, grafo_output_filename):\n nome_arquivo1 = f\"graph{ano}.txt\"\n nome_arquivo2 = f\"politicians{ano}.txt\"\n threshold = float(threshold)\n\n \n with open(nome_arquivo1, \"r\", encoding=\"utf-8\") as f1:\n data1 = f1.readlines()\n\n with open(nome_arquivo2, \"r\", encoding=\"utf-8\") as f2:\n data2 = f2.readlines()\n\n grafo = nx.Graph()\n min_votes = 0\n\n with open(nome_arquivo2, \"r\", encoding=\"utf-8\") as arquivo_politicos:\n for linha in arquivo_politicos:\n nome_politico, partido_politico, _ = linha.strip(\"[]\\n\").split(\";\")\n if not partido or partido_politico in partido:\n grafo.add_node(nome_politico, partido=partido_politico, votacoes=0)\n\n with open(nome_arquivo1, \"r\", encoding=\"utf-8\") as arquivo_grafo:\n for linha in arquivo_grafo:\n deputado1, deputado2, votacao = linha.strip(\"[]\\n\").split(\";\")\n votacao = int(votacao)\n if grafo.has_node(deputado1) and grafo.has_node(deputado2) and votacao > 0:\n grafo.nodes[deputado1]['votacoes'] += 1\n grafo.nodes[deputado2]['votacoes'] += 1\n grafo.add_edge(deputado1, deputado2, votacao=votacao)\n \n \n normalized_weights = {}\n grafo_novo = nx.Graph()\n \n for node1, node2, data in grafo.edges(data=True):\n partido_node1 = grafo.nodes[node1]['partido']\n partido_node2 = grafo.nodes[node2]['partido']\n \n for index, linha in enumerate(data2):\n nome, partido, votacao = linha.strip().split(\";\")\n if (nome == node1 and partido == partido_node1) or (nome == node2 and partido == partido_node2):\n votacao = int(votacao)\n while index + 1 < len(data2):\n proxima_linha = data2[index + 1]\n proximo_nome, proximo_partido, proxima_votacao = proxima_linha.strip().split(\";\")\n proxima_votacao = int(proxima_votacao)\n if (proximo_nome == node1 and proximo_partido == partido_node1) or (proximo_nome == node2 and proximo_partido == partido_node2):\n if votacao <= proxima_votacao:\n votacao = votacao\n else:\n votacao = proxima_votacao\n index += 1\n \n min_votes = votacao\n votacao = data['votacao']\n normalized_weight = GrafoPonderado.calculate_normalized_weight(votacao, min_votes)\n if normalized_weight >= threshold:\n #inversao = 1 - normalized_weight\n normalized_weights[(node1, node2)] = normalized_weight\n grafo_novo.add_edge(node1, node2, weight=normalized_weight)\n \n \n \n with open(grafo_saida_txt, \"w\", encoding=\"utf-8\") as arquivo_saida: \n for (dep1, dep2), weight in normalized_weights.items():\n arquivo_saida.write(f\"{dep1};{dep2} {weight:.3f}\\n\")\n\n #GRAFO BETWEENNESS \n betweenness_scores = nx.betweenness_centrality(grafo_novo)\n sorted_nodes = sorted(betweenness_scores, key=lambda x: betweenness_scores[x])\n deputados = sorted_nodes\n scores = [betweenness_scores[node] for node in sorted_nodes]\n plt.figure(figsize=(20, 10))\n plt.bar(deputados, scores)\n plt.xlabel('Deputados')\n plt.ylabel('Betweenness')\n plt.title('Medida de Centralidade - Betweenness')\n plt.xticks(rotation=45, ha='right', fontsize=5)\n plt.tight_layout()\n plt.gcf().subplots_adjust(bottom=0.20)\n plt.savefig(png_output_filename)\n plt.show()\n \n #HEATMAP\n adjacency_matrix = nx.to_numpy_array(grafo_novo, weight='weight') \n correlation_matrix = np.corrcoef(adjacency_matrix) \n plt.figure(figsize=(20, 10)) \n plt.imshow(correlation_matrix, cmap='hot', interpolation='nearest')\n plt.colorbar()\n plt.title('Heatmap - Correlação entre Deputados')\n plt.xticks(range(len(deputados)), deputados, rotation=45, ha='right', fontsize=5)\n plt.yticks(range(len(deputados)), deputados[::-1], fontsize=5) \n plt.subplots_adjust(left=0.25, right=0.95, top=0.95, bottom=0.2) \n plt.tight_layout() \n plt.savefig(heatmap_output_filename)\n plt.show()\n\n #GRAFO \n central_node = max(betweenness_scores, key=betweenness_scores.get) \n plt.figure(figsize=(10, 6)) \n pos = nx.spring_layout(grafo_novo)\n nx.draw_networkx(grafo_novo, pos, with_labels=True, font_size=5, node_size=100) \n\n # Criando um dicionário de cores para partidos\n unique_parties = list(set(nx.get_node_attributes(grafo_novo, 'partido').values()))\n color_map = {party: f'#{random.randint(0, 0xFFFFFF):06x}' for party in unique_parties}\n \n node_colors = [color_map.get(grafo_novo.nodes[node].get('partido', 'default'), '#FFFFFF') for node in grafo_novo.nodes]\n labels = {}\n for node in grafo_novo.nodes:\n partido = grafo_novo.nodes[node].get('partido')\n if partido:\n labels[node] = f\"{node}\\n({partido})\"\n else:\n labels[node] = node\n \n nx.draw_networkx(grafo_novo, pos, with_labels=False, font_size=5, node_size=100, node_color=node_colors)\n nx.draw_networkx_nodes(grafo_novo, pos, nodelist=[central_node], node_color='red', node_size=150)\n nx.draw_networkx_labels(grafo_novo, pos, labels=labels, font_size=5)\n \n # Adicionando o central_node à legenda de partidos\n central_party = grafo_novo.nodes[central_node].get('partido', 'Desconhecido')\n handles = [plt.Line2D([], [], marker='o', color='w', markerfacecolor=color, markersize=10, label=f\"{party} ({party if party != central_party else 'Central'})\") for party, color in color_map.items()]\n \n # Adicionando uma entrada na legenda para o central_node\n handles.append(plt.Line2D([], [], marker='o', color='w', markerfacecolor='red', markersize=10, label=f\"Central ({central_party})\"))\n \n plt.legend(handles=handles, title='Partidos', loc='upper left')\n \n plt.title(f'Grafo de Relações de Votos entre Deputados com Ponto Central Marcado')\n plt.tight_layout() \n plt.savefig(grafo_output_filename)\n plt.show()\n\n #Depois vou fazer a inversao de pesos separado \n # def grafo_inversao_de_pesos(ano, partido, grafo_saida_txt, threshold):\n # nome_arquivo1 = f\"graph{ano}.txt\"\n # nome_arquivo2 = f\"politicians{ano}.txt\"\n # threshold = float(threshold)\n\n # # Lê os dados dos arquivos e os transforma em listas\n # with open(nome_arquivo1, \"r\", encoding=\"utf-8\") as f1:\n # data1 = f1.readlines()\n\n # with open(nome_arquivo2, \"r\", encoding=\"utf-8\") as f2:\n # data2 = f2.readlines()\n\n # grafo = nx.Graph()\n # min_votos = 0\n\n # with open(nome_arquivo2, \"r\", encoding=\"utf-8\") as arquivo_politicos:\n # for linha in arquivo_politicos:\n # nome_politico, partido_politico, _ = linha.strip(\"[]\\n\").split(\";\")\n # if not partido or partido_politico in partido:\n # grafo.add_node(nome_politico, partido=partido_politico, votacoes=0)\n\n # with open(nome_arquivo1, \"r\", encoding=\"utf-8\") as arquivo_grafo:\n # for linha in arquivo_grafo:\n # deputado1, deputado2, votacao = linha.strip(\"[]\\n\").split(\";\")\n # votacao = int(votacao)\n # if grafo.has_node(deputado1) and grafo.has_node(deputado2) and votacao > 0:\n # grafo.nodes[deputado1]['votacoes'] += 1\n # grafo.nodes[deputado2]['votacoes'] += 1\n # grafo.add_edge(deputado1, deputado2, votacao=votacao)\n \n \n # normalizacao = {}\n \n \n # for node1, node2, data in grafo.edges(data=True):\n # partido_node1 = grafo.nodes[node1]['partido']\n # partido_node2 = grafo.nodes[node2]['partido']\n \n # for index, linha in enumerate(data2):\n # nome, partido, votacao = linha.strip().split(\";\")\n # if (nome == node1 and partido == partido_node1) or (nome == node2 and partido == partido_node2):\n # votacao = int(votacao)\n # while index + 1 < len(data2):\n # proxima_linha = data2[index + 1]\n # proximo_nome, proximo_partido, proxima_votacao = proxima_linha.strip().split(\";\")\n # proxima_votacao = int(proxima_votacao)\n # if (proximo_nome == node1 and proximo_partido == partido_node1) or (proximo_nome == node2 and proximo_partido == partido_node2):\n # if votacao <= proxima_votacao:\n # votacao = votacao\n # else:\n # votacao = proxima_votacao\n # index += 1\n \n # min_votos = votacao\n # votacao = data['votacao']\n # normalizacao = GrafoPonderado.calculate_normalized_weight(votacao, min_votos)\n # if normalizacao >= threshold:\n # inversao = 1 - normalizacao\n # normalizacao[(node1, node2)] = inversao\n \n \n # with open(grafo_saida_txt, \"w\", encoding=\"utf-8\") as arquivo_saida: \n # for (dep1, dep2), weight in normalized_weights.items():\n # arquivo_saida.write(f\"{dep1};{dep2} {weight:.3f}\\n\")\n\n ############################### INTERFACE GRÁFICA ########################################## \n\nanos = list(range(2002, 2024))\n\ndef processar_entrada():\n ano = int(entrada_ano.get())\n threshold = float(entrada_threshold.get())\n partido = entrada_partido.get().split(\", \")\n\n if not partido[0].strip():\n partido = []\n\n if ano not in anos:\n messagebox.showerror(\"Erro\", \"Ano inválido. Escolha um ano entre 2002 e 2023.\")\n else:\n resultado.config(text=\"Processando...\\n\")\n grafo_resultado_filtros = f\"grafo_votacoes_normalizado{ano}.txt\"\n grafico_centralidade = f\"grafico_centralidade_{ano}.png\"\n heatmap = f\"heatmap_{ano}.png\"\n grafo = f\"grafo_{ano}.png\"\n GrafoPonderado.criar_grafo_votacoes_iguais(ano, partido, grafo_resultado_filtros, threshold, grafico_centralidade, heatmap, grafo)\n resultado.config(text=f\"Grafo de votações normalizado salvo em {grafo_resultado_filtros}. Salvos em arquivo txt também.\\n\"\n f\"Os plots foram salvos nos arquivos:\\n{grafico_centralidade}\\n{heatmap}\\n{grafo}\\n\\n\")\n\n# Configuração da interface gráfica\nroot = tk.Tk()\nroot.title(\"Análise de Votações\")\n\nentrada_ano_label = tk.Label(root, text=\"Informe o ano a considerar:\")\nentrada_ano = tk.Entry(root)\nentrada_threshold_label = tk.Label(root, text=\"Informe o percentual mínimo de concordância (threshold) (ex: 0.9):\")\nentrada_threshold = tk.Entry(root)\nentrada_partido_label = tk.Label(root, text=\"Informe os partidos a analisar, separados por , (ex: PT, PMDB, PL):\")\nentrada_partido = tk.Entry(root)\n\nprocessar_botao = tk.Button(root, text=\"Processar\", command=processar_entrada)\nresultado = tk.Label(root, text=\"\")\n\n# Posicionamento dos widgets\nentrada_ano_label.pack()\nentrada_ano.pack()\nentrada_threshold_label.pack()\nentrada_threshold.pack()\nentrada_partido_label.pack()\nentrada_partido.pack()\nprocessar_botao.pack()\nresultado.pack()\n\nroot.mainloop()\n\n","repo_name":"Ivynaaa/02","sub_path":"grafoponderado.py","file_name":"grafoponderado.py","file_ext":"py","file_size_in_byte":15958,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"30279311777","text":"# coding: utf-8\r\nimport math\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.utils\r\nimport torch.utils.data\r\nfrom torch.autograd import Variable\r\nfrom torch.nn.parameter import Parameter\r\nimport torch.nn.functional as F\r\nfrom torch_scatter import scatter_mean, scatter_max, scatter_add\r\nfrom torch_geometric.utils import remove_self_loops, add_self_loops\r\nimport torch_scatter\r\nimport inspect\r\n\r\n\r\n# Variational Graph Recurrent Networks. For more information, please refer to https://arxiv.org/abs/1908.09710\r\n# We modify and simplify the code of VGRNN from https://github.com/VGraphRNN/VGRNN, and include this method in our graph embedding project framework.\r\n# Author: jhljx\r\n# Email: jhljx8918@gmail.com\r\n\r\n\r\n# utility functions\r\ndef uniform(size, tensor):\r\n stdv = 1.0 / math.sqrt(size)\r\n if tensor is not None:\r\n tensor.data.uniform_(-stdv, stdv)\r\n\r\n\r\ndef glorot(tensor):\r\n stdv = math.sqrt(6.0 / (tensor.size(0) + tensor.size(1)))\r\n if tensor is not None:\r\n tensor.data.uniform_(-stdv, stdv)\r\n\r\n\r\ndef zeros(tensor):\r\n if tensor is not None:\r\n tensor.data.fill_(0)\r\n\r\n\r\ndef reset(nn):\r\n def _reset(item):\r\n if hasattr(item, 'reset_parameters'):\r\n item.reset_parameters()\r\n\r\n if nn is not None:\r\n if hasattr(nn, 'children') and len(list(nn.children())) > 0:\r\n for item in nn.children():\r\n _reset(item)\r\n else:\r\n _reset(nn)\r\n\r\n\r\ndef scatter_(name, src, index, dim_size=None):\r\n r\"\"\"Aggregates all values from the :attr:`src` tensor at the indices\r\n specified in the :attr:`index` tensor along the first dimension.\r\n If multiple indices reference the same location, their contributions\r\n are aggregated according to :attr:`name` (either :obj:`\"add\"`,\r\n :obj:`\"mean\"` or :obj:`\"max\"`).\r\n Args:\r\n name (string): The aggregation to use (:obj:`\"add\"`, :obj:`\"mean\"`,\r\n :obj:`\"max\"`).\r\n src (Tensor): The source tensor.\r\n index (LongTensor): The indices of elements to scatter.\r\n dim_size (int, optional): Automatically create output tensor with size\r\n :attr:`dim_size` in the first dimension. If set to :attr:`None`, a\r\n minimal sized output tensor is returned. (default: :obj:`None`)\r\n :rtype: :class:`Tensor`\r\n \"\"\"\r\n\r\n assert name in ['add', 'mean', 'max']\r\n\r\n op = getattr(torch_scatter, 'scatter_{}'.format(name))\r\n fill_value = -1e38 if name is 'max' else 0\r\n out = op(src, index, 0, None, dim_size)\r\n if isinstance(out, tuple):\r\n out = out[0]\r\n\r\n if name is 'max':\r\n out[out == fill_value] = 0\r\n\r\n return out\r\n\r\n\r\nclass MessagePassing(torch.nn.Module):\r\n r\"\"\"Base class for creating message passing layers\r\n .. math::\r\n \\mathbf{x}_i^{\\prime} = \\gamma_{\\mathbf{\\Theta}} \\left( \\mathbf{x}_i,\r\n \\square_{j \\in \\mathcal{N}(i)} \\, \\phi_{\\mathbf{\\Theta}}\r\n \\left(\\mathbf{x}_i, \\mathbf{x}_j,\\mathbf{e}_{i,j}\\right) \\right),\r\n where :math:`\\square` denotes a differentiable, permutation invariant\r\n function, *e.g.*, sum, mean or max, and :math:`\\gamma_{\\mathbf{\\Theta}}`\r\n and :math:`\\phi_{\\mathbf{\\Theta}}` denote differentiable functions such as\r\n MLPs.\r\n See `here `__ for the accompanying tutorial.\r\n \"\"\"\r\n\r\n def __init__(self, aggr='add'):\r\n super(MessagePassing, self).__init__()\r\n\r\n self.message_args = inspect.getfullargspec(self.message)[0][1:]\r\n self.update_args = inspect.getfullargspec(self.update)[0][2:]\r\n\r\n def propagate(self, aggr, edge_index, **kwargs):\r\n r\"\"\"The initial call to start propagating messages.\r\n Takes in an aggregation scheme (:obj:`\"add\"`, :obj:`\"mean\"` or\r\n :obj:`\"max\"`), the edge indices, and all additional data which is\r\n needed to construct messages and to update node embeddings.\"\"\"\r\n\r\n assert aggr in ['add', 'mean', 'max']\r\n kwargs['edge_index'] = edge_index\r\n\r\n size = None\r\n message_args = []\r\n for arg in self.message_args:\r\n if arg[-2:] == '_i':\r\n tmp = kwargs[arg[:-2]]\r\n size = tmp.size(0)\r\n message_args.append(tmp[edge_index[0]])\r\n elif arg[-2:] == '_j':\r\n tmp = kwargs[arg[:-2]]\r\n size = tmp.size(0)\r\n message_args.append(tmp[edge_index[1]])\r\n else:\r\n message_args.append(kwargs[arg])\r\n\r\n update_args = [kwargs[arg] for arg in self.update_args]\r\n\r\n out = self.message(*message_args)\r\n out = scatter_(aggr, out, edge_index[0], dim_size=size)\r\n out = self.update(out, *update_args)\r\n\r\n return out\r\n\r\n def message(self, x_j): # pragma: no cover\r\n r\"\"\"Constructs messages in analogy to :math:`\\phi_{\\mathbf{\\Theta}}`\r\n for each edge in :math:`(i,j) \\in \\mathcal{E}`.\r\n Can take any argument which was initially passed to :meth:`propagate`.\r\n In addition, features can be lifted to the source node :math:`i` and\r\n target node :math:`j` by appending :obj:`_i` or :obj:`_j` to the\r\n variable name, *.e.g.* :obj:`x_i` and :obj:`x_j`.\"\"\"\r\n\r\n return x_j\r\n\r\n def update(self, aggr_out): # pragma: no cover\r\n r\"\"\"Updates node embeddings in analogy to\r\n :math:`\\gamma_{\\mathbf{\\Theta}}` for each node\r\n :math:`i \\in \\mathcal{V}`.\r\n Takes in the output of aggregation as first argument and any argument\r\n which was initially passed to :meth:`propagate`.\"\"\"\r\n\r\n return aggr_out\r\n\r\n\r\n# layers\r\n\r\nclass GCNConv(MessagePassing):\r\n def __init__(self, in_channels, out_channels, act=F.relu, improved=True, bias=False):\r\n super(GCNConv, self).__init__()\r\n\r\n self.in_channels = in_channels\r\n self.out_channels = out_channels\r\n self.improved = improved\r\n self.act = act\r\n\r\n self.weight = Parameter(torch.Tensor(in_channels, out_channels))\r\n\r\n if bias:\r\n self.bias = Parameter(torch.Tensor(out_channels))\r\n else:\r\n self.register_parameter('bias', None)\r\n\r\n self.reset_parameters()\r\n\r\n def reset_parameters(self):\r\n glorot(self.weight)\r\n zeros(self.bias)\r\n\r\n def forward(self, x, edge_index, edge_weight=None):\r\n if edge_weight is None:\r\n edge_weight = torch.ones((edge_index.size(1),), dtype=x.dtype, device=x.device)\r\n edge_weight = edge_weight.view(-1)\r\n assert edge_weight.size(0) == edge_index.size(1)\r\n edge_index, _ = add_self_loops(edge_index, num_nodes=x.size(0))\r\n loop_weight = torch.full((x.size(0),), 1 if not self.improved else 2, dtype=x.dtype, device=x.device)\r\n edge_weight = torch.cat([edge_weight, loop_weight], dim=0)\r\n row, col = edge_index\r\n deg = scatter_add(edge_weight, row, dim=0, dim_size=x.size(0))\r\n deg_inv = deg.pow(-0.5)\r\n deg_inv[deg_inv == float('inf')] = 0\r\n\r\n norm = deg_inv[row] * edge_weight * deg_inv[col]\r\n x = torch.matmul(x, self.weight)\r\n out = self.propagate('add', edge_index, x=x, norm=norm)\r\n return self.act(out)\r\n\r\n def message(self, x_j, norm):\r\n return norm.view(-1, 1) * x_j\r\n\r\n def update(self, aggr_out):\r\n if self.bias is not None:\r\n aggr_out = aggr_out + self.bias\r\n return aggr_out\r\n\r\n def __repr__(self):\r\n return '{}({}, {})'.format(self.__class__.__name__, self.in_channels, self.out_channels)\r\n\r\n\r\nclass SAGEConv(torch.nn.Module):\r\n def __init__(self, in_channels, out_channels, pool='mean', act=F.relu, normalize=False, bias=False):\r\n super(SAGEConv, self).__init__()\r\n\r\n self.in_channels = in_channels\r\n self.out_channels = out_channels\r\n self.normalize = normalize\r\n self.weight = Parameter(torch.Tensor(self.in_channels, out_channels))\r\n self.act = act\r\n self.pool = pool\r\n\r\n if bias:\r\n self.bias = Parameter(torch.Tensor(out_channels))\r\n else:\r\n self.register_parameter('bias', None)\r\n\r\n self.reset_parameters()\r\n\r\n def reset_parameters(self):\r\n size = self.weight.size(0)\r\n uniform(size, self.weight)\r\n uniform(size, self.bias)\r\n\r\n def forward(self, x, edge_index):\r\n edge_index, _ = remove_self_loops(edge_index)\r\n edge_index = add_self_loops(edge_index, num_nodes=x.size(0))\r\n\r\n x = x.unsqueeze(-1) if x.dim() == 1 else x\r\n row, col = edge_index\r\n\r\n if self.pool == 'mean':\r\n out = torch.matmul(x, self.weight)\r\n if self.bias is not None:\r\n out = out + self.bias\r\n out = self.act(out)\r\n out = scatter_mean(out[col], row, dim=0, dim_size=out.size(0))\r\n\r\n elif self.pool == 'max':\r\n out = torch.matmul(x, self.weight)\r\n if self.bias is not None:\r\n out = out + self.bias\r\n out = self.act(out)\r\n out, _ = scatter_max(out[col], row, dim=0, dim_size=out.size(0))\r\n\r\n elif self.pool == 'add':\r\n out = torch.matmul(x, self.weight)\r\n if self.bias is not None:\r\n out = out + self.bias\r\n out = self.act(out)\r\n out = scatter_add(x[col], row, dim=0, dim_size=x.size(0))\r\n else:\r\n print('pooling not defined!')\r\n\r\n if self.normalize:\r\n out = F.normalize(out, p=2, dim=-1)\r\n\r\n return out\r\n\r\n def __repr__(self):\r\n return '{}({}, {})'.format(self.__class__.__name__, self.in_channels, self.out_channels)\r\n\r\n\r\nclass GINConv(torch.nn.Module):\r\n def __init__(self, nn, eps=0, train_eps=False):\r\n super(GINConv, self).__init__()\r\n self.nn = nn\r\n self.initial_eps = eps\r\n if train_eps:\r\n self.eps = torch.nn.Parameter(torch.Tensor([eps]))\r\n else:\r\n self.register_buffer('eps', torch.Tensor([eps]))\r\n self.reset_parameters()\r\n\r\n def reset_parameters(self):\r\n reset(self.nn)\r\n self.eps.data.fill_(self.initial_eps)\r\n\r\n def forward(self, x, edge_index):\r\n x = x.unsqueeze(-1) if x.dim() == 1 else x\r\n edge_index, _ = remove_self_loops(edge_index)\r\n row, col = edge_index\r\n\r\n out = scatter_add(x[col], row, dim=0, dim_size=x.size(0))\r\n out = (1 + self.eps) * x + out\r\n out = self.nn(out)\r\n return out\r\n\r\n def __repr__(self):\r\n return '{}(nn={})'.format(self.__class__.__name__, self.nn)\r\n\r\n\r\nclass graph_gru_sage(nn.Module):\r\n def __init__(self, input_size, hidden_size, n_layer, bias=True):\r\n super(graph_gru_sage, self).__init__()\r\n\r\n self.hidden_size = hidden_size\r\n self.n_layer = n_layer\r\n\r\n # gru weights\r\n self.weight_xz = nn.ModuleList()\r\n self.weight_hz = nn.ModuleList()\r\n self.weight_xr = nn.ModuleList()\r\n self.weight_hr = nn.ModuleList()\r\n self.weight_xh = nn.ModuleList()\r\n self.weight_hh = nn.ModuleList()\r\n\r\n for i in range(self.n_layer):\r\n if i == 0:\r\n self.weight_xz.append(SAGEConv(input_size, hidden_size, act=lambda x: x, bias=bias))\r\n self.weight_hz.append(SAGEConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))\r\n self.weight_xr.append(SAGEConv(input_size, hidden_size, act=lambda x: x, bias=bias))\r\n self.weight_hr.append(SAGEConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))\r\n self.weight_xh.append(SAGEConv(input_size, hidden_size, act=lambda x: x, bias=bias))\r\n self.weight_hh.append(SAGEConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))\r\n else:\r\n self.weight_xz.append(SAGEConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))\r\n self.weight_hz.append(SAGEConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))\r\n self.weight_xr.append(SAGEConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))\r\n self.weight_hr.append(SAGEConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))\r\n self.weight_xh.append(SAGEConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))\r\n self.weight_hh.append(SAGEConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))\r\n\r\n def forward(self, inp, edgidx, h):\r\n h_out = torch.zeros(h.size(), device=h.device)\r\n for i in range(self.n_layer):\r\n if i == 0:\r\n z_g = torch.sigmoid(self.weight_xz[i](inp, edgidx) + self.weight_hz[i](h[i], edgidx))\r\n r_g = torch.sigmoid(self.weight_xr[i](inp, edgidx) + self.weight_hr[i](h[i], edgidx))\r\n h_tilde_g = torch.tanh(self.weight_xh[i](inp, edgidx) + self.weight_hh[i](r_g * h[i], edgidx))\r\n h_out[i] = z_g * h[i] + (1 - z_g) * h_tilde_g\r\n # out = self.decoder(h_t.view(1,-1))\r\n else:\r\n z_g = torch.sigmoid(self.weight_xz[i](h_out[i - 1], edgidx) + self.weight_hz[i](h[i], edgidx))\r\n r_g = torch.sigmoid(self.weight_xr[i](h_out[i - 1], edgidx) + self.weight_hr[i](h[i], edgidx))\r\n h_tilde_g = torch.tanh(self.weight_xh[i](h_out[i - 1], edgidx) + self.weight_hh[i](r_g * h[i], edgidx))\r\n h_out[i] = z_g * h[i] + (1 - z_g) * h_tilde_g\r\n out = h_out\r\n return out, h_out\r\n\r\n\r\nclass graph_gru_gcn(nn.Module):\r\n def __init__(self, input_size, hidden_size, n_layer, bias=True):\r\n super(graph_gru_gcn, self).__init__()\r\n\r\n self.hidden_size = hidden_size\r\n self.n_layer = n_layer\r\n\r\n # gru weights\r\n self.weight_xz = nn.ModuleList()\r\n self.weight_hz = nn.ModuleList()\r\n self.weight_xr = nn.ModuleList()\r\n self.weight_hr = nn.ModuleList()\r\n self.weight_xh = nn.ModuleList()\r\n self.weight_hh = nn.ModuleList()\r\n\r\n for i in range(self.n_layer):\r\n if i == 0:\r\n self.weight_xz.append(GCNConv(input_size, hidden_size, act=lambda x: x, bias=bias))\r\n self.weight_hz.append(GCNConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))\r\n self.weight_xr.append(GCNConv(input_size, hidden_size, act=lambda x: x, bias=bias))\r\n self.weight_hr.append(GCNConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))\r\n self.weight_xh.append(GCNConv(input_size, hidden_size, act=lambda x: x, bias=bias))\r\n self.weight_hh.append(GCNConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))\r\n else:\r\n self.weight_xz.append(GCNConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))\r\n self.weight_hz.append(GCNConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))\r\n self.weight_xr.append(GCNConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))\r\n self.weight_hr.append(GCNConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))\r\n self.weight_xh.append(GCNConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))\r\n self.weight_hh.append(GCNConv(hidden_size, hidden_size, act=lambda x: x, bias=bias))\r\n\r\n def forward(self, inp, edgidx, h):\r\n h_out = torch.zeros(h.size(), device=h.device)\r\n for i in range(self.n_layer):\r\n if i == 0:\r\n z_g = torch.sigmoid(self.weight_xz[i](inp, edgidx) + self.weight_hz[i](h[i], edgidx))\r\n r_g = torch.sigmoid(self.weight_xr[i](inp, edgidx) + self.weight_hr[i](h[i], edgidx))\r\n h_tilde_g = torch.tanh(self.weight_xh[i](inp, edgidx) + self.weight_hh[i](r_g * h[i], edgidx))\r\n h_out[i] = z_g * h[i] + (1 - z_g) * h_tilde_g\r\n # out = self.decoder(h_t.view(1,-1))\r\n else:\r\n z_g = torch.sigmoid(self.weight_xz[i](h_out[i - 1], edgidx) + self.weight_hz[i](h[i], edgidx))\r\n r_g = torch.sigmoid(self.weight_xr[i](h_out[i - 1], edgidx) + self.weight_hr[i](h[i], edgidx))\r\n h_tilde_g = torch.tanh(self.weight_xh[i](h_out[i - 1], edgidx) + self.weight_hh[i](r_g * h[i], edgidx))\r\n h_out[i] = z_g * h[i] + (1 - z_g) * h_tilde_g\r\n # out = self.decoder(h_t.view(1,-1))\r\n\r\n out = h_out\r\n return out, h_out\r\n\r\n\r\n# Inner product decoder(Only apply for small graphs and can not be apply into large scale graphs)\r\n# This decoder is memory-consuming!\r\nclass InnerProductDecoder(nn.Module):\r\n def __init__(self, act=torch.sigmoid, dropout=0.):\r\n super(InnerProductDecoder, self).__init__()\r\n\r\n self.act = act\r\n self.dropout = dropout\r\n\r\n def forward(self, inp):\r\n inp = F.dropout(inp, self.dropout, training=self.training)\r\n x = torch.transpose(inp, dim0=0, dim1=1)\r\n x = torch.mm(inp, x)\r\n return self.act(x)\r\n\r\n\r\n# VGRNN model\r\nclass VGRNN(nn.Module):\r\n input_dim: int\r\n hidden_dim: int\r\n output_dim: int\r\n rnn_layer_num: int\r\n conv_type: str\r\n bias: bool\r\n method_name: str\r\n\r\n def __init__(self, input_dim, hidden_dim, output_dim, rnn_layer_num, conv_type='GCN', bias=True):\r\n super(VGRNN, self).__init__()\r\n\r\n self.input_dim = input_dim\r\n self.hidden_dim = hidden_dim\r\n self.output_dim = output_dim\r\n self.rnn_layer_num = rnn_layer_num\r\n self.conv_type = conv_type\r\n self.bias = bias\r\n self.method_name = 'VGRNN'\r\n\r\n assert conv_type in ['GCN', 'SAGE', 'GIN']\r\n if conv_type == 'GCN':\r\n self.phi_x = nn.Sequential(nn.Linear(input_dim, hidden_dim, bias=bias), nn.ReLU())\r\n self.phi_z = nn.Sequential(nn.Linear(output_dim, hidden_dim, bias=bias), nn.ReLU())\r\n\r\n self.enc = GCNConv(hidden_dim + hidden_dim, hidden_dim, bias=bias)\r\n self.enc_mean = GCNConv(hidden_dim, output_dim, act=lambda x: x, bias=bias)\r\n self.enc_std = GCNConv(hidden_dim, output_dim, act=F.softplus, bias=bias)\r\n\r\n self.prior = nn.Sequential(nn.Linear(hidden_dim, hidden_dim, bias=bias), nn.ReLU())\r\n self.prior_mean = nn.Sequential(nn.Linear(hidden_dim, output_dim, bias=bias))\r\n self.prior_std = nn.Sequential(nn.Linear(hidden_dim, output_dim, bias=bias), nn.Softplus())\r\n\r\n self.rnn = graph_gru_gcn(hidden_dim + hidden_dim, hidden_dim, rnn_layer_num, bias=bias)\r\n\r\n elif conv_type == 'SAGE':\r\n self.phi_x = nn.Sequential(nn.Linear(input_dim, hidden_dim, bias=bias), nn.ReLU())\r\n self.phi_z = nn.Sequential(nn.Linear(output_dim, hidden_dim, bias=bias), nn.ReLU())\r\n\r\n self.enc = SAGEConv(hidden_dim + hidden_dim, hidden_dim, bias=bias)\r\n self.enc_mean = SAGEConv(hidden_dim, output_dim, act=lambda x: x, bias=bias)\r\n self.enc_std = SAGEConv(hidden_dim, output_dim, act=F.softplus, bias=bias)\r\n\r\n self.prior = nn.Sequential(nn.Linear(hidden_dim, hidden_dim, bias=bias), nn.ReLU())\r\n self.prior_mean = nn.Sequential(nn.Linear(hidden_dim, output_dim, bias=bias))\r\n self.prior_std = nn.Sequential(nn.Linear(hidden_dim, output_dim, bias=bias), nn.Softplus())\r\n\r\n self.rnn = graph_gru_sage(hidden_dim + hidden_dim, hidden_dim, rnn_layer_num, bias=bias)\r\n\r\n else: # 'GIN':\r\n self.phi_x = nn.Sequential(nn.Linear(input_dim, hidden_dim, bias=bias), nn.ReLU())\r\n self.phi_z = nn.Sequential(nn.Linear(output_dim, hidden_dim, bias=bias), nn.ReLU())\r\n\r\n self.enc = GINConv(nn.Sequential(nn.Linear(hidden_dim + hidden_dim, hidden_dim, bias=bias), nn.ReLU()))\r\n self.enc_mean = GINConv(nn.Sequential(nn.Linear(hidden_dim, output_dim, bias=bias)))\r\n self.enc_std = GINConv(nn.Sequential(nn.Linear(hidden_dim, output_dim, bias=bias), nn.Softplus()))\r\n\r\n self.prior = nn.Sequential(nn.Linear(hidden_dim, hidden_dim, bias=bias), nn.ReLU())\r\n self.prior_mean = nn.Sequential(nn.Linear(hidden_dim, output_dim, bias=bias))\r\n self.prior_std = nn.Sequential(nn.Linear(hidden_dim, output_dim, bias=bias), nn.Softplus())\r\n\r\n self.rnn = graph_gru_gcn(hidden_dim + hidden_dim, hidden_dim, rnn_layer_num, bias=bias)\r\n\r\n self.dec = InnerProductDecoder(act=lambda x: x)\r\n\r\n def forward(self, x_list, edge_idx_list, hx=None):\r\n assert len(x_list) == len(edge_idx_list) and len(x_list) > 0\r\n timestamp_num = len(x_list)\r\n\r\n if hx is None:\r\n h = Variable(torch.zeros(self.rnn_layer_num, x_list[0].size(1), self.hidden_dim, device=x_list[0].device))\r\n else:\r\n h = Variable(hx)\r\n loss_data_list = [[], [], [], [], []]\r\n\r\n embedding_list = []\r\n for t in range(timestamp_num):\r\n phi_x_t = self.phi_x(x_list[t])\r\n\r\n # encoder\r\n enc_t = self.enc(torch.cat([phi_x_t, h[-1]], 1), edge_idx_list[t])\r\n enc_mean_t = self.enc_mean(enc_t, edge_idx_list[t])\r\n enc_std_t = self.enc_std(enc_t, edge_idx_list[t])\r\n\r\n # prior\r\n prior_t = self.prior(h[-1])\r\n prior_mean_t = self.prior_mean(prior_t)\r\n prior_std_t = self.prior_std(prior_t)\r\n\r\n # sampling and reparameterization\r\n z_t = self._reparameterized_sample(enc_mean_t, enc_std_t)\r\n phi_z_t = self.phi_z(z_t)\r\n # decoder\r\n dec_t = self.dec(z_t)\r\n # recurrence\r\n _, h = self.rnn(torch.cat([phi_x_t, phi_z_t], 1), edge_idx_list[t], h)\r\n # add embedding matrix of each timestamp\r\n embedding_list.append(enc_mean_t)\r\n\r\n # add loss related data for variational autoencoder loss module\r\n loss_data_list[0].append(enc_mean_t)\r\n loss_data_list[1].append(enc_std_t)\r\n loss_data_list[2].append(prior_mean_t)\r\n loss_data_list[3].append(prior_std_t)\r\n loss_data_list[4].append(dec_t)\r\n\r\n return embedding_list, h, loss_data_list\r\n\r\n def reset_parameters(self, stdv=1e-1):\r\n for weight in self.parameters():\r\n weight.data.normal_(0, stdv)\r\n\r\n @staticmethod\r\n def _reparameterized_sample(mean, std):\r\n gaussian = torch.randn(std.size(), device=mean.device)\r\n sample = Variable(gaussian)\r\n return sample.mul(std).add_(mean)\r\n","repo_name":"jhljx/CTGCN","sub_path":"baseline/vgrnn.py","file_name":"vgrnn.py","file_ext":"py","file_size_in_byte":22470,"program_lang":"python","lang":"en","doc_type":"code","stars":81,"dataset":"github-code","pt":"77"}
+{"seq_id":"1777588942","text":"\r\n#nDFT v1.py\r\n#by Marius Johannes Hofmann\r\n#05/2018\r\n#\r\n#based on the thesis of Thomas Blochowicz (PhD thesis, University of Bayreuth, Germany 2003)\r\n#\r\n#please also check the documentation and the examples given therein\r\n#\r\n#The program calculates the Discrete Fourier Transform of nonuniformly spaced data (nDFT) in terms of the\r\n#Nonuniform Discrete Cosine Transform (nDCT) and the\r\n#Nonuniform Discrete Sine Transform (nDST)\r\n#The code is intentionally kept short and simple.\r\n#\r\n#INPUT: requires a two column array (t, f(t)) with the columns separated by tab\r\n# -1st column is termed t and represents the abscissa (x-values, (time, for instance))\r\n# -2nd column is termed f(t) and represents the ordinate (y-values, (voltage, for instance))\r\n#\r\n#OUTPUT: generates two new files with the cosine and the sine transformations g_c(w) and g_s(w)\r\n# in the same folder where the input file is located. those files are named\r\n# -\"filename_DCT.pef\" and\r\n# -\"filename_DST.pef\"\r\n#\r\n#Some comments:\r\n# -The complexity is O(N^2) where N is the number if input points\r\n# -applying the transformations twice, i.e. nDFT^2, nDST^2, yields the original function times Sqrt[2]\r\n# -the two nested for-loops are unfavorable (slow) but computation can be accelerated \r\n# using parallelization (not implemented in this version)\r\n#--------------------------------------------------------------------------------#\r\n#--------------------------------------------------------------------------------#\r\nimport math as m # math package\r\nimport numpy as np # numpy package\r\nimport tkinter.filedialog # provides a dialog in windows for opening an ascii file; may be removed\r\nfrom timeit import default_timer as timer # used for calculation of computing time; may be removed\r\n#--------------------------------------------------------------------------------#\r\n#--------------------------------------------------------------------------------#\r\n#FUNCTION DEFINITION\r\n#nDCT\r\n#w is the sampling vector in Fourier space, t are the x-values and f are the y-values of the input array\r\ndef nDCT(w,t,f):\r\n smp=[]\r\n \r\n for j in range(len(w)): #loops through all sampling points w_i\r\n ft=0 \r\n for i in range(len(f)-1): # Fourier integral \r\n ft+=(\r\n ((f[i+1]-f[i])/(t[i+1]-t[i])*(-2)*m.sin(0.5*w[j]*(t[i+1]+t[i]))*m.sin(0.5*w[j]*(t[i+1]-t[i]))/(w[j]*w[j])) \r\n )\r\n \r\n smp.append(ft\r\n +(1*f[-1]*m.sin(w[j]*t[-1])/w[j]) #last point\r\n -(1*f[0]*m.sin(t[0]*w[j])/w[j]) #first point\r\n )\r\n \r\n \r\n dctvec=np.column_stack((w, smp))\r\n return dctvec\r\n\r\n#--------------------------#\r\n#--------------------------#\r\n#nDCT\r\n#w is the sampling vector in Fourier space, t are the x-values and f are the y-values of the input array\r\ndef nDST(w,t,f):\r\n smp=[]\r\n \r\n for j in range(len(w)): #loops through all sampling points w_i\r\n ft=0 \r\n for i in range(len(f)-1): # Fourier integral \r\n ft+=(\r\n ((f[i+1]-f[i])/(t[i+1]-t[i])*(2)*m.cos(0.5*w[j]*(t[i+1]+t[i]))*m.sin(0.5*w[j]*(t[i+1]-t[i]))/(w[j]*w[j])) \r\n )\r\n \r\n smp.append(ft\r\n -(1*f[-1]*m.cos(w[j]*t[-1])/w[j]) #last point\r\n +(1*f[0]*m.cos(w[j]*t[0])/w[j]) #first point\r\n )\r\n \r\n \r\n dstvec=np.column_stack((w, smp))\r\n return dstvec\r\n\r\n#--------------------------------------------------------------------------------#\r\n#--------------------------------------------------------------------------------#\r\n# Select and Import file\r\n#Either, tkinter is used to open a dialog to specify the input file (2-column ascii) or\r\n#the filename is manually specified (e.g. 'C:/Users/.../myfile.txt'). in the latter case, \"tkinter.filedialog\" is not required \r\n\r\nfileopt = [('SF','*.txt')] #define the file extension\r\nfilename = tkinter.filedialog.askopenfilename(filetypes=fileopt) # opens a windows dialog to select and open an ascii file\r\n\r\n#filename='C:/Users/Mayo/Desktop/Programme/Github/Filon FT/threesines.txt'\r\nprint(filename) # prints filename and directory of input file\r\n\r\nwith open(filename) as finp: #read input file\r\n content = finp.read().splitlines() # line-by-line reading with \\n removed\r\n\r\n#--------------------------------------------------------------------------------#\r\n#--------------------------------------------------------------------------------#\r\n#Arrange the imported data \r\ntval=[];\r\nfval=[];\r\n\r\nfor i in range(len(content)):\r\n (tval.append(content[i].split('\\t')[0].replace(\" \",\"\")))\r\n (fval.append(content[i].split('\\t')[1].replace(\" \",\"\")))\r\n \r\nt=[float(i) for i in tval]; #converts string to float\r\nf=[float(i) for i in fval]; #converts string to float\r\n\r\n#create freq axis w_i=(t_i)^-1\r\nw=[];\r\nfor i in range(len(t)):\r\n w.append(1/t[i]) #calculate the inverse of the times\r\n \r\nw=w[::-1] #reverse the list of frequencies\r\n\r\n#--------------------------------------------------------------------------------#\r\n#--------------------------------------------------------------------------------#\r\n#nDCT and nDST are computed for the frequencies w_i\r\nstart = timer() \r\nnDCT=nDCT(w,t,f)\r\nnDST=nDST(w,t,f)\r\n#--------------------------------------------------------------------------------#\r\n#--------------------------------------------------------------------------------#\r\n#Write to file \r\nfsdct = open(filename[0:-4]+\"_DCT.pef\",'w') #create file for DCT\r\nfsdst = open(filename[0:-4]+\"_DST.pef\",'w') #create file for DCT\r\n\r\nfor i in range(len(nDCT)): #write g(w) to files\r\n fsdct.write(str(nDCT[i,0]) + '\\t' + str(nDCT[i,1])+ '\\n')\r\n fsdst.write(str(nDST[i,0]) + '\\t' + str(nDST[i,1])+ '\\n')\r\n \r\n#close files \r\nfsdct.close() \r\nfsdst.close() \r\n#--------------------------------------------------------------------------------#\r\n#--------------------------------------------------------------------------------# \r\nend = timer()\r\nprint('nDFT was successful. elapsed time: '+str(round(end - start,3))+'s')\r\n","repo_name":"MJHofmann/nDFT-Fourier-Transform-","sub_path":"nDFT v1.py","file_name":"nDFT v1.py","file_ext":"py","file_size_in_byte":6134,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"73358281850","text":"import os\nimport numpy as np\nimport random\n\nimport torch\nfrom torch.utils.data import Dataset\nimport cv2\nfrom pycocotools.coco import COCO\n\n\ncoco_class_labels = ('background',\n 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck',\n 'boat', 'traffic light', 'fire hydrant', 'street sign', 'stop sign',\n 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',\n 'elephant', 'bear', 'zebra', 'giraffe', 'hat', 'backpack', 'umbrella',\n 'shoe', 'eye glasses', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis',\n 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove',\n 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'plate', 'wine glass',\n 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich',\n 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair',\n 'couch', 'potted plant', 'bed', 'mirror', 'dining table', 'window', 'desk',\n 'toilet', 'door', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',\n 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'blender', 'book',\n 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush')\n\ncoco_class_index = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20,\n 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,\n 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 67,\n 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]\n\n\nclass COCODataset(Dataset):\n \"\"\"\n COCO dataset class.\n \"\"\"\n def __init__(self, \n data_dir=None, \n image_set='train2017',\n transform=None):\n \"\"\"\n COCO dataset initialization. Annotation data are read into memory by COCO API.\n Args:\n data_dir (str): dataset root directory\n json_file (str): COCO json file name\n name (str): COCO data name (e.g. 'train2017' or 'val2017')\n img_size (int): target image size after pre-processing\n min_size (int): bounding boxes smaller than this are ignored\n debug (bool): if True, only one data id is selected from the dataset\n \"\"\"\n if image_set == 'train2017':\n self.json_file = 'instances_train2017.json'\n elif image_set == 'val2017':\n self.json_file = 'instances_val2017.json'\n elif image_set == 'test2017':\n self.json_file == 'image_info_test-dev2017.json'\n self.image_set = image_set\n self.data_dir = data_dir\n self.coco = COCO(os.path.join(self.data_dir, 'annotations', self.json_file))\n self.ids = self.coco.getImgIds()\n self.class_ids = sorted(self.coco.getCatIds())\n # augmentation\n self.transform = transform\n\n\n def __len__(self):\n return len(self.ids)\n\n\n def __getitem__(self, index):\n img, target = self.pull_item(index)\n return img, target\n\n\n def pull_image(self, index):\n id_ = self.ids[index]\n img_file = os.path.join(self.data_dir, self.image_set,\n '{:012}'.format(id_) + '.jpg')\n img = cv2.imread(img_file)\n\n if self.json_file == 'instances_val5k.json' and img is None:\n img_file = os.path.join(self.data_dir, 'train2017',\n '{:012}'.format(id_) + '.jpg')\n img = cv2.imread(img_file)\n\n return img, id_\n\n\n def pull_anno(self, index):\n id_ = self.ids[index]\n\n anno_ids = self.coco.getAnnIds(imgIds=[int(id_)], iscrowd=None)\n annotations = self.coco.loadAnns(anno_ids)\n \n target = []\n for anno in annotations:\n if 'bbox' in anno:\n xmin = np.max((0, anno['bbox'][0]))\n ymin = np.max((0, anno['bbox'][1]))\n xmax = xmin + anno['bbox'][2]\n ymax = ymin + anno['bbox'][3]\n \n if anno['area'] > 0 and xmax >= xmin and ymax >= ymin:\n label_ind = anno['category_id']\n cls_id = self.class_ids.index(label_ind)\n\n target.append([xmin, ymin, xmax, ymax, cls_id]) # [xmin, ymin, xmax, ymax, label_ind]\n else:\n print('No bbox !!')\n return target\n\n\n def load_image_annotation(self, index):\n anno_ids = self.coco.getAnnIds(imgIds=[int(index)], iscrowd=None)\n annotations = self.coco.loadAnns(anno_ids)\n\n # load an image\n img_file = os.path.join(self.data_dir, self.image_set,\n '{:012}'.format(index) + '.jpg')\n img = cv2.imread(img_file)\n \n if self.json_file == 'instances_val5k.json' and img is None:\n img_file = os.path.join(self.data_dir, 'train2017',\n '{:012}'.format(index) + '.jpg')\n img = cv2.imread(img_file)\n\n assert img is not None\n\n height, width, channels = img.shape\n \n # load an annotation\n annotation = []\n for anno in annotations:\n if 'bbox' in anno and anno['area'] > 0: \n xmin = np.max((0, anno['bbox'][0]))\n ymin = np.max((0, anno['bbox'][1]))\n xmax = np.min((width - 1, xmin + np.max((0, anno['bbox'][2] - 1))))\n ymax = np.min((height - 1, ymin + np.max((0, anno['bbox'][3] - 1))))\n if xmax > xmin and ymax > ymin:\n label_ind = anno['category_id']\n cls_id = self.class_ids.index(label_ind)\n\n annotation.append([xmin, ymin, xmax, ymax, cls_id]) # [xmin, ymin, xmax, ymax, label_ind]\n else:\n print('No bbox !!!')\n # end here .\n\n return img, annotation, height, width\n\n\n def pull_item(self, index):\n id_ = self.ids[index]\n img, anno, height, width = self.load_image_annotation(id_)\n # check anno\n if len(anno) == 0:\n anno = np.zeros([1, 5])\n else:\n anno = np.array(anno)\n\n # transform\n target = {'boxes': anno[:, :4],\n 'labels': anno[:, 4],\n 'orig_size': [height, width]}\n img, target = self.transform(img, target)\n \n return img, target\n\n\nif __name__ == \"__main__\":\n from transforms import TrainTransforms, ValTransforms\n img_size = 512\n dataset = COCODataset(\n data_dir='/mnt/share/ssd2/dataset/COCO',\n transform=TrainTransforms(img_size),\n image_set='train')\n \n np.random.seed(0)\n class_colors = [(np.random.randint(255),\n np.random.randint(255),\n np.random.randint(255)) for _ in range(80)]\n rgb_mean = np.array(dataset.transform.mean)\n rgb_std = np.array(dataset.transform.std)\n print('Data length: ', len(dataset))\n for i in range(1000):\n # load an image\n img, target = dataset.pull_item(i)\n img = img.permute(1,2,0).numpy()\n img = (img*rgb_std + rgb_mean) * 255\n # from rgb to bgr\n img = img[:, :, (2, 1, 0)]\n img = img.astype(np.uint8).copy()\n # load a target\n cls_gt = target['labels'].tolist()\n box_gt = target['boxes'].tolist()\n for i in range(len(cls_gt)):\n cls_id = int(cls_gt[i])\n cx, cy, bw, bh = box_gt[i]\n x1 = int((cx - bw / 2) * img_size)\n y1 = int((cy - bh / 2) * img_size)\n x2 = int((cx + bw / 2) * img_size)\n y2 = int((cy + bh / 2) * img_size)\n img = cv2.rectangle(img, (x1, y1), (x2, y2), (0,0,255), 2)\n color = class_colors[cls_id]\n cls_name = coco_class_labels[coco_class_index[cls_id]]\n mess = '%s' % (cls_name)\n cv2.putText(img, mess, (int(x1), int(y1 - 5)), 0, 0.5, color, 1, lineType=cv2.LINE_AA)\n cv2.imshow('gt', img)\n cv2.waitKey(0)\n","repo_name":"yjh0410/FCOS-RT_PyTorch","sub_path":"data/coco.py","file_name":"coco.py","file_ext":"py","file_size_in_byte":8317,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"77"}
+{"seq_id":"42972378129","text":"def merge (izq,der):\r\n lista = []\r\n izq_index = der_index = 0\r\n izq_largo, der_largo = len (izq), len(der)\r\n\r\n for _ in range (izq_largo + der_largo):\r\n if izq_index < der_index and der_index < izq_index:\r\n\r\n if izq [izq_index <= der[der_index]]:\r\n lista.append(izq [izq_index])\r\n izq_index +=1\r\n\r\n else:\r\n lista.append(der[der_index])\r\n der_index +=1\r\n\r\n elif izq_index == izq_largo:\r\n lista.append(der[der_index])\r\n der_index += 1\r\n\r\n elif der_index == der_largo:\r\n lista.append(izq[izq_index])\r\n izq_index += 1\r\n\r\n return lista\r\n\r\ndef mergeSort(nums):\r\n if len(nums) <= 2:\r\n return nums\r\n\r\n mid = len (nums) // 2\r\n\r\n izq = mergeSort(nums[:mid])\r\n der = mergeSort(nums[mid:])\r\n\r\n return merge (izq,der)\r\n\r\nlistan = [5,2,1,8,6]\r\nlistan = mergeSort(listan)\r\nprint (listan)\r\n","repo_name":"Thevid225/Practica-2","sub_path":"Merge Sort.py","file_name":"Merge Sort.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"22984171779","text":"from . import Youtube, Twitch, Steam\n# import requests\n\n\nclass Importer():\n\n def get(self):\n array_post = []\n steam = Steam.Steam()\n youtube = Youtube.Youtube()\n twitch = Twitch.Twitch()\n print(\"Inicio de importação dos jogos da steam ...\\n\")\n array_steam_data = steam.get_steam_data()\n for game_steam in array_steam_data:\n print(\"Jogo: {}\".format(game_steam['name']))\n print(\"Importando dados do youtube ...\")\n game_youtube = youtube.get_youtube_data(game_steam['name'])\n print(\"Importando dados da twitch ...\")\n game_twitch = twitch.get_twitch_data(game_steam['name'])\n dictionary_game = self.merge_data(\n game_steam, game_youtube, game_twitch)\n array_post.append(dictionary_game)\n\n\n print(\"Jogo {} importado com sucesso!\\n\".format(game_steam['name']))\n\n\n # requests.post(\"http://web:8000/api/\", json=array_post)\n return array_post\n\n def merge_data(self, steam_game, youtube_game, twitch_game):\n merge_dictionary = {\n # Steam data\n 'id_steam': steam_game['appid'],\n 'name': steam_game['name'],\n 'positive_reviews_steam': steam_game['positive'],\n 'negative_reviews_steam': steam_game['negative'],\n 'owners': steam_game['owners'],\n 'average_forever': steam_game['average_forever'],\n 'average_2weeks': steam_game['average_2weeks'],\n 'price': steam_game['price'],\n 'languages': steam_game['supported_languages'],\n 'genres': steam_game['genres'],\n 'main_image': steam_game['header_image'],\n 'screenshots': steam_game['screenshots'],\n 'release_date': steam_game['release_date'],\n 'r_average': steam_game['r'],\n 'g_average': steam_game['g'],\n 'b_average': steam_game['b'],\n # Youtube data\n 'count_videos': youtube_game['count_videos'],\n 'count_views': youtube_game['count_views'],\n 'count_likes': youtube_game['count_likes'],\n 'count_dislikes': youtube_game['count_dislikes'],\n 'count_comments': youtube_game['count_comments'],\n # Twitch data\n 'total_views': twitch_game['total_views'],\n 'streams': twitch_game['streams']\n }\n return merge_dictionary\n","repo_name":"fga-eps-mds/2018.2-GamesBI_Importadores","sub_path":"worker/resources/Importer.py","file_name":"Importer.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"9665798807","text":"from typing import Optional, Tuple, Union\n\nimport numpy as np\nimport torch\n\nfrom mmhuman3d.core.conventions.keypoints_mapping import KEYPOINTS_FACTORY\nfrom mmhuman3d.core.conventions.keypoints_mapping.human_data import (\n HUMAN_DATA_LIMBS_INDEX,\n HUMAN_DATA_PALETTE,\n)\n\n\ndef search_limbs(\n data_source: str,\n mask: Optional[Union[np.ndarray, tuple, list]] = None,\n keypoints_factory: dict = KEYPOINTS_FACTORY) -> Tuple[dict, dict]:\n \"\"\"Search the corresponding limbs following the basis human_data limbs. The\n mask could mask out the incorrect keypoints.\n\n Args:\n data_source (str): data source type.\n mask (Optional[Union[np.ndarray, tuple, list]], optional):\n refer to keypoints_mapping. Defaults to None.\n keypoints_factory (dict, optional): Dict of all the conventions.\n Defaults to KEYPOINTS_FACTORY.\n Returns:\n Tuple[dict, dict]: (limbs_target, limbs_palette).\n \"\"\"\n limbs_source = HUMAN_DATA_LIMBS_INDEX\n limbs_palette = HUMAN_DATA_PALETTE\n keypoints_source = keypoints_factory['human_data']\n keypoints_target = keypoints_factory[data_source]\n limbs_target = {}\n for k, part_limbs in limbs_source.items():\n limbs_target[k] = []\n for limb in part_limbs:\n flag = False\n if (keypoints_source[limb[0]]\n in keypoints_target) and (keypoints_source[limb[1]]\n in keypoints_target):\n if mask is not None:\n if mask[keypoints_target.index(keypoints_source[\n limb[0]])] != 0 and mask[keypoints_target.index(\n keypoints_source[limb[1]])] != 0:\n flag = True\n else:\n flag = True\n if flag:\n limbs_target.setdefault(k, []).append([\n keypoints_target.index(keypoints_source[limb[0]]),\n keypoints_target.index(keypoints_source[limb[1]])\n ])\n if k in limbs_target:\n if k == 'body':\n np.random.seed(0)\n limbs_palette[k] = np.random.randint(\n 0, high=255, size=(len(limbs_target[k]), 3))\n else:\n limbs_palette[k] = np.array(limbs_palette[k])\n return limbs_target, limbs_palette\n\n\ndef transform_kps2d(kps2d: torch.Tensor, transf, img_res=224):\n \"\"\"Process gt 2D keypoints and apply transforms.\"\"\"\n bs, n_kps = kps2d.shape[:2]\n kps_pad = torch.cat([kps2d, torch.ones((bs, n_kps, 1)).to(kps2d)], dim=-1)\n kps_new = torch.bmm(transf, kps_pad.transpose(1, 2))\n kps_new = kps_new.transpose(1, 2)\n kps_new[:, :, :-1] = 2. * kps_new[:, :, :-1] / img_res - 1.\n return kps_new[:, :, :2]\n","repo_name":"open-mmlab/mmhuman3d","sub_path":"mmhuman3d/utils/keypoint_utils.py","file_name":"keypoint_utils.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","stars":1016,"dataset":"github-code","pt":"77"}
+{"seq_id":"29440588729","text":"def es_primo(numero):\n if numero==1 or numero%2==0:\n n=False\n else:\n n=True\n return n\n\ndef suma_divisores(a):\n i=1\n acum=0\n while i '\" + today + \"'\")\r\n return_list = [ol_item_items.Count, ol_item_items_rst.Count, ol_item_items.Count - ol_item_items_rst.Count,\r\n ol_item_items_reso1.Count]\r\n\r\n return return_list\r\n\r\n @staticmethod\r\n def count_resolved(ol_item):\r\n today = datetime.now().strftime(\"%Y-%m-%d\") + \" 00:00\"\r\n ol_item_items = ol_item.Items\r\n ol_item_items_reso1 = ol_item_items.Restrict(\"[LastModificationTime] > '\" + today + \"'\")\r\n\r\n return ol_item_items_reso1.Count\r\n\r\n @staticmethod\r\n def view_all():\r\n headers = (\"id\", \"mailbox\", \"received\", \"sent\", \"resolved\", \"year\", \"month\", \"day\", \"week\")\r\n print(headers)\r\n for row in database.view_all():\r\n print(row)\r\n\r\n @staticmethod\r\n def folder_stats(folder):\r\n today = datetime.now().strftime(\"%Y-%m-%d\") + \" 00:00\"\r\n if folder.Name == \"Sent Items\":\r\n sent_items = folder.Items\r\n sent_today = sent_items.Restrict(\"[SentOn] > '\" + today + \"'\")\r\n return sent_today.Count\r\n else:\r\n all_items = folder.Items\r\n all_items_r = all_items.Restrict(\"[ReceivedTime] >= '\" + today + \"'\")\r\n return all_items_r.Count\r\n\r\n def to_excel(self):\r\n wb = Workbook()\r\n ws = wb.active\r\n for index, item in enumerate(self.export_list):\r\n for subindex, subitem in enumerate(item):\r\n ws.cell(row=index+1, column=subindex+1).value = subitem\r\n wb.save(\"export.xlsx\")\r\n print(\"DONE!\")\r\n self.enter_mailbox_menu()\r\n\r\n\r\nif __name__ == '__main__':\r\n app = App()\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"z0rdd/EmailReportApp","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7780,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"22177483706","text":"import abc\nimport collections\nfrom typing import (\n Any,\n cast,\n Dict,\n Iterator,\n Generic,\n List,\n Optional,\n Sequence,\n Tuple,\n Type,\n TypeVar,\n TYPE_CHECKING,\n)\n\nimport numpy as np\n\nfrom cirq import devices, ops, protocols, study, value\nfrom cirq.sim.simulation_product_state import SimulationProductState\nfrom cirq.sim.simulation_state import TSimulationState\nfrom cirq.sim.simulation_state_base import SimulationStateBase\nfrom cirq.sim.simulator import (\n TSimulationTrialResult,\n SimulatesIntermediateState,\n SimulatesSamples,\n StepResult,\n SimulationTrialResult,\n check_all_resolved,\n split_into_matching_protocol_then_general,\n)\n\nif TYPE_CHECKING:\n import cirq\n\nTStepResultBase = TypeVar('TStepResultBase', bound='StepResultBase')\n\n\nclass SimulatorBase(\n Generic[TStepResultBase, TSimulationTrialResult, TSimulationState],\n SimulatesIntermediateState[\n TStepResultBase, TSimulationTrialResult, SimulationStateBase[TSimulationState]\n ],\n SimulatesSamples,\n metaclass=abc.ABCMeta,\n):\n \"\"\"A base class for the built-in simulators.\n\n Most implementors of this interface should implement the\n `_create_partial_simulation_state` and `_create_step_result` methods. The\n first one creates the simulator's quantum state representation at the\n beginning of the simulation. The second creates the step result emitted\n after each `Moment` in the simulation.\n\n Iteration in the subclass is handled by the `_core_iterator` implementation\n here, which handles moment stepping, application of operations, measurement\n collection, and creation of noise. Simulators with more advanced needs can\n override the implementation if necessary.\n\n Sampling is handled by the implementation of `_run`. This implementation\n iterates the circuit to create a final step result, and samples that\n result when possible. If not possible, due to noise or classical\n probabilities on a state vector, the implementation attempts to fully\n iterate the unitary prefix once, then only repeat the non-unitary\n suffix from copies of the state obtained by the prefix. If more advanced\n functionality is required, then the `_run` method can be overridden.\n\n Note that state here refers to simulator state, which is not necessarily\n a state vector. The included simulators and corresponding states are state\n vector, density matrix, Clifford, and MPS. Each of these use the default\n `_core_iterator` and `_run` methods.\n \"\"\"\n\n def __init__(\n self,\n *,\n dtype: Type[np.complexfloating] = np.complex64,\n noise: 'cirq.NOISE_MODEL_LIKE' = None,\n seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None,\n split_untangled_states: bool = False,\n ):\n \"\"\"Initializes the simulator.\n\n Args:\n dtype: The `numpy.dtype` used by the simulation.\n noise: A noise model to apply while simulating.\n seed: The random seed to use for this simulator.\n split_untangled_states: If True, optimizes simulation by running\n unentangled qubit sets independently and merging those states\n at the end.\n \"\"\"\n self._dtype = dtype\n self._prng = value.parse_random_state(seed)\n self._noise = devices.NoiseModel.from_noise_model_like(noise)\n self._split_untangled_states = split_untangled_states\n\n @property\n def noise(self) -> 'cirq.NoiseModel':\n return self._noise\n\n @abc.abstractmethod\n def _create_partial_simulation_state(\n self,\n initial_state: Any,\n qubits: Sequence['cirq.Qid'],\n classical_data: 'cirq.ClassicalDataStore',\n ) -> TSimulationState:\n \"\"\"Creates an instance of the TSimulationState class for the simulator.\n\n It represents the supplied qubits initialized to the provided state.\n\n Args:\n initial_state: The initial state to represent. An integer state is\n understood to be a pure state. Other state representations are\n simulator-dependent.\n qubits: The sequence of qubits to represent.\n classical_data: The shared classical data container for this\n simulation.\n \"\"\"\n\n @abc.abstractmethod\n def _create_step_result(\n self, sim_state: SimulationStateBase[TSimulationState]\n ) -> TStepResultBase:\n \"\"\"This method should be implemented to create a step result.\n\n Args:\n sim_state: The SimulationStateBase for this trial.\n\n Returns:\n The StepResult.\n \"\"\"\n\n def _can_be_in_run_prefix(self, val: Any):\n \"\"\"Determines what should be put in the prefix in `_run`\n\n The `_run` method has an optimization that reduces repetition by\n splitting the circuit into a prefix that is pure with respect to the\n state representation, and only executing that once per sample set. For\n state vectors, any unitary operation is pure, and we make this the\n default here. For density matrices, any non-measurement operation can\n be represented wholely in the matrix, and thus this method is\n overridden there to enable greater optimization there.\n\n Custom simulators can override this method appropriately.\n\n Args:\n val: An operation or noise model to test for purity within the\n state representation.\n\n Returns:\n A boolean representing whether the value can be added to the\n `_run` prefix.\"\"\"\n return protocols.has_unitary(val)\n\n def _base_iterator(\n self, circuit: 'cirq.AbstractCircuit', qubits: Tuple['cirq.Qid', ...], initial_state: Any\n ) -> Iterator[TStepResultBase]:\n sim_state = self._create_simulation_state(initial_state, qubits)\n return self._core_iterator(circuit, sim_state)\n\n def _core_iterator(\n self,\n circuit: 'cirq.AbstractCircuit',\n sim_state: SimulationStateBase[TSimulationState],\n all_measurements_are_terminal: bool = False,\n ) -> Iterator[TStepResultBase]:\n \"\"\"Standard iterator over StepResult from Moments of a Circuit.\n\n Args:\n circuit: The circuit to simulate.\n sim_state: The initial args for the simulation. The form of\n this state depends on the simulation implementation. See\n documentation of the implementing class for details.\n all_measurements_are_terminal: Whether all measurements in the\n given circuit are terminal.\n\n Yields:\n StepResults from simulating a Moment of the Circuit.\n\n Raises:\n TypeError: The simulator encounters an op it does not support.\n \"\"\"\n\n if len(circuit) == 0:\n yield self._create_step_result(sim_state)\n return\n\n noisy_moments = self.noise.noisy_moments(circuit, sorted(circuit.all_qubits()))\n measured: Dict[Tuple['cirq.Qid', ...], bool] = collections.defaultdict(bool)\n for moment in noisy_moments:\n for op in ops.flatten_to_ops(moment):\n try:\n # Preprocess measurements\n if all_measurements_are_terminal and measured[op.qubits]:\n continue\n if isinstance(op.gate, ops.MeasurementGate):\n measured[op.qubits] = True\n if all_measurements_are_terminal:\n continue\n\n # Simulate the operation\n protocols.act_on(op, sim_state)\n except TypeError:\n raise TypeError(f\"{self.__class__.__name__} doesn't support {op!r}\")\n\n yield self._create_step_result(sim_state)\n\n def _run(\n self,\n circuit: 'cirq.AbstractCircuit',\n param_resolver: 'cirq.ParamResolver',\n repetitions: int,\n ) -> Dict[str, np.ndarray]:\n \"\"\"See definition in `cirq.SimulatesSamples`.\"\"\"\n param_resolver = param_resolver or study.ParamResolver({})\n resolved_circuit = protocols.resolve_parameters(circuit, param_resolver)\n check_all_resolved(resolved_circuit)\n qubits = tuple(sorted(resolved_circuit.all_qubits()))\n sim_state = self._create_simulation_state(0, qubits)\n\n prefix, general_suffix = (\n split_into_matching_protocol_then_general(resolved_circuit, self._can_be_in_run_prefix)\n if self._can_be_in_run_prefix(self.noise)\n else (resolved_circuit[0:0], resolved_circuit)\n )\n step_result = None\n for step_result in self._core_iterator(circuit=prefix, sim_state=sim_state):\n pass\n\n general_ops = list(general_suffix.all_operations())\n if all(isinstance(op.gate, ops.MeasurementGate) for op in general_ops):\n for step_result in self._core_iterator(\n circuit=general_suffix, sim_state=sim_state, all_measurements_are_terminal=True\n ):\n pass\n assert step_result is not None\n measurement_ops = [cast(ops.GateOperation, op) for op in general_ops]\n return step_result.sample_measurement_ops(\n measurement_ops, repetitions, seed=self._prng, _allow_repeated=True\n )\n\n records: Dict['cirq.MeasurementKey', List[Sequence[Sequence[int]]]] = {}\n for i in range(repetitions):\n for step_result in self._core_iterator(\n general_suffix,\n sim_state=sim_state.copy(deep_copy_buffers=False)\n if i < repetitions - 1\n else sim_state,\n ):\n pass\n for k, r in step_result._classical_data.records.items():\n if k not in records:\n records[k] = []\n records[k].append(r)\n for k, cr in step_result._classical_data.channel_records.items():\n if k not in records:\n records[k] = []\n records[k].append([cr])\n\n def pad_evenly(results: Sequence[Sequence[Sequence[int]]]):\n largest = max(len(result) for result in results)\n xs = np.zeros((len(results), largest, len(results[0][0])), dtype=np.uint8)\n for i, result in enumerate(results):\n xs[i, 0 : len(result), :] = result\n return xs\n\n return {str(k): pad_evenly(v) for k, v in records.items()}\n\n def simulate_sweep_iter(\n self,\n program: 'cirq.AbstractCircuit',\n params: 'cirq.Sweepable',\n qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,\n initial_state: Any = None,\n ) -> Iterator[TSimulationTrialResult]:\n \"\"\"Simulates the supplied Circuit.\n\n This particular implementation overrides the base implementation such\n that an unparameterized prefix circuit is simulated and fed into the\n parameterized suffix circuit.\n\n Args:\n program: The circuit to simulate.\n params: Parameters to run with the program.\n qubit_order: Determines the canonical ordering of the qubits. This\n is often used in specifying the initial state, i.e. the\n ordering of the computational basis states.\n initial_state: The initial state for the simulation. This can be\n either a raw state or an `SimulationStateBase`. The form of the\n raw state depends on the simulation implementation. See\n documentation of the implementing class for details.\n\n Returns:\n List of SimulationTrialResults for this run, one for each\n possible parameter resolver.\n \"\"\"\n\n def sweep_prefixable(op: 'cirq.Operation'):\n return self._can_be_in_run_prefix(op) and not protocols.is_parameterized(op)\n\n qubits = ops.QubitOrder.as_qubit_order(qubit_order).order_for(program.all_qubits())\n initial_state = 0 if initial_state is None else initial_state\n sim_state = self._create_simulation_state(initial_state, qubits)\n prefix, suffix = (\n split_into_matching_protocol_then_general(program, sweep_prefixable)\n if self._can_be_in_run_prefix(self.noise)\n else (program[0:0], program)\n )\n step_result = None\n for step_result in self._core_iterator(circuit=prefix, sim_state=sim_state):\n pass\n sim_state = step_result._sim_state\n yield from super().simulate_sweep_iter(suffix, params, qubit_order, sim_state)\n\n def _create_simulation_state(\n self, initial_state: Any, qubits: Sequence['cirq.Qid']\n ) -> SimulationStateBase[TSimulationState]:\n if isinstance(initial_state, SimulationStateBase):\n return initial_state\n\n classical_data = value.ClassicalDataDictionaryStore()\n if self._split_untangled_states:\n args_map: Dict[Optional['cirq.Qid'], TSimulationState] = {}\n if isinstance(initial_state, int):\n for q in reversed(qubits):\n args_map[q] = self._create_partial_simulation_state(\n initial_state=initial_state % q.dimension,\n qubits=[q],\n classical_data=classical_data,\n )\n initial_state = int(initial_state / q.dimension)\n else:\n args = self._create_partial_simulation_state(\n initial_state=initial_state, qubits=qubits, classical_data=classical_data\n )\n for q in qubits:\n args_map[q] = args\n args_map[None] = self._create_partial_simulation_state(0, (), classical_data)\n return SimulationProductState(\n args_map, qubits, self._split_untangled_states, classical_data=classical_data\n )\n else:\n return self._create_partial_simulation_state(\n initial_state=initial_state, qubits=qubits, classical_data=classical_data\n )\n\n\nclass StepResultBase(\n Generic[TSimulationState], StepResult[SimulationStateBase[TSimulationState]], abc.ABC\n):\n \"\"\"A base class for step results.\"\"\"\n\n def __init__(self, sim_state: SimulationStateBase[TSimulationState]):\n \"\"\"Initializes the step result.\n\n Args:\n sim_state: The `SimulationStateBase` for this step.\n \"\"\"\n super().__init__(sim_state)\n self._merged_sim_state_cache: Optional[TSimulationState] = None\n qubits = sim_state.qubits\n self._qubits = qubits\n self._qubit_mapping = {q: i for i, q in enumerate(qubits)}\n self._qubit_shape = tuple(q.dimension for q in qubits)\n self._classical_data = sim_state.classical_data\n\n def _qid_shape_(self):\n return self._qubit_shape\n\n @property\n def _merged_sim_state(self) -> TSimulationState:\n if self._merged_sim_state_cache is None:\n self._merged_sim_state_cache = self._sim_state.create_merged_state()\n return self._merged_sim_state_cache\n\n def sample(\n self,\n qubits: List['cirq.Qid'],\n repetitions: int = 1,\n seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None,\n ) -> np.ndarray:\n return self._sim_state.sample(qubits, repetitions, seed)\n\n\nclass SimulationTrialResultBase(\n SimulationTrialResult[SimulationStateBase[TSimulationState]], Generic[TSimulationState], abc.ABC\n):\n \"\"\"A base class for trial results.\"\"\"\n\n def __init__(\n self,\n params: study.ParamResolver,\n measurements: Dict[str, np.ndarray],\n final_simulator_state: 'cirq.SimulationStateBase[TSimulationState]',\n ) -> None:\n \"\"\"Initializes the `SimulationTrialResultBase` class.\n\n Args:\n params: A ParamResolver of settings used for this result.\n measurements: A dictionary from measurement gate key to measurement\n results. Measurement results are a numpy ndarray of actual\n boolean measurement results (ordered by the qubits acted on by\n the measurement gate.)\n final_simulator_state: The final simulator state of the system after the\n trial finishes.\n \"\"\"\n super().__init__(params, measurements, final_simulator_state=final_simulator_state)\n self._merged_sim_state_cache: Optional[TSimulationState] = None\n\n def get_state_containing_qubit(self, qubit: 'cirq.Qid') -> TSimulationState:\n \"\"\"Returns the independent state space containing the qubit.\n\n Args:\n qubit: The qubit whose state space is required.\n\n Returns:\n The state space containing the qubit.\"\"\"\n return self._final_simulator_state[qubit]\n\n def _get_substates(self) -> Sequence[TSimulationState]:\n state = self._final_simulator_state\n if isinstance(state, SimulationProductState):\n substates: Dict[TSimulationState, int] = {}\n for q in state.qubits:\n substates[self.get_state_containing_qubit(q)] = 0\n substates[state[None]] = 0\n return tuple(substates.keys())\n return [state.create_merged_state()]\n\n def _get_merged_sim_state(self) -> TSimulationState:\n if self._merged_sim_state_cache is None:\n self._merged_sim_state_cache = self._final_simulator_state.create_merged_state()\n return self._merged_sim_state_cache\n","repo_name":"quantumlib/Cirq","sub_path":"cirq-core/cirq/sim/simulator_base.py","file_name":"simulator_base.py","file_ext":"py","file_size_in_byte":17529,"program_lang":"python","lang":"en","doc_type":"code","stars":3974,"dataset":"github-code","pt":"77"}
+{"seq_id":"9616507248","text":"from pdf2image import convert_from_path\nimport os\nimport time\n\nPOPPLER_PATH = r\"poppler\\poppler-0.68.0\\bin\"\n\n\ndef pdf2jpg(input, output, name, progress, loadtimes):\n pdf_path = input\n save_folder = output\n\n # Update progress bar (3rd time)\n time.sleep(0.3)\n progress.setValue(loadtimes[2])\n pages = convert_from_path(pdf_path=pdf_path, poppler_path=POPPLER_PATH)\n\n i = 1\n # Update progress bar (4th time)\n progress.setValue(loadtimes[3])\n\n for page in pages:\n page.thumbnail((680, 880))\n fname = f\"{name}-{i}.jpg\"\n page.save(os.path.join(save_folder, fname), \"JPEG\")\n i += 1\n # Update progress bar (5th time)\n progress.setValue(loadtimes[4])\n","repo_name":"SwayamSahoo11742/Pluvius","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"22178600056","text":"import numpy as np\nimport pytest\n\nimport cirq\nimport cirq_google\nimport cirq_google.experimental.ops.coupler_pulse as coupler_pulse\n\n\ndef test_sycamore_grid_layout():\n # Qubits on Sycamore but not on Sycamore23\n q0 = cirq.GridQubit(5, 5)\n q1 = cirq.GridQubit(5, 6)\n syc = cirq.FSimGate(theta=np.pi / 2, phi=np.pi / 6)(q0, q1)\n sqrt_iswap = cirq.FSimGate(theta=np.pi / 4, phi=0)(q0, q1)\n cirq_google.Sycamore.validate_operation(syc)\n cirq_google.Sycamore.validate_operation(sqrt_iswap)\n\n with pytest.raises(ValueError):\n cirq_google.Sycamore23.validate_operation(syc)\n with pytest.raises(ValueError):\n cirq_google.Sycamore23.validate_operation(sqrt_iswap)\n\n\n@pytest.mark.parametrize(\n 'device, qubit_size, layout_str',\n [\n (\n cirq_google.Sycamore,\n 88,\n \"\"\"\\\n (0, 5)───(0, 6)\n │ │\n │ │\n (1, 4)───(1, 5)───(1, 6)───(1, 7)\n │ │ │ │\n │ │ │ │\n (2, 3)───(2, 4)───(2, 5)───(2, 6)───(2, 7)───(2, 8)\n │ │ │ │ │ │\n │ │ │ │ │ │\n (3, 2)───(3, 3)──��(3, 4)───(3, 5)───(3, 6)───(3, 7)───(3, 8)───(3, 9)\n │ │ │ │ │ │ │ │\n │ │ │ │ │ │ │ │\n (4, 1)───(4, 2)───(4, 3)───(4, 4)───(4, 5)───(4, 6)───(4, 7)───(4, 8)───(4, 9)\n │ │ │ │ │ │ │ │\n │ │ │ │ │ │ │ │\n(5, 0)───(5, 1)───(5, 2)───(5, 3)───(5, 4)───(5, 5)───(5, 6)───(5, 7)───(5, 8)\n │ │ │ │ │ │ │\n │ │ │ │ │ │ │\n (6, 1)───(6, 2)───(6, 3)───(6, 4)───(6, 5)───(6, 6)───(6, 7)\n │ │ │ │ │\n │ │ │ │ │\n (7, 2)───(7, 3)───(7, 4)───(7, 5)───(7, 6)\n │ │ │\n │ │ │\n (8, 3)───(8, 4)───(8, 5)\n │\n │\n (9, 4)\"\"\",\n ),\n (\n cirq_google.Sycamore23,\n 32,\n \"\"\"\\\n (3, 2)\n │\n │\n (4, 1)───(4, 2)───(4, 3)\n │ │ │\n │ │ │\n(5, 0)───(5, 1)───(5, 2)───(5, 3)───(5, 4)\n │ │ │ │\n │ │ │ │\n (6, 1)───(6, 2)───(6, 3)───(6, 4)───(6, 5)\n │ │ │ │\n │ │ │ │\n (7, 2)───(7, 3)───(7, 4)───(7, 5)───(7, 6)\n │ │ │\n │ │ │\n (8, 3)───(8, 4)───(8, 5)\n │\n │\n (9, 4)\"\"\",\n ),\n ],\n)\ndef test_sycamore_devices(device, qubit_size, layout_str):\n q0 = cirq.GridQubit(5, 3)\n q1 = cirq.GridQubit(5, 4)\n valid_sycamore_gates_and_ops = [\n cirq_google.SYC,\n cirq.SQRT_ISWAP,\n cirq.SQRT_ISWAP_INV,\n cirq.X,\n cirq.Y,\n cirq.Z,\n cirq.Z(q0).with_tags(cirq_google.PhysicalZTag()),\n coupler_pulse.CouplerPulse(hold_time=cirq.Duration(nanos=10), coupling_mhz=25.0),\n cirq.measure(q0),\n cirq.WaitGate(cirq.Duration(millis=5)),\n # TODO(#5050) Uncomment after GlobalPhaseGate support is added.\n # cirq.GlobalPhaseGate(-1.0),\n ]\n syc = cirq.FSimGate(theta=np.pi / 2, phi=np.pi / 6)(q0, q1)\n sqrt_iswap = cirq.FSimGate(theta=np.pi / 4, phi=0)(q0, q1)\n\n assert str(device) == layout_str\n assert len(device.metadata.qubit_pairs) == qubit_size\n assert all(gate_or_op in device.metadata.gateset for gate_or_op in valid_sycamore_gates_and_ops)\n assert len(device.metadata.gate_durations) == len(device.metadata.gateset.gates)\n assert any(\n isinstance(cgs, cirq_google.SycamoreTargetGateset)\n for cgs in device.metadata.compilation_target_gatesets\n )\n assert any(\n isinstance(cgs, cirq.SqrtIswapTargetGateset)\n for cgs in device.metadata.compilation_target_gatesets\n )\n\n device.validate_operation(syc)\n device.validate_operation(sqrt_iswap)\n\n assert next(\n (\n duration\n for gate_family, duration in device.metadata.gate_durations.items()\n if syc in gate_family\n ),\n None,\n ) == cirq.Duration(nanos=12)\n assert next(\n (\n duration\n for gate_family, duration in device.metadata.gate_durations.items()\n if sqrt_iswap in gate_family\n ),\n None,\n ) == cirq.Duration(nanos=32)\n","repo_name":"quantumlib/Cirq","sub_path":"cirq-google/cirq_google/devices/known_devices_test.py","file_name":"known_devices_test.py","file_ext":"py","file_size_in_byte":5956,"program_lang":"python","lang":"en","doc_type":"code","stars":3974,"dataset":"github-code","pt":"77"}
+{"seq_id":"38005387274","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'''\n------------------------------------------------------------------------------\nMODULE VELIRE: CONTROLE DU SPOT VELIRE\n------------------------------------------------------------------------------\nAnthony Fratamico\nLaboratoire de Physiologie Végétale\nInstitut de Botanique, Université de Liège\n18 septembre 2018\n------------------------------------------------------------------------------\n'''\n\n# ----------------------------------------------------------------------------\n# DEPENDANCES\n\nimport serial\nimport os\nimport datetime\nimport codecs\nfrom time import sleep\n\n# ----------------------------------------------------------------------------\n# VARIABLES\n\nrelease = \"0.0 [dev, 2018-09-18]\"\n\nspot_cmd_dict = {\n\n# SF\n\"set_function\" :\n{\"cmd\": \"SF\",\n\"doc\":\n'''\nCette commande permet de spécifier deux fonctions du SPOT.\nUn seul argument est utilisé fixant un masque binaire pour les deux fonctions.\n\nBit 0: Si ce bit est à 1, les drivers de LED sont activés, sino ils sont en shutdown.\nBit 1: Si ce bit est à 1, le SPOT concerné obtient le rôle MASTER.\n(Un seul et un seul SPOT du reseau doit avoir le rôle de MASTER).\n''',\n\"last_update\" : \"2018-09-19\"\n},\n\n# GF\n\"get_function\":\n{\"cmd\": \"GF\",\n\"doc\":\n'''\nCette commande permet de relire la valeur du bitmask des fonctions.\nRéponse: \"#GF 0x00000003*XX\"\n''',\n\"last_update\" : \"2018-09-19\"\n},\n\n# SS\n\"set_frequence\":\n{\"cmd\": \"SS\",\n\"doc\":\n'''\nCette commande permet de spécifier la fréquence du PWM difital entre 0,1 et 10 kHz.\nUn seul argument est utilisé donnant la fréquence désirée en 1/10ème de Hz.\nUn nombre limité de fréquence est autorisé. En cas d'impossibilité, le SPOT répondra par un NAK4.\nNote: Tous les SPOT's du réseau doivent être programmé avec la même valeur.\n''',\n\"last_update\" : \"2018-09-19\"\n},\n\n# GS\n\"get_frequence\":\n{\"cmd\": \"GS\",\n\"doc\": None,\n\"last_update\" : \"2018-09-19\"\n},\n\n# GT\n\"get_temperature\":\n{\"cmd\": \"GT\",\n\"doc\": None,\n\"last_update\" : \"2018-09-19\"\n},\n\n# GL\n\"get_led\":\n{\"cmd\": \"GB\",\n\"doc\": None,\n\"last_update\" : \"2018-09-19\"\n},\n\n# SC\n\"set_channel\":\n{\"cmd\": \"SC\",\n\"doc\": None,\n\"last_update\" : \"2018-09-20\"\n},\n\n# GC\n\"get_channel\":\n{\"cmd\": \"GC\",\n\"doc\": None,\n\"last_update\" : \"2018-10-03\"\n},\n\n# GI\n\"get_cpu\":\n{\"cmd\": \"GI\",\n\"doc\": None,\n\"last_update\" : \"2018-10-03\"\n},\n\n# GE\n\"get_status\":\n{\"cmd\": \"GE\",\n\"doc\": None,\n\"last_update\" : \"2018-10-04\"\n},\n\n# SM\n\"set_master\":\n{\"cmd\": \"SM\",\n\"doc\": None,\n\"last_update\" : \"2018-11-28\"\n},\n\n# SP\n\"set_state\":\n{\"cmd\": \"SP\",\n\"doc\": None,\n\"last_update\" : \"2018-11-28\"\n},\n# SV\n\"save_conf\":\n{\"cmd\": \"SV\",\n\"doc\": None,\n\"last_update\" : \"2018-11-28\"\n}\n}\n\n# ----------------------------------------------------------------------------\n# FONCTIONS\nverbosity = 10\ndef verbose(msg, level):\n\tglobal verbosity\n\tif level <= verbosity:\n\t\tprint(msg)\n\ndef serial_dialog(ser, cmd, add, arg=\"\", checksum=True, time_for_reply=15):\n\t\"\"\" Envoie une commande sur ser et renvoi la réponse\n\n\tser: Objet serial\n\tcmd: commande du spot (cf. dictionnaire des commandes)\n\tadd: addresse du spot\n\targ: les arguments de la commande (cf. dictionnaire des commandes)\n\tchecksum: vérifie la communication (True/False)\n\ttime_for_reply: temps d'attente max. pour la réponse (s). Defaut: 15s.\n\t\"\"\"\n\tverbose(\"CALLFCT: serial_dialog\", 10)\n\tdef compute_checksum(string):\n\t\t\"\"\" Calcul la somme de contôle\n\n\t\tCalcule le reste de la division par 256 (2^8) de la somme binaire d'une chaine de caractère\n\t\t(voir doc). Reste de la somme car checksum codée en 8bits par le driver.\n\t\tRéponse de type integer\n\t\t\"\"\"\n\n\t\tchecksum = 0\n\t\tfor x in list(string):\n\t\t\tchecksum = checksum + ord(x)\n\t\treturn checksum % 256\n\n\t# Dictionnaire pour la sortie\n\treply_dict = {'raw': None, 'cmd': None, 'checksum': None, 'reply': None, 'log': None, 'error': True}\n\n\t# Vérifie que le port est ouvert\n\tser_state = ser.isOpen()\n\tif ser_state == False:\n\t\ttry:\n\t\t\tser.open()\n\t\texcept:\n\t\t\treply_dict['log'] = \"Unable to open serial port\"\n\t\t\tverbose(reply_dict['log'], 1)\n\t\t\treturn reply_dict\n\n\t# Préparation de la commande balisée\n\tcmdbal = str(\"@\"+str(cmd)+\" \"+str(add)+\" \"+str(arg)+\"\\r\")\n\tif checksum == True:\n\t\tcmdbal = cmdbal[:-1]+\"*\"+str(compute_checksum(cmdbal))+\"\\r\"\n\treply_dict['cmd'] = cmdbal\n\n\t# Envoie de la commande\n\tverbose(\"Sending to serial: \"+cmdbal, 10) # Pour le deboggage\n\tser.write(cmdbal.encode()) # encodage ascii nécessaire\n\n\t# Écoute de la réponse\n\treply = \"\"\n\tLoop = True\n\tx = None\n\twhile Loop == True:\n\t\tfor x in ser.read().decode():\n\t\t\tif x == \"\\r\":\n\t\t\t\tLoop = False\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tif x != \"\\n\": # semble arriver quand on ne ferme pas le port entre deux comunications\n\t\t\t\t\treply=reply+str(x)\n\t\tif x == None: # le port série n'a rien répondu\n\t\t\tLoop = False\n\tser.flushInput() # flush, utile si timeout dépassé\n\tser.flushOutput()\n\n\t# Sauvegarde de la réponse brute\n\treply_dict['raw'] = reply\n\tverbose(\"Received from serial: \"+reply, 10)\n\n\t# Vérification de la réponse\n\tif reply == \"\":\n\t\tverbose(msg=\"ERROR: reply is empty\", level=9)\n\t\treply_dict['log'] = \"reply was empty\"\n\t\treturn reply_dict\n\n\t# Type de réponse\n\tif (reply[0] == \"#\") and (cmd in reply) and (\"*\" in reply): # réponse structurée\n\t\treply_dict['reply'] = reply.split(\"*\")[0].replace(\"#\"+cmd+\" \", \"\") # supprime l'entête\n\t\treply_dict['checksum'] = compute_checksum(reply.split(\"*\")[0])\n\t\tif reply_dict['checksum'] == int(reply.split(\"*\")[1], 16):\n\t\t\treply_dict['error'] = False\n\t\telse:\n\t\t\treply_dict['log'] = \"wrong checksum\"\n\telse:\n\t\tif reply == \"ACK\" or reply == \"NACK\":\n\t\t\treply_dict['reply'] = reply\n\t\t\treply_dict['error'] = False\n\t\telse:\n\t\t\treply_dict['log'] = \"wrong reply structure\"\n\n\tif ser_state == False: # remet dans l'état initial\n\t\tser.close() \n\treturn reply_dict\n\n# ----------------------------------------------------------------------------\n# CLASSES\n\nclass Channel():\n\n\tdef __init__(self):\n\t\t\"\"\" Déclare les variables de base\n\n\t\t\"\"\"\n\t\tself.ser = None\n\t\tself.ch_dict = {'address': None,\n\t\t\t\t\t\t'id': None,\n\t\t\t\t\t\t'type': None,\n\t\t\t\t\t\t'wl': None,\n\t\t\t\t\t\t'color': None,\n\t\t\t\t\t\t'max': None,\n\t\t\t\t\t\t'manuf': None,\n\t\t\t\t\t\t'intensity': None,\n\t\t\t\t\t\t'unit': \"%\",\n\t\t\t\t\t\t'pwm_start': None,\n\t\t\t\t\t\t'pwm_stop': None,\n\t\t\t\t\t\t'last_request': None,\n\t\t\t\t\t\t'status':{}\n\t\t\t\t\t\t}\n\n\tdef pass_serial(self, ser):\n\t\t\"\"\" Transmet le canal du port série du spot préalablement défini\n\n\t\t\"\"\"\n\t\tself.ser = ser\n\t\treturn\n\n\tdef get_ledinfo(self, param):\n\t\t\"\"\" Renvoi la valeur du paramètre demandé\n\n\t\t\"\"\"\n\t\tif param == \"all\":\n\t\t\treturn self.ch_dict\n\t\tif param in self.ch_dict.keys():\n\t\t\treturn self.ch_dict[param]\n\t\telse:\n\t\t\treturn None\n\n\tdef get_config(self):\n\t\t\"\"\" Renvoi la valeur programmée du cana\n\n\t\t\"\"\"\n\t\treply = serial_dialog(self.ser, spot_cmd_dict[\"get_channel\"][\"cmd\"], self.ch_dict['address'], arg = str(self.ch_dict['id']))\n\t\tif reply['error'] == False:\n\t\t\treply_split = reply['reply'].split(\" \")\n\t\t\tout = {'channel': reply_split[0], 'intensity': int(reply_split[1])/2, 'pwm_start': int(reply_split[2])/200, 'pwm_stop': int(reply_split[3])/200} # intensité en % et PWM dans [0,1]\n\t\t\treturn out\n\t\telse:\n\t\t\treturn None\n\n\tdef set_config(self, intensity, unit, start, stop):\n\t\t\"\"\" Envoi la configuration demandée au canal\n\n\t\tintensity: l'intensité du courant\n\t\tunit: unité pour l'intensité du courant (défaut: % du max)\n\t\tstart: moment d'allumage (fraction de la phase du PWM)\n\t\tstop: moment d'extinction (fraction de la phase du PWM)\n\t\t\"\"\"\n\n\t\t# Conversion de 'intensity' en fonction de l'unité\n\t\tself.ch_dict['last_request'] = {'intensity': intensity, 'unit': unit, 'pwm_start': start, 'pwm_stop': stop}\n\t\tif self.ch_dict['max'] == None:\n\t\t\t#verbose(\"Empty channel\")\n\t\t\treturn None\n\t\tif unit == \"%\":\n\t\t\tif (float(intensity) < 0) or (float(intensity) > 100):\n\t\t\t\tverbose(\"ERROR: intensity out of range (0-100%)\", 3)\n\t\t\t\treturn None\n\t\t\tintensity = int(intensity*2)\n\t\t\tif intensity > self.ch_dict['max']:\n\t\t\t\tverbose(\"ERROR: intensity greather than current max\", 3)\n\t\t\t\treturn None\n\t\telse:\n\t\t\tverbose(\"ERROR: Undefined unit\", 3)\n\t\t\treturn None\n\n\t\t# Vérification du timing d'allumage\n\t\tif (float(start) < 0 or float(start) > 1) or (float(stop) < 0 or float(stop) > 1):\n\t\t\tverbose(\"ERROR: time out of range (0-1)\", 3)\n\t\t\treturn None\n\t\tstart = int(start * 200)\n\t\tstop = int(stop *200)\n\t\tif start > stop:\n\t\t\tverbose(\"ERROR: start define after stop\", 3)\n\t\t\treturn None\n\n\t\t# Envoi de la commande\n\t\treply_raw = serial_dialog(self.ser, spot_cmd_dict[\"set_channel\"][\"cmd\"], self.ch_dict['address'], arg = str(self.ch_dict['id'])+\" \"+str(intensity)+\" \"+str(start)+\" \"+str(stop))['reply']\n\t\tconfig = self.get_config()\n\t\tself.ch_dict['intensity'] = config['intensity']\n\t\tself.ch_dict['pwm_start'] = config['pwm_start']\n\t\tself.ch_dict['pwm_stop'] = config['pwm_stop']\n\t\tif reply_raw == \"ACK\":\n\t\t\treturn 0\n\t\telse:\n\t\t\treturn reply_raw\n\n\tdef shutdown(self):\n\t\t\"\"\" Racourci pour étiendre le canal\n\n\t\t\"\"\"\n\t\tself.set_config(0, \"%\", 0, 1)\n\n\tdef new(self, ser, spot_add, id, type, wl, max, manuf):\n\t\t\"\"\" Défini les paramètres du canal\n\n\t\t\"\"\"\n\t\tself.ser = ser\n\t\tself.ch_dict['address'] = spot_add\n\t\tself.ch_dict['id'] = id\n\t\tself.ch_dict['type'] = type\n\t\tself.ch_dict['wl'] = wl\n\t\tself.ch_dict['max'] = max\n\t\tself.ch_dict['manuf'] = manuf\n\t\tself.ch_dict['color'] = str(type)+\"_\"+str(wl)\n\t\tconfig = self.get_config()\n\t\tself.ch_dict['intensity'] = config['intensity']\n\t\tself.ch_dict['pwm_start'] = config['pwm_start']\n\t\tself.ch_dict['pwm_stop'] = config['pwm_stop']\n\t\tself.ch_dict['last_request'] = None\n\n\nclass Spot():\n\t\"\"\" Définit un spot sur le réseau via son numéro de série\n\n\tCharge les objets channels associés\n\tDifferentes fonctions de contrôle d'un spot\n\t\"\"\"\n\n\tdef __init__(self):\n\t\t\"\"\" Définit la liste des variables de base.\n\n\t\tValeur par défaut: None\n\t\t\"\"\"\n\t\tself.ser = None\n\t\tself.address = None\n\t\tself.grid_id = None\n\t\tself.group = None # not used\n\t\tself.network = None # not used\n\t\tself.pcb = {}\n\t\tself.cpu = None\n\t\tself.channels = None\n\t\tself.channels_color = {}\n\t\tself.available_colors = []\n\t\tself.symmetry = None\n\t\t# Recherche des fréquences (en Hz) disponibles (selon code source du driver, com. Pierre Jenard 17/09/18 10:41)\n\t\tself.available_freq = []\n\t\t'''\n\t\tfor i in range(1, 100001):\n\t\t\tperiods = [9600,6000,4800,3200]\n\t\t\tfor p in periods:\n\t\t\t\ttimerF = p*i/10\n\t\t\t\tpsc = int(48000000 / timerF)\n\t\t\t\tif timerF <= 48000000 and int(psc*timerF) == 48000000:\n\t\t\t\t\tself.available_freq.append(i/10)\n\t\tself.available_freq = sorted(list(set(self.available_freq)))\n\t\t'''\n\t\tself.frequency = None\n\t\tself.box = None\n\t\tself.errors = {}\n\n\tdef set_address(self, address):\n\t\t\"\"\" Défini l'adresse du spot sur le réseau\n\n\t\tL'adresse est fixée par le n° de série du spot\n\t\tet est comprise en 1 et 1000000.\n\t\t\"\"\"\n\n\t\ttry:\n\t\t\tint(address)\n\t\texcept:\n\t\t\tverbose(\"Spot address must be an integer (1-1000000)\", 8)\n\t\t\treturn\n\t\t\n\t\tif int(address) < 1 | int(address) > 1000000:\n\t\t\tverbose(\"Spot address must be comprised between 1 and 1000000\", 8)\n\t\t\treturn\n\n\t\tself.address = str(int(address)) # converti en str pour usage futur\n\t\treturn self.address\n\n\tdef get_address(self):\n\t\t\"\"\" Renvoi l'adresse du spot sur le réseau\n\n\t\t\"\"\"\n\t\treturn int(self.address)\n\n\tdef get_temp(self):\n\t\t\"\"\" Renvoi la température du CPU du driver et des cartes LED en °C\n\n\t\t\"\"\"\n\t\ttemp_dict = {\"cpu\": None, \"led_pcb_0\": None, \"led_pcb_1\": None, \"unit\": \"C\"}\n\t\treply = serial_dialog(self.ser, spot_cmd_dict[\"get_temperature\"][\"cmd\"], self.address)\n\t\tif reply['error'] == False:\n\t\t\ttemp = reply['reply'].split(\" \")\n\t\t\ttemp_dict['cpu'] = float(temp[0])\n\t\t\ttemp_dict[\"led_pcb_0\"] = float(temp[1])\n\t\t\ttemp_dict[\"led_pcb_1\"] = float(temp[2])\n\t\t\t\n\t\treturn temp_dict\n\n\tdef get_cpuinfo(self):\n\t\t\"\"\" Renvoie la version du firmware et le numéro de série du CPU\n\n\t\t\"\"\"\n\t\treply = serial_dialog(self.ser, spot_cmd_dict[\"get_cpu\"][\"cmd\"], self.address)\n\t\tif reply['error'] == False:\n\t\t\tcpu = {'firmware_version': reply['reply'].split(\" \")[0], 'serial':reply['reply'].split(\" \")[1]}\n\t\telse:\n\t\t\tcpu = None\n\t\treturn cpu\n\n\tdef get_pcbledinfo(self, pcb=[0,1]):\n\t\t\"\"\" Lit les informations dans la mémoire de chaque PCB Led\n\n\t\tRevoi une liste structurée (dictionaire)\n\t\t\"\"\"\n\t\tdef decode_pcbledinfo(string, pcb):\n\t\t\t\"\"\" Decode la chaine de caractères codée en hexadécimale\n\n\t\t\tSi données de plus de 8bits, inverser la lecture (par deux caractères)\n\t\t\tcar LSB first\n\t\t\t\"\"\"\n\t\t\t\n\t\t\t# Fonction qui regroupe les \"bits\" et les décode\n\t\t\tdef substring_decode(input, start, length, reverse, coding):\n\t\t\t\ttmp = input[start:(start+length)]\n\t\t\t\tif reverse == True: # pour les données de plus de 8 bits envoyées LSB first (voir doc)\n\t\t\t\t\ttmp.reverse()\n\t\t\t\ttmp = \"\".join(tmp)\n\t\t\t\tif coding == \"text\":\n\t\t\t\t\ttmp = bytearray.fromhex(tmp).decode()\n\t\t\t\tif coding == \"int\":\n\t\t\t\t\ttmp = int(tmp, 16)\n\t\t\t\tif coding == \"hex\":\n\t\t\t\t\ttmp = \"0x\"+tmp\n\t\t\t\treturn tmp\n\n\t\t\t# Dictionnaire pour la sortie\n\t\t\tinfo_dict = {}\n\n\t\t\t# Découpe de la chaine par deux caractères\n\t\t\tstring_splitted = [string[i:i+2] for i in range(0, len(string), 2)]\n\t\t\t\n\t\t\t# Information sur la carte LED\n\t\t\t#info_dict[\"raw_info_pcb_\"+str(pcb)] = string # pour debbogage\n\t\t\tinfo_dict[\"pcb\"]={}\n\t\t\tinfo_dict[\"pcb\"]['n'] = pcb\n\t\t\tinfo_dict[\"pcb\"]['crc'] = substring_decode(input=string_splitted, start=0, length=2, reverse=True, coding=\"hex\")\n\t\t\tinfo_dict[\"pcb\"]['type'] = substring_decode(input=string_splitted, start=2, length=2, reverse=True, coding=\"int\")\n\t\t\tinfo_dict[\"pcb\"]['serial'] = substring_decode(input=string_splitted, start=4, length=4, reverse=True, coding=\"hex\")\n\n\t\t\t# Informations des canaux\n\t\t\tinfo_len = 6 # nb bytes par canal\n\t\t\tnb_channels = int((len(string_splitted) - 8)/info_len) # recherche du nombre de canaux en fonction de la longueur de la chaine d'info (8 pour l'en-tête)\n\t\t\tinfo_dict['channels']={}\n\t\t\tfor i in range(0,nb_channels):\n\t\t\t\tinfo_dict['channels'][i]={}\n\t\t\t\tinfo_dict['channels'][i]['channel'] = i\n\t\t\t\tinfo_dict['channels'][i]['i_peek'] = substring_decode(input=string_splitted, start=8+i*info_len, length=1, reverse=False, coding=\"int\")\n\t\t\t\tinfo_dict['channels'][i]['manuf'] = substring_decode(input=string_splitted, start=8+i*info_len+1, length=1, reverse=False, coding=\"text\")\n\t\t\t\tinfo_dict['channels'][i]['led_type'] = substring_decode(input=string_splitted, start=8+i*info_len+2, length=2, reverse=False, coding=\"text\")\n\t\t\t\tinfo_dict['channels'][i]['wave_length'] = substring_decode(input=string_splitted, start=8+i*info_len+4, length=2, reverse=True, coding=\"int\")\n\t\t\t\n\t\t\t# Sortie\n\t\t\treturn info_dict\n\n\t\t# Lecture des informations de chaque carte (pcb)\n\t\treply={}\n\t\tfor i in pcb: # voir valeur par défaut dans les arguments de la fonction\n\t\t\treply_tmp = serial_dialog(self.ser, spot_cmd_dict[\"get_led\"][\"cmd\"], self.address, str(i))\n\t\t\tif reply_tmp['error'] == False:\n\t\t\t\treply[i] = decode_pcbledinfo(string=reply_tmp['reply'].split(\" \")[1], pcb=i) # décodage de la chaine\n\t\t\telse:\n\t\t\t\treply[i] = None\n\n\t\treturn reply\n\n\tdef load_channels(self, pcb=[0,1]):\n\t\t\"\"\" Crée une liste d'objets channels en fonction des informations lues dans la mémoire des PCB LED\n\n\t\t\"\"\"\n\t\tspot_info = self.get_pcbledinfo()\n\t\tself.channels = []\n\t\t# Configuration de chaque canal\n\t\tfor i in range(0, len(spot_info[0][\"channels\"])):\n\t\t\tfor key, value in spot_info[0][\"channels\"][i].items():\n\t\t\t\tself.symmetry = True\n\t\t\t\t\"\"\"\n\t\t\t\tfor j in range(0, len(spot_info)): # Vérifie la symétrie\n\t\t\t\t\tif value != spot_info[j][\"channels\"][i][key]:\n\t\t\t\t\t\tself.symmetry = False\n\t\t\t\t\"\"\"\n\t\t\tif self.symmetry == True:\n\t\t\t\tvalue = spot_info[0][\"channels\"][i]\n\t\t\t\tc = Channel()\n\t\t\t\tc.new(\tser= self.ser, spot_add = self.address, id = i,\n\t\t\t\t\t\ttype = value[\"led_type\"], wl = value[\"wave_length\"],\n\t\t\t\t\t\tmax = value[\"i_peek\"], manuf = value[\"manuf\"])\n\t\t\t\tself.channels.append(c)\n\t\t\t\tif c.get_ledinfo(\"color\") not in self.channels_color.keys():\n\t\t\t\t\tself.channels_color[c.get_ledinfo(\"color\")] = [c.get_ledinfo(\"id\")]\n\t\t\t\telse:\n\t\t\t\t\tself.channels_color[c.get_ledinfo(\"color\")].append(c.get_ledinfo(\"id\"))\n\t\t\t\t# Sauvegarde de la liste des couleurs disponibes\n\t\t\t\tself.available_colors = list(sorted(set(self.channels_color.keys())))\n\t\t\telse:\n\t\t\t\tc = Channel()\n\t\t\t\tc.ch_dict['id'] = i # force pour un canal vide\n\t\t\t\tself.channels.append(c) # empty channel\n\t\treturn\n\n\tdef get_status(self):\n\t\t\"\"\" Renvoi le status des 16 drivers LED\n\n\t\t\"\"\"\n\t\treply = serial_dialog(self.ser, spot_cmd_dict[\"get_status\"][\"cmd\"], self.address)\n\t\tif reply['error'] == False:\n\t\t\tdrivers_st = list(str(bin(int(reply['reply'].split(\" \")[1][2:], 16)))[2:]) # Hexa décimal en binaire = 16bits, 1 par canal = status\n\t\t\tdrivers_st_prod = 1\n\t\t\tdrivers_st_dict = {}\n\t\t\tfor i in range(0, len(drivers_st)):\n\t\t\t\tdrivers_st_dict[i] = int(drivers_st[i])\n\t\t\t\tdrivers_st_prod = drivers_st_prod * int(drivers_st[i])\n\t\t\tstatus = {\t'config': reply['reply'].split(\" \")[0],\n\t\t\t\t\t\t'drivers': {'global': drivers_st_prod, 'details': drivers_st_dict}\n\t\t\t\t\t\t}\n\t\telse:\n\t\t\t status = {'config': None, 'drivers': None}\n\n\t\treturn status\t\t\t\n\n\tdef get_freq(self):\n\t\t\"\"\" Renvoi la fréquence de l'horloge du spot\n\n\t\t\"\"\"\n\t\treply = serial_dialog(self.ser, spot_cmd_dict[\"get_frequence\"][\"cmd\"], self.address)\n\t\tif reply['error'] == False:\n\t\t\treturn int(reply['reply'])/10 # en Hz (voir doc)\n\t\telse:\n\t\t\treturn None\n\n\tdef set_freq(self, freq):\n\t\t\"\"\" Assigne une fréquence pour le PWM\n\n\t\t\"\"\"\n\t\tself.errors[\"set_freq\"] = True\n\t\tif freq not in self.available_freq:\n\t\t\tverbose(\"Frequency not available\", 8)\n\t\t\treturn\n\t\treply = serial_dialog(self.ser, spot_cmd_dict[\"set_frequence\"][\"cmd\"], self.address, freq*10) # itération par 1/10è de Hz (voir doc)\n\t\tself.frequency = self.get_freq()\n\t\tif reply['error'] == False and freq == self.frequency:\n\t\t\tself.errors[\"set_freq\"] = False\n\t\treturn self.frequency\n\n\tdef set_channel(self, conf):\n\t\t\"\"\" Contrôle un canal\n\n\t\t\"\"\"\n\t\t#self.channels[int(conf[\"channel\"])].pass_serial(self.ser)\n\t\treply = self.channels[int(conf[\"channel\"])].set_config(intensity=conf[\"intensity\"], unit=conf[\"unit\"], start=conf[\"start\"], stop=conf[\"stop\"])\n\t\treturn reply\n\n\tdef set_ms(self, master, state=0):\n\t\t\"\"\" Définit le rôle du spot: maître ou esclave\n\n\t\t\"\"\"\n\t\tif master == True:\n\t\t\treply1 = serial_dialog(self.ser, spot_cmd_dict[\"set_master\"][\"cmd\"], self.address, 1) # maître\n\t\telse:\n\t\t\treply1 = serial_dialog(self.ser, spot_cmd_dict[\"set_master\"][\"cmd\"], self.address, 0) #esclave\n\n\t\treply2 = serial_dialog(self.ser, spot_cmd_dict[\"set_state\"][\"cmd\"], self.address, state) # état du driver\n\t\treply3 = serial_dialog(self.ser, spot_cmd_dict[\"save_conf\"][\"cmd\"], self.address) # enregistre dans la mémoire du driver\n\t\t\n\t\treturn [reply1, reply2, reply3]\n\t\n\tdef set_state(self, state):\n\t\t\"\"\" Défini l'état des drivers\n\n\t\t\"\"\"\n\t\treply = serial_dialog(self.ser, spot_cmd_dict[\"set_state\"][\"cmd\"], self.address, state)\n\t\treturn reply\n\n\tdef shutdown(self):\n\t\t\"\"\" Eteind tous les canaux\n\n\t\t\"\"\"\n\t\treply = []\n\t\tfor c in self.channels:\n\t\t\t#c.pass_serial(self.ser)\n\t\t\treply.append(c.shutdown())\n\n\tdef set_bycolor(self, conf):\n\t\t\"\"\" Allume tout les canaux qui ont la même couleur\n\n\t\t\"\"\"\n\t\tif conf[\"colortype\"] not in self.channels_color.keys():\n\t\t\tverbose(\"Color '\"+conf[\"colortype\"]+\"' not available\", 8)\n\t\t\treturn -1\n\n\t\terror = 0\n\t\tfor i in self.channels_color[conf[\"colortype\"]]:\n\t\t\tconf[\"channel\"] = i\n\t\t\treply = self.set_channel(conf)\n\t\t\tif reply != 0:\n\t\t\t\terror += 1\n\t\treturn error\n\n\tdef get_info(self):\n\t\t\"\"\" Renvoi une liste détaillé du statut du spot\n\n\t\t\"\"\"\n\t\tinfos = {}\n\t\tinfos[\"firmware_version\"] = self.cpu[\"firmware_version\"]\n\t\tinfos[\"serial\"] = self.cpu[\"serial\"]\n\t\tinfos[\"frequency\"] = {'value': self.frequency, 'unit' : \"Hz\"}\n\t\tinfos[\"pcb\"]=self.pcb\n\t\tinfos['symmetry'] = self.symmetry\n\t\tinfos[\"temperature\"] = self.get_temp()\n\t\tinfos['status'] = self.get_status()\n\t\tinfos[\"channels\"] = {}\n\t\tfor c in self.channels:\n\t\t\tledinfos = c.get_ledinfo(\"all\")\n\t\t\tinfos[\"channels\"][ledinfos['id']] = ledinfos\n\t\t\t#infos[\"channels\"][ledinfos['id']]['driver_status'] = infos['status']['drivers']['details'][ledinfos['id']]\n\t\tinfos[\"library_version\"] = release\n\t\tinfos[\"available_colors\"] = self.available_colors\n\t\tinfos[\"available_frequencies\"] = self.available_freq\n\t\tinfos[\"address\"] = self.address\n\t\tinfos[\"id\"] = self.grid_id\n\t\tinfos[\"box\"] = self.box\n\t\treturn infos\n\n\tdef set_box(self, box):\n\t\t\"\"\" Groupe associé\n\n\t\t\"\"\"\n\t\tself.box = box\n\n\tdef get_function(self):\n\t\treply = serial_dialog(self.ser, spot_cmd_dict[\"get_function\"][\"cmd\"], self.address)\n\t\treturn reply\n\n\tdef new(self, address, ser, grid_id=None):\n\t\t\"\"\" Crée un objet à partir des fonctions de base\n\n\n\t\t\"\"\"\n\t\t# Adresse sur le réseau\n\t\taddress_reply = self.set_address(address)\n\t\tif str(address_reply) != str(address):\n\t\t\tverbose(\"Spot not found at address \"+str(address), 8)\n\t\t\treturn None\n\n\t\t# Port série\n\t\tself.ser = ser\n\n\t\t# id sur le réseau\n\t\tself.grid_id = grid_id\n\n\tdef activate(self):\n\t\tself.cpu = self.get_cpuinfo\t()\n\t\tself.frequency = self.get_freq() # Fréquence de l'horloge\n\t\tledinfo = self.get_pcbledinfo()\n\t\tfor k,v in ledinfo.items():\n\t\t\tif v is not None:\n\t\t\t\ttmp = v\n\t\tfor k in ledinfo.keys():\n\t\t\tself.pcb[str(k)] = tmp['pcb']\n\t\tself.load_channels() # Charge les canaux\n\n\t# def activate(self):\n # \tself.cpu = self.get_cpuinfo\t()\n # \tself.frequency = self.get_freq() # Fréquence de l'horloge\n # ledinfo = self.get_pcbledinfo()\n # for k,v in ledinfo.items():\n # if v is not None:\n # tmp = v\n # for k in ledinfo.keys():\n # self.pcb[str(k)] = tmp['pcb']\n # self.load_channels() # Charge les canaux\n\n\tdef activate2(self, config, avcol):\n\t\tself.available_colors = avcol\n\t\tself.channels = []\n\t\tkeys = []\n\t\tfor k in config.keys():\n\t\t\tkeys.append(int(k))\n\t\tkeys = sorted(keys)\n\t\t#for k,v in config.items():\n\t\tfor k in keys :\n\t\t\tk = str(k)\n\t\t\tv = config[k]\n\t\t\tc = Channel()\n\t\t\tc.ser = self.ser\n\t\t\tc.ch_dict = v\n\t\t\tif v['color'] not in self.channels_color.keys():\n\t\t\t\tself.channels_color[v['color']] = [v['id']]\n\t\t\telse:\n\t\t\t\tself.channels_color[v['color']].append(v['id'])\n\t\t\tself.channels.append(c)\n\nclass Grid():\n\t\"\"\" Définit le réseau de spots, caractérisé par un port série\n\n\t\"\"\"\n\n\tdef __init__(self):\n\t\t\"\"\" Déclare les varables de bases\n\n\t\t\"\"\"\n\t\tself.ser = None\n\t\tself.spots_list = []\n\t\tself.available_colors = []\n\t\tself.available_freq = []\n\t\tself.freq = None\n\t\tself.boxes = []\n\t\tself.out_of_boxes=[]\n\n\tdef set_serial(self, port, baudrate, timeout):\n\t\t\"\"\" Déclare les paramètres du port série\n\n\t\tport: par exemple /dev/ttyUSB0\n\t\tbaudrate: vitesse de communication, par défaut 115200\n\t\t\"\"\"\n\n\t\t# Vérifie la présence du port\n\t\ttry:\n\t\t\tf = open(port, \"r\")\n\t\texcept FileNotFoundError:\n\t\t\tverbose(\"Port '\"+port+\"' not found\", 8)\n\t\t\treturn\n\n\t\t# Vérifie le baudrate\n\t\ttry:\n\t\t\tint(baudrate)\n\t\texcept ValueError:\n\t\t\tverbose(\"Baudrate must be an integer\", 8)\n\t\t\treturn\n\n\t\t# Tente de configurer le port série + sauvegarde \n\t\ttry:\n\t\t\tself.ser = serial.Serial(port, int(baudrate), timeout=float(timeout))\n\t\texcept:\n\t\t\tverbose(\"Unable to set serial port on '\"+port+\"'\", 8)\n\t\t\treturn\n\n\t\t# Fermeture du port\n\t\ttry:\n\t\t\tself.ser.close()\n\t\texcept:\n\t\t\tverbose(\"Unable to close port after initialization\", 8)\n\t\t\treturn\n\n\t\treturn self.ser\n\n\tdef get_serial(self):\n\t\t\"\"\" Renvoi le port série\n\n\t\t\"\"\"\n\t\treturn self.ser\n\n\tdef open(self):\n\t\t\"\"\" Ouvre le port s��rie préfini avec set_serial\n\t\t\n\t\t\"\"\"\n\n\t\t# Vérifie que le port a été défini\n\t\tif self.ser == None:\n\t\t\tverbose(\"Serial port not define. Use set_serial first.\", 8)\n\t\t\treturn False\n\n\t\t# Ouverture du port\n\t\tif not self.ser.isOpen():\n\t\t\ttry:\n\t\t\t\tself.ser.open()\n\t\t\texcept:\n\t\t\t\tverbose(\"Unable to open serial port\", 8)\n\t\t\t\treturn False\n\t\treturn self.ser.isOpen()\n\n\tdef close(self):\n\t\t\"\"\" Ferme le port série ouvert avec open_serial\n\t\t\n\t\t\"\"\"\n\n\t\t# Vérifie que le port a été défini\n\t\tif self.ser == None:\n\t\t\tverbose(\"Serial port not define. Use set_serial first.\", 8)\n\t\t\treturn\n\n\t\t# Configuration le port\n\t\tif not self.ser.isOpen():\n\t\t\tverbose(\"Serial port already closed\", 8)\n\t\t\treturn\n\n\t\ttry:\n\t\t\tself.ser.close()\n\t\texcept:\n\t\t\tverbose(\"Unable to close serial port\", 8)\n\t\t\treturn\n\n\tdef find_spot(self):\n\t\ttm_save = self.ser.timeout\n\t\tself.ser.timeout = 0.1\n\t\tresult = {\"found\":[], \"not_found\":[]}\n\t\tfor s in self.spots_list:\n\t\t\treply = s.get_function()\n\t\t\tif reply[\"error\"] == False:\n\t\t\t\tresult['found'].append(int(s.address))\n\t\t\telse:\n\t\t\t\tresult['not_found'].append(int(s.address))\n\t\tself.ser.timeout = tm_save\n\t\treturn result\n\n\tdef add_spot(self, address, grid_id):\n\t\t\"\"\" Ajoute un spot à la liste du réseau\n\n\t\taddress: l'adresse du spot sur le réseau (type integer)\n\t\t\"\"\"\n\t\tif type(address) is int:\n\t\t\ts = Spot()\n\t\t\ts.new(ser = self.ser, address = address, grid_id = grid_id)\n\t\t\tself.spots_list.append(s) # ajoute le spot à la liste\n\t\t\t'''\n\t\t\tself.available_colors = sorted(list(set(self.available_colors + s.available_colors))) # ajoute les couleurs disponibles, et élimine les doublons\n\t\t\tself.available_freq = sorted(list(set(self.available_freq + s.available_freq))) # ajoute les fréquences disponibles, et élimine les doublons\n\t\t\t'''\n\t\telse:\n\t\t\tverbose(\"Invalid spot address '\"+str(address)+\"'\", 8)\n\n\tdef get_spot(self, value, target=\"id\"):\n\t\t\"\"\" retourne un objet spot pour le controler indépendament\n\n\t\t\"\"\"\n\t\tif target == \"id\":\n\t\t\treturn self.spots_list[value]\n\t\tif target == \"add\":\n\t\t\tfor s in self.spots_list:\n\t\t\t\tif str(s.address) == str(value):\n\t\t\t\t\treturn s\n\n\tdef set_freq(self, freq):\n\t\t\"\"\" Défini la fréquence du PWM de tous les spots\n\t\t\n\t\tfreq: fréquence en Hz\n\t\t\"\"\"\n\t\treply_freq = []\n\t\tfor s in self.spots_list:\n\t\t\ts.set_freq(freq = freq)\n\t\t\treply_freq.append(s.get_freq())\n\n\t\treply_freq = set(reply_freq)\n\t\tif len(reply_freq) == 1:\n\t\t\tself.freq = reply_freq\n\t\telse:\n\t\t\tself.freq = None\n\n\tdef set_bycolor(self, conf, box = None):\n\t\t\"\"\" Allume tout les canaux qui ont la même couleur\n\n\t\t\"\"\"\n\t\tif box == None: # tout le réseau\n\t\t\tspots = self.spots_list\n\t\telse:\n\t\t\tspots = self.boxes[box]\n\t\terror = 0\n\t\tfor s in spots:\n\t\t\tif conf[\"colortype\"] in s.available_colors:\n\t\t\t\treply = s.set_bycolor(conf)\n\t\t\t\tif reply > 0:\n\t\t\t\t\terror += 1\n\t\treturn error\n\n\tdef set_state(self, state, box=None):\n\t\tif box == None: # tout le réseau\n\t\t\tspots = self.spots_list\n\t\telse:\n\t\t\tspots = self.boxes[box]\n\t\terror = 0\n\t\tfor s in spots:\n\t\t\ts.set_state(state)\n\t\treturn error\n\n\tdef shutdown(self, box = None):\n\t\t\"\"\" Mets tous les spots en shutdown\n\n\t\tspots: liste des id des spots, si 'None': éteind tout\n\t\t\"\"\"\n\t\tif box == None: # éteind tout\n\t\t\tfor s in self.spots_list:\n\t\t\t\ts.shutdown()\n\t\t\treturn\n\t\tif box in self.boxes.keys(): \n\t\t\tfor s in self.boxes[box]:\n\t\t\t\ts.shutdown()\n\t\telse:\n\t\t\tverbose(\"Undefined box '\"+str(box)+\"'\", 8)\t\n\n\tdef new_boxes(self, n):\n\t\t\"\"\" Crèe n groupe\n\n\t\tn: nombre de groupe (max = nombre de spot sur la grille)\n\t\t\"\"\"\n\t\tif type(n) is not int:\n\t\t\tverbose(\"'n' must be an integer\", 8)\n\t\t\treturn\n\t\tif n > len(self.spots_list):\n\t\t\tverbose(\"Number of boxes greather than number of available spots\", 8)\n\t\t\treturn\n\t\tself.boxes = {}\n\t\tself.out_of_boxes=[]\n\t\tfor i in range(0, n):\n\t\t\tself.boxes[i] = []\n\t\tfor s in self.spots_list:\n\t\t\tself.out_of_boxes.append(s)\n\t\t\ts.set_box(None)\n\n\tdef add_spots_to_box(self, spots, box):\n\t\t\"\"\" Lie les spots à un groupe\n\n\t\t\"\"\"\n\t\tif box not in range(0, len(self.boxes)):\n\t\t\tverbose(\"Undefine box '\"+str(box)+\"'\", 8)\n\t\t\treturn\n\t\tfor i in spots:\n\t\t\tif i not in range(0, len(self.spots_list)):\n\t\t\t\tverbose(\"Undefine spot '\"+str(i)+\"'\", 8)\n\t\t\t\tcontinue\n\t\t\tif self.spots_list[i] not in self.boxes[box]:\n\t\t\t\t# Supprime de l'ancien groupe\n\t\t\t\tif self.spots_list[i].box != None:\n\t\t\t\t\tself.boxes[self.spots_list[i].box].remove(self.spots_list[i])\n\t\t\t\telse:\n\t\t\t\t\tself.out_of_boxes.remove(self.spots_list[i])\n\t\t\t\t# Ajoute au groupe\n\t\t\t\tself.boxes[box].append(self.spots_list[i])\n\t\t\t\tself.spots_list[i].set_box(box)\n\t\n\tdef remove_spots_from_box(self, spots, box):\n\t\t\"\"\" Retire les spots à un groupe\n\n\t\t\"\"\"\n\t\tif box not in range(0, len(self.boxes)):\n\t\t\tverbose(\"Undefine box '\"+str(box)+\"'\", 8)\n\t\t\treturn\n\t\tfor i in spots:\n\t\t\tif i not in range(0, len(self.spots_list)):\n\t\t\t\tverbose(\"Undefine spot '\"+str(i)+\"'\", 8)\n\t\t\t\tcontinue\n\t\t\tif self.spots_list[i] in self.boxes[box]:\n\t\t\t\t# Supprime de l'ancien groupe\n\t\t\t\tif self.spots_list[i].box != None:\n\t\t\t\t\tself.boxes[self.spots_list[i].box].remove(self.spots_list[i])\n\t\t\t\t\tself.out_of_boxes.append(self.spots_list[i])\n\n\tdef get_info(self):\n\t\t\"\"\" Revoi une liste structurée des infos des spots\n\n\t\t\"\"\"\n\t\treply = {}\n\t\treply[\"spots\"]={}\n\t\tfor i in range(0, len(self.spots_list)):\n\t\t\treply[\"spots\"][i] = self.spots_list[i].get_info()\n\t\treply[\"available_colors\"] = self.available_colors\n\t\treply[\"available_frequencies\"] = self.available_freq\n\t\treply[\"boxes\"] = {}\n\t\tfor i in range(0, len(self.boxes)):\n\t\t\treply[\"boxes\"][i] = []\n\t\t\tfor j in range(0, len(self.boxes[i])):\n\t\t\t\tverbose(self.boxes[i][j].address, 8)\n\t\t\t\treply[\"boxes\"][i].append(self.boxes[i][j].address)\n\t\treturn(reply)\n\n\tdef set_from_file(self, file, spots_add, port, baudrate=115200, timeout=10):\n\t\t\"\"\" Crèe un nouveau réseau à partir d'un fichier de configuration.\n\n\t\tContrairement à .new, ne charge pas la configuration depuis la mémoire des spots, mais depuis un fichier.\n\t\tValide la configuration via les numéros de série (driver+pcb)\n\t\t\"\"\"\n\n\t\tverbose(file, 8)\n\t\tself.ser = self.set_serial(port=port, baudrate=baudrate, timeout=timeout)\n\t\tif self.ser == None:\n\t\t\treturn\n\n\t\tspots_add = list(set(spots_add)) # adresse unique\n\t\tself.ser.open()\n\n\t\t# Ajoute les spots\n\t\tif self.ser.name == port: # port série correctement configuré\n\t\t\tfor i in range(0, len(spots_add)):\n\t\t\t\tif type(address) is int:\n\t\t\t\t\ts = Spot()\n\t\t\t\t\t\n\t\t\t\t\ts.new(ser = self.ser, address = address, grid_id = grid_id)\n\t\t\t\t\t\n\t\t\t\t\tself.spots_list.append(s) # ajoute le spot à la liste\n\t\t\t\t\tself.available_colors = sorted(list(set(self.available_colors + s.available_colors))) # ajoute les couleurs disponibles, et élimine les doublons\n\t\t\t\t\tself.available_freq = sorted(list(set(self.available_freq + s.available_freq))) # ajoute les fréquences disponibles, et élimine les doublons\n\t\t\t\telse:\n\t\t\t\t\tverbose(\"Invalid spot address '\"+str(address)+\"'\", 8)\n\n\tdef activate(self):\n\t\tfor s in self.spots_list:\n\t\t\ts.activate()\n\t\t\tself.available_colors = sorted(list(set(self.available_colors + s.available_colors))) # ajoute les couleurs disponibles, et élimine les doublons\n\t\t\tself.available_freq = sorted(list(set(self.available_freq + s.available_freq))) # ajoute les fréquences disponibles, et élimine les doublons\n\n\tdef activate2(self, config):\n\t\tfor s in self.spots_list:\n\t\t\tverbose(s.address, 8)\n\t\t\tfor k,v in config[\"spots\"].items():\n\t\t\t\tif int(v[\"address\"]) == int(s.address):\n\t\t\t\t\tcdict = config[\"spots\"][k][\"channels\"]\n\t\t\t\t\ts.activate2(cdict, avcol = config[\"spots\"][k][\"available_colors\"] )\n\t\tself.available_colors = config[\"spots\"][\"0\"][\"available_colors\"]\n\n\n\tdef new(self, spots_add, port, baudrate=115200, timeout=2):\n\t\t\"\"\" Crèe un nouveau réseau\n\n\t\t\"\"\"\n\t\t# Port Série\n\t\tself.ser = self.set_serial(port=port, baudrate=baudrate, timeout=timeout)\n\t\tif self.ser == None:\n\t\t\treturn\n\n\t\t# Ajoute les spots\n\t\tspots_add = list(set(spots_add)) # adresse unique\n\t\tself.ser.open()\n\t\tif self.ser.name == port: # port série correctement configuré\n\t\t\tfor i in range(0, len(spots_add)):\n\t\t\t\tself.add_spot(spots_add[i], grid_id = i)\n\t\telse:\n\t\t\tverbose(\"Serial port '\"+port+\"' is wrong\", 8)\n\t\tself.ser.close()\n","repo_name":"ptocquin/velire","sub_path":"public/bin/velire/velire.py","file_name":"velire.py","file_ext":"py","file_size_in_byte":31124,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"31978684378","text":"from client.messages.handlers import general\r\n\r\nimport json\r\n\r\nclass MessageHandler:\r\n\r\n async def handle_msg(self, client, line):\r\n try:\r\n decoded_line = await self.decode_json(line)\r\n function_name = decoded_line.pop('action').lower()\r\n\r\n module_functions = [curr_name for curr_name, func in general.__dict__.items() \\\r\n if hasattr(func, '__call__')]\r\n\r\n if function_name in module_functions:\r\n return await getattr(general, function_name)(client, **decoded_line)\r\n\r\n print(f'Action function {function_name} does not exist to handle')\r\n except TypeError:\r\n print('Could not parse invalid JSON message for action')\r\n \r\n async def encode_json(self, **kwargs):\r\n return json.dumps(kwargs, separators=(',', ':'))\r\n\r\n async def decode_json(self, line):\r\n return json.loads(line)\r\n ","repo_name":"its-tn10/paycom-pubsub-client","sub_path":"client/messages/messagehandler.py","file_name":"messagehandler.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"32461840703","text":"from urllib.request import urlopen\r\nfrom bs4 import BeautifulSoup\r\nimport csv\r\nfrom datetime import datetime\r\n\r\ndef writecsv(data):\r\n date = datetime.now().strftime('%Y-%m-%d')\r\n with open('excsv.csv','a',newline='',encoding='utf-8') as file:\r\n filewriter = csv.writer(file)\r\n filewriter.writerow(data)\r\n\r\nalldata = {}\r\n\r\ndef footballtable(season):\r\n url = 'https://www.sanook.com/sport/football/table/premierleague/20'+ str(season) + '-20' + str(season + 1) + '/'\r\n webopen = urlopen(url)\r\n html_page = webopen.read()\r\n webopen.close()\r\n data = BeautifulSoup(html_page,'html.parser')\r\n\r\n try:\r\n team = data.find('td',{\"class\":\"jsx-827658710\"})\r\n year = data.find('h1',{\"class\":\"jsx-1187604094\"})\r\n \r\n champ = team.text.strip()\r\n year = year.text\r\n alldata[champ] = year\r\n except:\r\n pass\r\n \r\n \r\nfor i in range(10,20):\r\n footballtable(i)\r\n \r\nfor k,v in alldata.items():\r\n data = [k,v]\r\n writecsv(data)\r\n \r\nprint('save')\r\n","repo_name":"Robotboy007/uncle03-webscraping","sub_path":"mudrik.py","file_name":"mudrik.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"18257758383","text":"from tkinter import *\nfrom random import *\nx_of_circle = 0\nsizes = [23,10,5,12,6,8,3]\ncolors = ['red', 'yellow', 'blue', 'grey70', 'purple', 'green', 'orange']\nokno = Tk()\nokno.title(\"Окно №1\")\nholst = Canvas(okno, width=300, height=300, bg='white')\nholst.pack()\nfor index in range(0,7):\n holst.create_oval(x_of_circle,100, x_of_circle+sizes[index],100+sizes[index], fill=colors[index])\n x_of_circle = x_of_circle + 20\n","repo_name":"kn0pkasanchouskoffeev/idle","sub_path":"2spiska/2spiska.py","file_name":"2spiska.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"12753372786","text":"# Program pecahan uang\n# Buku Siswa IKM Informatika untuk SMA Kelas XI Hal. 34\n# Aktivitas SAP-K11-06-U: Menukarkan Uang\n# Programmed by : Armansyah, S.Kom, M.Pd\n# Guru Informatika SMAN Sumatera Selatan \n# armansyah@smansumsel.sch.id\n# Alumni CS50 for Teachers Harvard-Indonesia 2022/2023\n# Setiap copy-paste dan pengembangan harus mencantumkan informasi HAKI diatas\n\n\ndef cari_kombinasi_minimal(nilai_target, pecahan):\n pecahan.sort(reverse=True) # Urutkan pecahan secara menurun\n kombinasi = []\n \n for pecahan_uang in pecahan:\n while nilai_target >= pecahan_uang:\n kombinasi.append(pecahan_uang)\n nilai_target -= pecahan_uang\n \n return kombinasi\n\ndef main():\n pecahan = [50000, 20000, 10000, 5000, 2000, 1000,500,100, 50]\n nilai_target = int(input(\"Masukkan nilai uang yang diinginkan (kelipatan ribuan): \"))\n \n if nilai_target % 1000 != 0:\n print(\"Masukkan nilai yang merupakan kelipatan ribuan.\")\n else:\n kombinasi = cari_kombinasi_minimal(nilai_target, pecahan)\n print(\"Kombinasi minimal pecahan uang yang diperlukan:\")\n print(kombinasi)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Armansyahmpd/Python-SMA-Kumer","sub_path":"penukaranuang.py","file_name":"penukaranuang.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"id","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"23447849721","text":"\"\"\"Test revrand models.\"\"\"\nimport numpy as np\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.decomposition import PCA\nfrom sklearn.base import clone\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV\n\nfrom revrand import StandardLinearModel, GeneralizedLinearModel\nfrom revrand.likelihoods import Gaussian, Binomial\nfrom revrand.basis_functions import LinearBasis, RandomRBF, RandomMatern52\nfrom revrand.metrics import smse\nfrom revrand.btypes import Parameter, Positive\n\n\ndef test_slm(make_gaus_data):\n\n X, y, Xs, ys = make_gaus_data\n\n basis = LinearBasis(onescol=False)\n\n slm = StandardLinearModel(basis)\n slm.fit(X, y)\n Ey = slm.predict(Xs)\n\n assert smse(ys, Ey) < 0.1\n\n basis = LinearBasis(onescol=False) \\\n + RandomRBF(nbases=10, Xdim=X.shape[1]) \\\n + RandomMatern52(nbases=10, Xdim=X.shape[1])\n\n slm = StandardLinearModel(basis)\n slm.fit(X, y)\n Ey = slm.predict(Xs)\n\n assert smse(ys, Ey) < 0.1\n\n\ndef test_pipeline_slm(make_gaus_data):\n\n X, y, Xs, ys = make_gaus_data\n\n slm = StandardLinearModel(LinearBasis(onescol=True))\n estimators = [('PCA', PCA()),\n ('SLM', slm)]\n pipe = Pipeline(estimators)\n\n pipe.fit(X, y)\n Ey = pipe.predict(Xs)\n assert smse(ys, Ey) < 0.1\n\n\ndef test_gridsearch_slm(make_gaus_data):\n\n X, y, Xs, ys = make_gaus_data\n\n slm = StandardLinearModel(LinearBasis(onescol=True))\n\n param_dict = {'var': [Parameter(v, Positive()) for v in [1.0, 2.0]]}\n estimator = GridSearchCV(slm, param_dict, n_jobs=-1)\n\n estimator.fit(X, y)\n Ey = estimator.predict(Xs)\n assert len(ys) == len(Ey) # we just want to make sure this all runs\n\n\ndef test_randomgridsearch_slm(make_gaus_data):\n\n X, y, Xs, ys = make_gaus_data\n\n slm = StandardLinearModel(LinearBasis(onescol=True))\n\n param_dict = {\n 'var': [Parameter(1.0 / v, Positive()) for v in range(1, 6)]\n }\n estimator = RandomizedSearchCV(slm, param_dict, n_jobs=-1, n_iter=2)\n\n estimator.fit(X, y)\n Ey = estimator.predict(Xs)\n assert len(ys) == len(Ey) # we just want to make sure this all runs\n\n\ndef test_glm_gaussian(make_gaus_data, make_random):\n\n X, y, Xs, ys = make_gaus_data\n\n basis = LinearBasis(onescol=True)\n lhood = Gaussian()\n\n # simple SGD\n glm = GeneralizedLinearModel(lhood, basis, random_state=make_random)\n glm.fit(X, y)\n Ey = glm.predict(Xs)\n assert smse(ys, Ey) < 0.1\n\n # Test BasisCat\n basis = LinearBasis(onescol=True) \\\n + RandomRBF(nbases=20, Xdim=X.shape[1]) \\\n + RandomMatern52(nbases=20, Xdim=X.shape[1])\n\n glm = GeneralizedLinearModel(lhood, basis, random_state=make_random)\n glm.fit(X, y)\n Ey = glm.predict(Xs)\n assert smse(ys, Ey) < 0.1\n\n # Test upper quantile estimates\n py, _, _ = glm.predict_cdf(Xs, 1e5)\n assert np.allclose(py, 1.)\n\n # Test log probability\n lpy, _, _ = glm.predict_logpdf(Xs, Ey)\n assert np.all(lpy > -100)\n\n EyQn, EyQx = glm.predict_interval(Xs, 0.9)\n assert all(Ey <= EyQx)\n assert all(Ey >= EyQn)\n\n\ndef test_glm_binomial(make_binom_data, make_random):\n # This is more to test the logic than to test if the model can overfit,\n # hence more relaxed SMSE. This is because this is a harder problem than\n # the previous case. We also haven't split training ans test sets, since we\n # want to check the latent function and bounds\n\n X, y, p, n = make_binom_data\n f = p * n\n\n basis = LinearBasis(onescol=True) \\\n + RandomRBF(nbases=20, Xdim=X.shape[1]) \\\n + RandomMatern52(nbases=20, Xdim=X.shape[1])\n lhood = Binomial()\n largs = (n,)\n\n # SGD\n glm = GeneralizedLinearModel(lhood, basis, random_state=make_random)\n glm.fit(X, y, likelihood_args=largs)\n Ey = glm.predict(X, likelihood_args=largs)\n\n assert smse(f, Ey) < 1\n\n # Test upper quantile estimates\n py, _, _ = glm.predict_cdf(X, 1e5, likelihood_args=largs)\n assert np.allclose(py, 1.)\n\n EyQn, EyQx = glm.predict_interval(X, 0.9, likelihood_args=largs)\n assert all(Ey <= EyQx)\n assert all(Ey >= EyQn)\n\n\ndef test_pipeline_glm(make_gaus_data, make_random):\n\n X, y, Xs, ys = make_gaus_data\n\n glm = GeneralizedLinearModel(Gaussian(), LinearBasis(onescol=True),\n random_state=make_random)\n estimators = [('PCA', PCA()),\n ('SLM', glm)\n ]\n pipe = Pipeline(estimators)\n\n pipe.fit(X, y)\n Ey = pipe.predict(Xs)\n assert smse(ys, Ey) < 0.1\n\n\ndef test_gridsearch_glm(make_gaus_data):\n\n X, y, Xs, ys = make_gaus_data\n\n glm = GeneralizedLinearModel(Gaussian(), LinearBasis(onescol=True),\n random_state=1, maxiter=100)\n\n param_dict = {'batch_size': [10, 20]}\n estimator = GridSearchCV(glm, param_dict, verbose=1, n_jobs=-1)\n\n estimator.fit(X, y)\n Ey = estimator.predict(Xs)\n assert len(ys) == len(Ey) # we just want to make sure this all runs\n\n\ndef test_randomgridsearch_glm(make_gaus_data):\n\n X, y, Xs, ys = make_gaus_data\n\n glm = GeneralizedLinearModel(Gaussian(), LinearBasis(onescol=True),\n random_state=1, maxiter=100)\n\n param_dict = {'batch_size': range(1, 11)}\n estimator = RandomizedSearchCV(glm, param_dict, verbose=1, n_jobs=-1,\n n_iter=2)\n\n estimator.fit(X, y)\n Ey = estimator.predict(Xs)\n assert len(ys) == len(Ey) # we just want to make sure this all runs\n\n\ndef test_sklearn_clone(make_gaus_data):\n\n X, y, Xs, ys = make_gaus_data\n\n basis = LinearBasis(onescol=True)\n slm = StandardLinearModel(basis=basis)\n glm = GeneralizedLinearModel(likelihood=Gaussian(), basis=basis,\n maxiter=100)\n\n slm_clone = clone(slm)\n glm_clone = clone(glm)\n\n slm_clone.fit(X, y)\n glm_clone.fit(X, y)\n\n # scalar values\n glm_keys = [\n 'K',\n 'batch_size',\n 'maxiter',\n 'nsamples',\n 'random_state',\n 'updater'\n ]\n\n for k in glm_keys:\n assert glm.get_params()[k] == glm_clone.get_params()[k]\n\n # Manually test likelihood objects\n assert glm_clone.likelihood.params.value == glm.likelihood.params.value\n\n # scalar values\n slm_keys = [\n 'maxiter',\n 'tol'\n ]\n\n for k in slm_keys:\n assert slm.get_params()[k] == slm_clone.get_params()[k]\n\n # Manually test variance objects\n assert slm_clone.var.value == slm.var.value\n","repo_name":"NICTA/revrand","sub_path":"tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":6449,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"77"}
+{"seq_id":"40770876796","text":"import pandas as pd\r\nimport os\r\n\r\nclass CSV_Processor():\r\n def __init__(self):\r\n self.white_policy_eventlog = {'task_ID':[], 'transition':[], 'skip': [], \"make king\": []}\r\n self.red_policy_eventlog = {'task_ID':[], 'transition':[], 'skip': [], \"make king\": []}\r\n self.policy_dir = \"D:/XAI Process Mining Research/Python-Checkers-AI/RL policy traces\"\r\n\r\n # for each epsidoe, we extract tasks IDs and corresponding events\r\n # we generate our event log through combining all epsiodes' task IDs and events \r\n def process_policies(self):\r\n\r\n red_counter = 0\r\n white_counter = 0\r\n\r\n for file in os.listdir(self.policy_dir):\r\n full_path = self.policy_dir + f\"/{file}\"\r\n df = pd.read_csv(full_path)\r\n\r\n for tuple in df.itertuples():\r\n current_position = tuple[2]\r\n next_position = tuple[3]\r\n skip = tuple[4]\r\n reward = tuple[5]\r\n\r\n if reward % 10 == 0:\r\n king = False\r\n elif reward % 4 == 0:\r\n king = True\r\n\r\n transistion = (current_position, next_position, skip, king)\r\n\r\n if \"red\" in file:\r\n self.red_policy_eventlog['task_ID'].append(red_counter)\r\n self.red_policy_eventlog['transition'].append(transistion)\r\n red_counter += 1\r\n\r\n elif \"white\" in file:\r\n self.white_policy_eventlog['task_ID'].append(white_counter)\r\n self.white_policy_eventlog['transition'].append(transistion)\r\n white_counter += 1 \r\n\r\n df = pd.DataFrame(self.white_policy_eventlog)\r\n df.to_csv(f\"D:/XAI Process Mining Research/Taxi Environment/RL policy event log/white_policy_eventlog.csv\")\r\n\r\n df = pd.DataFrame(self.red_policy_eventlog)\r\n df.to_csv(f\"D:/XAI Process Mining Research/Taxi Environment/RL policy event log/red_policy_eventlog.csv\")","repo_name":"qyy752457002/Explainable-AI","sub_path":"Python-Checkers-AI/process_files.py","file_name":"process_files.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"13872030688","text":"# Import-commands\r\nimport json\r\nimport methodes\r\n\r\ndef help():\r\n print(\"Valid commands:\")\r\n print(\"- new - add new 'item' to current list\")\r\n print(\"- del
- remove 'item' from current list\")\r\n print(\"- store
save current list as 'listname'\")\r\n print(\"- show show content of current list\")\r\n print(\"- continue end editing of list and get a random item back\")\r\n print(\"- back back to the main menu\")\r\n print(\"- exit close the application\")\r\n print(\"- help show this help message\")\r\n\r\ndef start(data_file_path):\r\n print(\"\\n= Initialize fastmode =\\n\")\r\n\r\n # Method spezific variable\r\n list = []\r\n\r\n help()\r\n\r\n while(True):\r\n # get input\r\n user_input = input(\"\\n>> \")\r\n\r\n # add new item\r\n if \"new \" in user_input:\r\n if user_input.replace(\"new \", \"\") == \"\":\r\n print(\"Please name an item to add.\")\r\n continue\r\n else:\r\n list = methodes.new_item(list, user_input)\r\n\r\n # delete item\r\n elif \"del \" in user_input:\r\n if user_input.replace(\"del \", \"\") == \"\":\r\n print(\"Please name an item to delete.\")\r\n continue\r\n else:\r\n list = methodes.del_item(list, user_input)\r\n\r\n # save list\r\n elif \"store \" in user_input:\r\n if user_input.replace(\"store \", \"\") == \"\":\r\n print(\"Please name a list.\")\r\n else:\r\n listname = user_input.replace(\"store \", \"\")\r\n\r\n if methodes.check_listname(listname, data_file_path):\r\n while(True):\r\n user_input = input(\"A list with this name already exists. Do you want to overwrite it? y/n\")\r\n\r\n if user_input == \"y\":\r\n data = methodes.load(data_file_path)\r\n\r\n print(\"Saving in progress...\")\r\n\r\n data.update({listname: list})\r\n\r\n methodes.save(data, data_file_path)\r\n\r\n print(f\"List {listname} saved.\")\r\n break\r\n\r\n elif user_input == \"n\":\r\n print(\"Overwriting list exited.\")\r\n break\r\n else:\r\n print(\"Error: Command not found.\")\r\n continue\r\n\r\n else:\r\n data = methodes.load(data_file_path)\r\n\r\n print(\"Saving in progress...\")\r\n\r\n data.update({listname: list})\r\n\r\n methodes.save(data, data_file_path)\r\n\r\n print(f\"List {listname} is saved.\")\r\n\r\n # show current list content\r\n elif user_input == \"show\":\r\n methodes.show(list)\r\n\r\n # close editing of list and continue with random selection\r\n elif user_input == \"continue\":\r\n if len(list) == 0:\r\n print(\"Well, you are a funny person, there are no items in this list yet! Better start adding some...\")\r\n else:\r\n # selects a random item\r\n methodes.random_selector(list)\r\n break\r\n\r\n # abort fastmode and return to main menu\r\n elif user_input == \"back\":\r\n break\r\n\r\n # exit the application\r\n elif user_input == \"exit\":\r\n methodes.exit_app()\r\n\r\n # shows all valid commands\r\n elif user_input == \"help\":\r\n help()\r\n\r\n # no valid command\r\n else:\r\n print(\"Error: Command not found.\\n\\n\")\r\n\r\n print(\"Exit fastmode\\n\")\r\n","repo_name":"Nebelwald/Decider","sub_path":"fastmode.py","file_name":"fastmode.py","file_ext":"py","file_size_in_byte":3804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"74148227447","text":"# -*- coding: UTF-8 -*-\nfrom dataStructure import TreeNode\nfrom dataStructure import ListNode\n\n\ndef sortedListToBST(head):\n \"\"\"\n 109. 有序链表转换二叉搜索树\n 思路:遍历求长度,递归创建树\n :type head: ListNode\n :rtype: TreeNode\n \"\"\"\n\n def create(tmp, l, r):\n if l > r:\n return None\n mid = (l + r) // 2 # 因为已经有序,平衡二叉树选取列表中点作为根节点就可以\n root = TreeNode.TreeNode(tmp[mid])\n root.left = create(tmp, l, mid - 1)\n root.right = create(tmp, mid + 1, r)\n return root\n\n p = head\n tmp = []\n while p:\n tmp.append(p.val)\n p = p.next\n\n return create(tmp, 0, len(tmp) - 1)\n\n\ndef isBalanced(root):\n \"\"\"\n 110. 平衡二叉树\n 递归解决 -1 代表不是平衡二叉树\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n\n def find(root):\n if not root:\n return 0\n left = find(root.left)\n right = find(root.right)\n if left == -1 or right == -1:\n return -1\n if abs(left - right) > 1:\n return -1\n return 1 + left if left > right else 1 + right\n\n if find(root) == -1:\n return False\n return True\n\n\ndef minDepth(root):\n \"\"\"\n 111. 二叉树的最小深度\n 递归求深度当子节点为0的时候不应该参与计算\n :type root: TreeNode\n :rtype: int\n \"\"\"\n\n def find(root):\n if not root:\n return 0\n left = find(root.left)\n right = find(root.right)\n if left == 0:\n return right + 1\n if right == 0:\n return left + 1\n return min(left + 1, 1 + right)\n\n return find(root)\n\n\ndef hasPathSum(root, sum):\n \"\"\"\n 112. 路径总和(review)\n :type root: TreeNode\n :type sum: int\n :rtype: bool\n \"\"\"\n if root == None:\n return False\n if root.left or root.right:\n res = hasPathSum(root.left, sum - root.val) or hasPathSum(root.right, sum - root.val)\n return res\n elif sum - root.val == 0:\n return True\n else:\n return False\n\n\ndef pathSum(root, sum):\n \"\"\"\n 113. 路径总和 II\n :type root: TreeNode\n :type sum: int\n :rtype: List[List[int]]\n \"\"\"\n res = []\n\n def find(root, t, tmp):\n if root.val + t == sum:\n if not root.left and not root.right:\n res.append(tmp + [root.val])\n\n if root.left:\n find(root.left, t + root.val, tmp + [root.val])\n if root.right:\n find(root.right, t + root.val, tmp + [root.val])\n\n if not root:\n return []\n find(root, 0, [])\n return res\n\n\ndef flatten(root):\n \"\"\"\n 114. 二叉树展开为链表\n :type root: TreeNode\n :rtype: void Do not return anything, modify root in-place instead.\n \"\"\"\n\n def dfs(root):\n if not root:\n return None\n left = dfs(root.left)\n right = dfs(root.right)\n if left:\n left.right = root.right\n root.right = root.left\n root.left = None\n if right:\n return right\n if left:\n return left\n return root\n\n dfs(root)\n\n\ndef rightSideView(root):\n \"\"\"\n 199. 二叉树的右视图\n 队列\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n if not root:\n return []\n queue, res = [root], []\n\n while queue:\n lens = len(queue)\n for i in range(lens):\n tmp = queue.pop(0)\n if tmp.right:\n queue.append(tmp.right)\n if tmp.left:\n queue.append(tmp.left)\n if i == 0:\n res.append(tmp.val)\n return res\n\n\ndef lowestCommonAncestor(root, p, q):\n \"\"\"\n 235. 二叉搜索树的最近公共祖先(review)\n :type root: TreeNode\n :type p: TreeNode\n :type q: TreeNode\n :rtype: TreeNode\n \"\"\"\n # if not root \\\n # or (p.val < root.val and q.val > root.val) \\\n # or (p.val > root.val and q.val < root.val) \\\n # or root.val == p.val \\\n # or root.val == q.val:\n # return root\n #\n # if p.val > root.val:\n # return lowestCommonAncestor(root.right, p, q)\n # else:\n # return lowestCommonAncestor(root.left, p, q)\n if root.val > p.val and root.val > q.val:\n return lowestCommonAncestor(root.left, p, q)\n elif root.val < p.val and root.val < q.val:\n return lowestCommonAncestor(root.right, p, q)\n return root\n\n\nif __name__ == '__main__':\n # head = ListNode.ListNode(1)\n # head.next = ListNode.ListNode(2)\n # head.next.next = ListNode.ListNode(3)\n # head.next.next.next = ListNode.ListNode(4)\n # head.next.next.next.next = ListNode.ListNode(5)\n # mid = head.next.next.next.next\n # mid.next = ListNode.ListNode(6)\n\n root = TreeNode.TreeNode(2)\n root.left = TreeNode.TreeNode(1)\n root.right = TreeNode.TreeNode(3)\n # root.left.left = TreeNode.TreeNode(0)\n # root.left.right = TreeNode.TreeNode(4)\n # root.right.left = TreeNode.TreeNode(7)\n # root.right.right = TreeNode.TreeNode(9)\n # root.left.left.left = TreeNode.TreeNode(-1)\n print(lowestCommonAncestor(root, TreeNode.TreeNode(3), TreeNode.TreeNode(1)))\n","repo_name":"fuyao-w/PYAlgorithmsAndDataStructures","sub_path":"dataStructure/DSCodeFive.py","file_name":"DSCodeFive.py","file_ext":"py","file_size_in_byte":5258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"14990479005","text":"# BST Traversal\n# 🟠Medium\n#\n# https://www.algoexpert.io/questions/bst-traversal\n#\n# Tags: Binary Tree - Binary Search Tree\n\nimport timeit\n\nfrom utils.binary_tree import BinaryTree\n\n\n# Use the definition of the tree traversals to recursively call the\n# functions and append values to the input array in the correct order.\n#\n# Time complexity: O(n) - On each of the traversals we will visit each\n# node once.\n# Space complexity: O(h) - On each of the traversals, the call stack\n# will grow to the height of the tree, this would be log(n) on the best\n# case, a perfectly balanced tree, to O(n) in the worst case, a totally\n# skewed tree.\nclass Recursive:\n def inOrderTraverse(self, tree, array):\n if tree:\n # Explore left subtree, then the root, then right subtree.\n self.inOrderTraverse(tree.left, array)\n array.append(tree.value)\n self.inOrderTraverse(tree.right, array)\n return array\n\n def preOrderTraverse(self, tree, array):\n if tree:\n # Explore the root, the left subtree, then right subtree.\n array.append(tree.value)\n self.preOrderTraverse(tree.left, array)\n self.preOrderTraverse(tree.right, array)\n return array\n\n def postOrderTraverse(self, tree, array):\n if tree:\n # Explore the left subtree, the right subtree, then the root.\n self.postOrderTraverse(tree.left, array)\n self.postOrderTraverse(tree.right, array)\n array.append(tree.value)\n return array\n\n\nclass UseBinaryTreeFn:\n def inOrderTraverse(self, tree, array):\n return BinaryTree(tree).inOrderTraverse()\n\n def preOrderTraverse(self, tree, array):\n return BinaryTree(tree).preOrderTraverse()\n\n def postOrderTraverse(self, tree, array):\n return BinaryTree(tree).postOrderTraverse()\n\n\ndef test():\n executors = [\n Recursive,\n UseBinaryTreeFn,\n ]\n tests = [\n [\"[]\", [], [], []],\n [\"[1]\", [1], [1], [1]],\n [\"[1,null,4]\", [1, 4], [1, 4], [4, 1]],\n [\n \"[10,5,15,2,5,13,22,1,null,null,null,null,14]\",\n [1, 2, 5, 5, 10, 13, 14, 15, 22],\n [10, 5, 2, 1, 5, 15, 13, 14, 22],\n [1, 2, 5, 5, 14, 13, 22, 15, 10],\n ],\n ]\n for executor in executors:\n start = timeit.default_timer()\n for _ in range(1):\n for col, t in enumerate(tests):\n sol = executor()\n root = BinaryTree.fromStringArray(t[0]).getRoot()\n inorder = sol.inOrderTraverse(root, [])\n preorder = sol.preOrderTraverse(root, [])\n postorder = sol.postOrderTraverse(root, [])\n assert inorder == t[1], (\n f\"\\033[93m» {inorder} <> {t[1]}\\033[91m for\"\n + f\" test {col} inorder using \\033[1m{executor.__name__}\"\n )\n assert preorder == t[2], (\n f\"\\033[93m» {preorder} <> {t[2]}\\033[91m for\"\n + f\" test {col} preorder using \\033[1m{executor.__name__}\"\n )\n assert postorder == t[3], (\n f\"\\033[93m» {postorder} <> {t[3]}\\033[91m for\"\n + f\" test {col} postorder using \\033[1m{executor.__name__}\"\n )\n stop = timeit.default_timer()\n used = str(round(stop - start, 5))\n cols = \"{0:20}{1:10}{2:10}\"\n res = cols.format(executor.__name__, used, \"seconds\")\n print(f\"\\033[92m» {res}\\033[0m\")\n\n\ntest()\n","repo_name":"raul-sauco/coding-challenges","sub_path":"algoexpert/bst-traversal.py","file_name":"bst-traversal.py","file_ext":"py","file_size_in_byte":3557,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"7466820653","text":"import os\nimport time\nimport subprocess\nimport keyboard\nimport matplotlib.pyplot as plt\nimport psutil\nimport platform\n\n\ndef getinfo():\n cpuhigh = 0\n gpuhigh = 0\n nvmehigh = 0\n vcorehigh = 0\n vbathigh = 0\n systinhigh = 0\n cputinhigh = 0\n auxtin0high = 0\n auxtin2high = 0\n smbusmasterhigh = 0\n gpumemhigh = 0\n memhigh = 0\n cpuusehigh = 0\n cpufreqhigh = 0\n cpugraph = []\n cpuusegraph = []\n gpugraph = []\n nvmegraph = []\n smbusgraph = []\n timelist = []\n memgraph = []\n timenum = 0 \n uname = platform.uname()\n\n system = subprocess.getoutput('neofetch | grep x86')\n system = system[-25:-12]\n\n cpucount = psutil.cpu_count()\n totram = round(psutil.virtual_memory().total / 1000000000, 3)\n architecture = uname.processor\n\n while True:\n if not keyboard.is_pressed('q'):\n timenum += 0.01\n timelist.append(timenum)\n\n cpufreq = psutil.cpu_freq()[0]\n cpufreq = round(cpufreq / 1000, 1)\n if cpufreq > cpufreqhigh:\n cpufreqhigh = cpufreq\n\n cpuusage = psutil.cpu_percent(0.1)\n if cpuusage > cpuusehigh:\n cpuusehigh = cpuusage\n cpuusegraph.append(cpuusage)\n\n memusage = psutil.virtual_memory()[3]\n memusage = round(memusage / 1000000000, 2)\n if memusage > memhigh:\n memhigh = memusage\n memgraph.append(psutil.virtual_memory()[2])\n\n cputemp = subprocess.getoutput('sensors | grep Tccd1')\n cputemp = float(cputemp[-8:-4])\n if cputemp > cpuhigh:\n cpuhigh = cputemp\n cpugraph.append(cputemp)\n\n gputemp = subprocess.getoutput('nvidia-smi | grep %')\n gputemp = float(gputemp[8:10])\n if gputemp > gpuhigh:\n gpuhigh = gputemp\n gpugraph.append(gputemp)\n\n gpumem = subprocess.getoutput('nvidia-smi | grep %')\n gpumem = float(gpumem[36:40])\n if gpumem > gpumemhigh:\n gpumemhigh = gpumem\n\n nvmetemp = subprocess.getoutput('sensors | grep Composite')\n nvmetemp = float(nvmetemp[15:19])\n if nvmetemp > nvmehigh:\n nvmehigh = nvmetemp\n nvmegraph.append(nvmetemp)\n\n vcore = subprocess.getoutput('sensors | grep in0')\n vcore = float(vcore[25:29])\n if vcore > vcorehigh:\n vcorehigh = vcore\n\n vbat = subprocess.getoutput('sensors | grep in8')\n vbat = float(vbat[25:29])\n if vbat > vbathigh:\n vbathigh = vbat\n\n systin = subprocess.getoutput('sensors | grep SYSTIN')\n systin = float(systin[25:29])\n if systin > systinhigh:\n systinhigh = systin\n\n cputin = subprocess.getoutput('sensors | grep CPUTIN')\n cputin = float(cputin[25:29])\n if cputin > cputinhigh:\n cputinhigh = cputin\n\n auxtin0 = subprocess.getoutput('sensors | grep AUXTIN0')\n auxtin0 = float(auxtin0[25:29])\n if auxtin0 > auxtin0high:\n auxtin0high = auxtin0\n\n auxtin2 = subprocess.getoutput('sensors | grep AUXTIN2')\n auxtin2 = float(auxtin2[25:29])\n if auxtin2 > auxtin2high:\n auxtin2high = auxtin2\n\n smbusmaster = subprocess.getoutput('sensors | grep SMBUSMASTER')\n smbusmaster = float(smbusmaster[25:29])\n if smbusmaster > smbusmasterhigh:\n smbusmasterhigh = smbusmaster\n smbusgraph.append(smbusmaster)\n \n os.system('clear')\n print('-------------------------------------------------------------------------------')\n print('GPU temp: {}C | HIGH: {}C GPU mem: {}MB | High: {}MB'.format(gputemp, gpuhigh, gpumem, gpumemhigh))\n print('-------------------------------------------------------------------------------')\n print('CPU temp: {}C | HIGH: {}C CPU usage: {}% | HIGH: {}%'.format(cputemp, cpuhigh, cpuusage, cpuusehigh))\n print('CPU freq {}Ghz | High: {}GHz Vcore: {}V | HIGH: {}V'.format(cpufreq, cpufreqhigh, vcore, vcorehigh))\n print('-------------------------------------------------------------------------------')\n print('Mem used {}GB | High: {}GB NVME temp: {}C | HIGH: {}C'.format(memusage, memhigh, nvmetemp, nvmehigh))\n print('-------------------------------------------------------------------------------')\n print('Vbat: {}V | HIGH: {}V'.format(vbat, vbathigh))\n print('-------------------------------------------------------------------------------')\n print('SYSTIN: {}C | HIGH: {}C CPUTIN: {}C | HIGH: {}C'.format(systin, systinhigh, cputin, cputinhigh))\n print('-------------------------------------------------------------------------------')\n print('AUXTIN0: {}C | HIGH: {}C AUXTIN2: {}C | HIGH: {}C'.format(auxtin0, auxtin0high, auxtin2, auxtin2high))\n print('-------------------------------------------------------------------------------')\n print('SMBUSMASTER: {}C | HIGH: {}C'.format(smbusmaster, smbusmasterhigh))\n print('-------------------------------------------------------------------------------')\n print('='*30, 'System Info', '='*30)\n print('CPU Count: {} Total RAM: {}GB'.format(cpucount, totram))\n print('System: {} Architecture: {}'.format(system, architecture))\n print('Press Q to exit')\n time.sleep(0.01)\n else:\n print('Generating graph...')\n time.sleep(1)\n plt.plot(timelist, cpugraph, label='CPU')\n plt.plot(timelist, gpugraph, label='GPU')\n plt.plot(timelist, nvmegraph, label='NVME')\n plt.plot(timelist, smbusgraph, label='SMBUSMASTER')\n plt.plot(timelist, cpuusegraph, label='CPU Usage')\n plt.plot(timelist, memgraph, label='Memory Usage %')\n plt.ylabel('Temp(C) / Usage %')\n plt.axis([0, timelist[-1], 0, 100])\n plt.legend()\n plt.show()\n os.system('clear')\n exit()\n \n\n\ngetinfo()\n\n\n#made by https://github.com/BoomanWill\n","repo_name":"BoomanWill/HW-Monitor-Pop_OS","sub_path":"hwmonitor.py","file_name":"hwmonitor.py","file_ext":"py","file_size_in_byte":6495,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"12370849408","text":"__revision__ = \"$Id$\"\n\nfrom invenio.search_engine import get_creation_date\n\ndef format(bfo, format='%Y-%m-%d'):\n '''\n Get the record creation date.\n @param format: The date format in MySQL syntax\n '''\n recID = bfo.recID\n out = get_creation_date(recID, format)\n return out\n","repo_name":"lbjay/cds-invenio","sub_path":"modules/bibformat/lib/elements/bfe_creation_date.py","file_name":"bfe_creation_date.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"27099183089","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution:\n def __init__(self):\n self.ans = float(\"-inf\")\n\n def maxPathSum(self, root: TreeNode) -> int:\n self.getMaxPath(root)\n return self.ans\n\n def getMaxPath(self, node: TreeNode) -> int:\n lm = rm = 0\n now = node.val\n if node.left != None:\n lm = self.getMaxPath(node.left)\n if lm+node.val > now:\n now = lm+node.val\n if node.right != None:\n rm = self.getMaxPath(node.right)\n if rm+node.val > now:\n now = rm+node.val\n m = lm+rm+node.val\n if m>now:\n if m>self.ans:\n self.ans = m\n else:\n if now>self.ans:\n self.ans = now\n return now\n","repo_name":"0xtinyuk/LeetCode","sub_path":"Algorithms/124. Binary Tree Maximum Path Sum.py","file_name":"124. Binary Tree Maximum Path Sum.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"65129560","text":"from app import db\r\nfrom datetime import datetime\r\nfrom sqlalchemy.sql.functions import current_timestamp\r\n\r\n\r\ndefault = {\r\n 'updated_at': datetime.now(),\r\n}\r\n\r\nclass DBConfig(db.Model):\r\n id = db.Column(db.Integer, primary_key=True)\r\n updated_at = db.Column(db.DateTime, server_default=current_timestamp())\r\n\r\n @classmethod\r\n def get(cls):\r\n obj = cls.query.get(1)\r\n if obj == None:\r\n obj = cls()\r\n for k, v in default.items():\r\n setattr(obj, k, v)\r\n db.session.add(obj)\r\n db.session.commit()\r\n return obj\r\n\r\n def to_dict(self):\r\n return {\r\n 'id': self.id,\r\n 'updated_at': self.updated_at,\r\n }\r\n","repo_name":"akiraak/localfood-server","sub_path":"server/models/db_config.py","file_name":"db_config.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"3688379401","text":"import os, pickle, glob\nfrom pathlib import Path\n\"\"\"\nexport \n(1) paths to code, data, models\n(2) items - abide_lbl_items, cross_lbl_items, all_lbl_items\n(3) getd (train & valid transforms in transforms.py)\n\"\"\"\n\n############## PATHS #####################################\n# Paths to (1) code (2) data\ncode_src = \"/gpfs/home/gologr01\"\ndata_src = \"/gpfs/data/oermannlab/private_data/DeepPit\"\n\n# stored code\ndeepPit_src = f\"{code_src}/DeepPit\"\nobelisk_src = f\"{code_src}/OBELISK\"\n\n# stored data\nmodel_src = f\"{data_src}/saved_models\"\nlabel_src = f\"{data_src}/PitMRdata/samir_labels\"\nABIDE_src = f\"{data_src}/PitMRdata/ABIDE\"\n\n# saved metadata\ndsetmd_src = f\"{data_src}/saved_dset_metadata\"\n\n# stored runs Tensorboard\nrun_src = f\"{data_src}/runs\"\n\n############## LABEL ITEMS #####################################\ncross_lbl_folders = [\"PPMI_full\", \"ICMB_full\", \"ADNI1_full\", \"AIBL_full\", \"ABVIB_full\"]\ncross_lbl_folders = [f\"{label_src}/{folder}\" for folder in cross_lbl_folders]\n\nabide_lbl_folders = [\"50373-50453\", \"50313-50372\", \"50213-50312\", \"50155-50212\", \"50002-50153\"]\nabide_lbl_folders = [f\"{label_src}/{folder}\" for folder in abide_lbl_folders]\n\ndef get_las_n4(file):\n nii_paths = glob.glob(f\"{file}/*.nii\") \n las_n4_niis = [nii for nii in nii_paths if \"las_n4\" in nii or \"las_corrected_n4\" in nii]\n assert(len(las_n4_niis) == 1)\n return las_n4_niis[0]\n\n# for abide\n# make a dictionary of key = train folder, value = (segm obj, nii file) \ndef get_data_dict_las_n4(train_path):\n train_folders = os.listdir(train_path)\n train_data_dict = {}\n for folder in train_folders:\n segm_obj_path = os.path.join(train_path, folder, \"seg.pt\")\n\n mp_path = os.path.join(train_path, folder, \"MP-RAGE\")\n folder1_path = os.path.join(mp_path, os.listdir(mp_path)[0])\n folder2_path = os.path.join(folder1_path, os.listdir(folder1_path)[0])\n\n # choose corrected_n4 if available\n nii_path = get_las_n4(folder2_path)\n train_data_dict[folder] = (nii_path, segm_obj_path) #(segm_obj_path, nii_path)\n return train_data_dict\n\n# Get ABIDE data dict\nabide_data = {}\nfor folder in abide_lbl_folders: abide_data.update(get_data_dict_las_n4(folder))\n\n# Convert data dict => items (path to MR, path to Segm tensor)\nabide_lbl_items = list(abide_data.values())\nprint(f\"Full lbl items: {len(abide_lbl_items)}\")\n\n# remove bad label 50132\nabide_weird_lbls = [50132, 50403]\ndef is_weird(fn): return any([str(lbl) in fn for lbl in abide_weird_lbls])\n \nabide_lbl_items = [o for o in abide_lbl_items if not is_weird(o[0])]\nprint(f\"Removed {len(abide_weird_lbls)} weird, new total lbl items: {len(abide_lbl_items)}\")\n\n# train/valid/test\nwith open(f\"{data_src}/saved_dset_metadata/split_train_valid_test.pkl\", 'rb') as f:\n train_idxs, valid_idxs, test_idxs, train_items, valid_items, test_items = pickle.load(f)\n tr_len, va_len, te_len = len(train_items), len(valid_items), len(test_items)\n print(\"train, valid, test\", tr_len, va_len, te_len, \"total\", tr_len + va_len + te_len)\n \n# train_items = [items[i] for i in train_idxs]\n# valid_items = [items[i] for i in valid_idxs]\n# test_items = [items[i] for i in test_idxs]\n\n# Open matched segs = (seg_folder, mr_folder)\nwith open(f\"{dsetmd_src}/first_418_matched_segs.txt\", \"r\") as f:\n lst = f.read().splitlines()\n # str to tuple\n cross_mr_paths, cross_seg_paths = zip(*[eval(s) for s in lst])\n \n# Get cross-dset data dict\ncross_lbl_items = [(get_las_n4(mr), f\"{seg}/seg.pt\") for mr, seg in zip(cross_mr_paths, cross_seg_paths)]\n\nall_lbl_items = abide_lbl_items + cross_lbl_items\nall_test_lbl_items = test_items + cross_lbl_items\nprint(f\"Cross label items: \", len(cross_lbl_items))\nprint(f\"All label items: \", len(all_lbl_items), f\"(abide ({len(abide_lbl_items)}) + cross_lbl ({len(cross_lbl_items)}))\")\nprint(f\"Test label items: \", len(all_test_lbl_items), f\"(test ({len(test_items)}) + cross_lbl ({len(cross_lbl_items)}))\")\n\ndef getd(items): return [{\"image\": mr_path, \"label\": f\"{Path(mk_path).parent}/seg.nii\"} for mr_path, mk_path in items]","repo_name":"RGologorsky/DeepPit","sub_path":"helpers/items_constants.py","file_name":"items_constants.py","file_ext":"py","file_size_in_byte":4098,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"6400994228","text":"#!/usr/bin/env python3\n\ndef extract_numbers(s):\n lst = s.split()\n lst2 = []\n for e in lst:\n try:\n e = int(e)\n except ValueError:\n try:\n e = float(e)\n except ValueError:\n pass #skip, not an int or float\n else:\n lst2.append(e)\n else:\n lst2.append(e)\n \n\n return lst2\n\ndef main():\n print(extract_numbers(\"abd 123 1.2 test 13.2 -1\"))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"DU-ds/PythonDataAnalysisCourse","sub_path":"hy-data-analysis-with-python-summer-2019/part02-e10_extract_numbers/src/extract_numbers.py","file_name":"extract_numbers.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"2787076004","text":"import openpyxl\n\nwb = openpyxl.load_workbook('sample_file.xlsx')\n\nsheet = wb.active\n\nx1 = sheet['A1']\nx2 = sheet['A2']\n# using cell() function\nx3 = sheet.cell(row=3, column=1)\n\nprint(\"The first cell value:\", x1.value)\nprint(\"The second cell value:\", x2.value)\nprint(\"The third cell value:\", x3.value)\n","repo_name":"7anojmj/manoj_python","sub_path":"Lectures/Lecture 14 Monday, September 13, 2021/CS384 Python Programming- Module 07- CSV Handling- Lec 12 - Excel Opening -4.py","file_name":"CS384 Python Programming- Module 07- CSV Handling- Lec 12 - Excel Opening -4.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"6800895009","text":"from django import template\n\nfrom ..models import BlogListingPage, BlogDetailPage\n\nregister = template.Library()\n\n@register.inclusion_tag(\"sportsblog/include/categories.html\", takes_context=True)\ndef get_all_categories(context):\n categories = BlogListingPage.objects.live().public().all()\n context['categories'] = categories\n return context\n\n@register.inclusion_tag(\"sportsblog/include/blogs.html\", takes_context=True)\ndef get_top_five_blogs(context):\n blogs = BlogDetailPage.objects.live().public().order_by('-first_published_at')[:5]\n context['blogs'] = blogs\n return context\n","repo_name":"Dexteritymedia/blog","sub_path":"sportsblog/templatetags/sportsblog_tags.py","file_name":"sportsblog_tags.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"41822653348","text":"import time\nimport requests\ndef sarahah_post(user, msg):\n s = requests.Session()\n\n homeurl = 'https://' + user + '.sarahah.com/'\n home = s.get(homeurl)\n\n csrftoken = home.text.split(\n ' int:\n if len(prices) == 1:\n return 0\n left,right = 0,1\n maxProfit = 0\n\n while right < len(prices):\n if prices[left] < prices[right]:\n profit = prices[right] - prices[left]\n maxProfit = max(maxProfit, profit)\n else:\n left =right\n right +=1\n return maxProfit","repo_name":"sunruyun2/leetcodePractice","sub_path":"121.BestTimeToBuyAndSellStock.py","file_name":"121.BestTimeToBuyAndSellStock.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"29474221753","text":"\"\"\"\nDag for fifth lesson, where we use BranchOperator and plugins for our task.\nWe search for top-3 locations in cartoon 'Rick and Mortey'.\n\"\"\"\n\nfrom airflow import DAG\nimport psycopg2\nfrom airflow.operators.postgres_operator import PostgresOperator\nfrom airflow.providers.postgres.hooks.postgres import PostgresHook\nfrom airflow.operators.dummy import DummyOperator\nfrom airflow.operators.python import BranchPythonOperator\nfrom airflow.utils.dates import days_ago\nfrom a_gunicheva_16_plugins.a_gunicheva_16_Top3Location import GunichevaTopLocationsOperator\n\nDEFAULT_ARGS = {\n 'start_date': days_ago(1),\n 'owner': 'a-gunicheva-16'\n}\n\ndag = DAG(\"a-gunicheva_16-lesson-5\",\n default_args=DEFAULT_ARGS,\n max_active_runs=1,\n tags=['a-gunicheva-16']\n )\n\nget_top_3_locations = GunichevaTopLocationsOperator(\n task_id='get_top_3_locations',\n top_number=3,\n dag=dag\n )\n\ndef is_table_exists():\n get_sql = f\"select * from a_gunicheva_16_ram_location\"\n\n pg_hook = PostgresHook(postgres_conn_id='conn_greenplum_write') # инициализируем хук\n conn = pg_hook.get_conn() # берём из него соединение\n cursor = conn.cursor(\"cursor_name\") # и именованный (необязательно) курсор\n try:\n cursor.execute(get_sql)\n return 'clear_table'\n except psycopg2.errors.UndefinedTable:\n print(\"таблица не существует, можно создать новую\")\n locked = True\n return 'all_ok'\n \n \n\nexists_branch = BranchPythonOperator(\n task_id='exists_branch',\n python_callable=is_table_exists,\n dag=dag)\n\ncreate_table = PostgresOperator(\n task_id='create_table',\n postgres_conn_id='conn_greenplum_write',\n trigger_rule='one_success',\n sql='''\n create table if not exists \n a_gunicheva_16_ram_location (\n id SERIAL4 PRIMARY KEY,\n name VARCHAR NOT NULL,\n type VARCHAR NOT NULL,\n dimension VARCHAR NOT NULL,\n residents_cnt INT4 NOT NULL);\n ''',\n dag=dag\n)\n\nall_ok = DummyOperator(task_id='all_ok', dag=dag)\n\nclear_table = PostgresOperator(\n task_id='clear_table',\n postgres_conn_id='conn_greenplum_write',\n trigger_rule='all_done',\n sql='drop table a_gunicheva_16_ram_location',\n dag=dag\n )\n\nwrite_locations = PostgresOperator(\n task_id='write_locations',\n postgres_conn_id='conn_greenplum_write',\n trigger_rule='all_success',\n sql='''\n insert into a_gunicheva_16_ram_location VALUES \n {{ ti.xcom_pull(task_ids='get_top_3_locations', key='return_value') }}\n ''',\n dag=dag\n )\n\nget_top_3_locations >> exists_branch >> [all_ok, clear_table] >> create_table >> write_locations\n","repo_name":"skarfex/education.courses_data_engineer","sub_path":"karpov_airflow_fullrep/dags/a-gunicheva-16/a-gunicheva-16-lesson-5.py","file_name":"a-gunicheva-16-lesson-5.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"73050154809","text":"import random\nimport os\nfrom pytimedinput import timedInput\n# from services.snake_service import *\n\n\nclass GameService:\n DIRECTIONS = {\n 'w': (-1, 0),\n 's': (1, 0),\n 'd': (0, 1),\n 'a': (0, -1)\n\n }\n\n @classmethod\n def generate_random_apple(cls, gameObj):\n apple_x = random.randint(1, gameObj.dimension[0] - 1)\n apple_y = random.randint(1, gameObj.dimension[1] - 1)\n while (apple_x, apple_y) in gameObj.snake.snake_coordinates:\n apple_x = random.randint(1, gameObj.dimension[0] - 1)\n apple_y = random.randint(1, gameObj.dimension[1] - 1)\n return apple_x, apple_y\n\n @classmethod\n def update_apple_pos(cls, gameObj):\n gameObj.apple = cls.generate_random_apple(gameObj)\n\n @classmethod\n def print_game(cls, gameObj):\n os.system('cls')\n for i in range(gameObj.dimension[0]):\n for j in range(gameObj.dimension[1]):\n if i == 0 or j == 0 or i == gameObj.dimension[0] - 1 or j == gameObj.dimension[1] - 1:\n print('#', end=' ')\n elif (i, j) in gameObj.snake.snake_coordinates:\n print('X', end=' ')\n elif (i, j) == gameObj.apple:\n print('a', end=' ')\n else:\n print(' ', end=' ')\n print()\n\n @classmethod\n def validate(cls, game_obj):\n return all([(0 < sc[0] < game_obj.dimension[0]-1 and 0 < sc[1] < game_obj.dimension[1]-1) for sc in game_obj.snake.snake_coordinates])\n\n @classmethod\n def update_snake_head(cls, game_obj, direction):\n\n snake_head = game_obj.snake.snake_coordinates[-1]\n new_snake_head = (cls.DIRECTIONS[direction][0] + snake_head[0], cls.DIRECTIONS[direction][1] + snake_head[1])\n # if new_snake_head is same as apple increase the length of the snake by 1 i.e just push new snake head\n if new_snake_head == game_obj.apple:\n game_obj.snake.snake_coordinates.append(new_snake_head)\n GameService.update_apple_pos(game_obj)\n # else pop tail and push new snake_head\n else:\n game_obj.snake.snake_coordinates.pop(0)\n game_obj.snake.snake_coordinates.append(new_snake_head)\n\n @classmethod\n def start_game(cls, game_obj):\n game_obj.apple = cls.generate_random_apple(game_obj)\n cls.print_game(game_obj)\n last_input = 'd'\n while 1:\n # i is input and 1s is timeout\n i, timed_out = timedInput(\"\", 0.3)\n if i == 'q':\n print('Your score : {}'.format(game_obj.get_score()))\n break\n elif i != last_input and i in cls.DIRECTIONS.keys():\n # if get head of snake, and append updated snake head so that snake size increases by 1\n cls.update_snake_head(game_obj, i)\n last_input = i\n\n cls.print_game(game_obj)\n else:\n # if no input, move snake in last imput direction\n\n cls.update_snake_head(game_obj, last_input)\n cls.print_game(game_obj)\n snake_head = game_obj.snake.snake_coordinates[-1]\n if not cls.validate(game_obj):\n print('Your score : {}'.format(game_obj.get_score()))\n break\n\n","repo_name":"iadityakumar/snakeGame","sub_path":"services/game_service.py","file_name":"game_service.py","file_ext":"py","file_size_in_byte":3329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"8085278598","text":"from nltk import word_tokenize, pos_tag\nfrom nltk.stem import WordNetLemmatizer\nimport spacy\nimport os\nimport string\nimport functools\nfrom copy import deepcopy\nfrom ..engine.utils import print_time_info\n\n\ndef T2TData(\n data_dir, is_spacy, is_lemma, fold_attr,\n use_punct, min_length=-1, train=True):\n raw_text, sf_data = transform_data(data_dir, fold_attr, train)\n text = parse_text(raw_text, is_spacy)\n input_data, input_attr_seqs, output_labels = \\\n build_dataset(text, is_lemma, use_punct, min_length)\n\n temp = input_data[0]\n refs_list = []\n temp_refs = []\n for i, ref in zip(input_data, output_labels):\n if i != temp:\n for _ in range(len(temp_refs)):\n refs_list.append(temp_refs)\n temp_refs = [ref]\n else:\n temp_refs.append(ref)\n temp = i\n for _ in range(len(temp_refs)):\n refs_list.append(temp_refs)\n\n return input_data, input_attr_seqs, output_labels, refs_list, sf_data\n\n\ndef transform_data(data_dir, fold_attr, train):\n if train:\n lines_file = os.path.join(data_dir, \"trainset.csv\")\n else:\n lines_file = os.path.join(data_dir, \"testset.csv\")\n data = list()\n with open(lines_file, 'r', encoding='utf-8') as file:\n for i, line in enumerate(file):\n if len(line.split('\"')) >= 3 and i > 0:\n attributes = line.split('\"')[1].strip('\"')\n s = line.replace(\"\\\"{}\\\",\".format(attributes), \"\") \\\n .replace(\"\\n\", \"\")\n attributes = attributes.split(',')\n attributes = [\n [\n i.strip().split('[')[0],\n i.strip().split('[')[1].strip(']')\n ] for i in attributes]\n # trim all punctuation marks in one line\n seq = functools.reduce(\n lambda s, c: s.replace(c, ''), string.punctuation, s)\n data.append([attributes, seq])\n\n for idx, d in enumerate(data):\n for a_idx, attr_pair in enumerate(d[0]):\n data[idx][0][a_idx][1] = attr_pair[1].replace(\"£\", \"\")\n data[idx][1] = d[1].replace(\"£\", \"\")\n data[idx][1] = data[idx][1].replace(\"2030\", \"20 30\")\n data[idx][1] = data[idx][1].replace(\"2025\", \"20 25\")\n data[idx][1] = data[idx][1].replace(\"2530\", \"25 30\")\n\n sf_data = []\n if fold_attr:\n for idx, d in enumerate(data):\n for a_idx, attr_pair in enumerate(d[0]):\n data[idx][0][a_idx][1] = attr_pair[1].lower()\n data[idx][1] = data[idx][1].lower()\n sf_data.append(d[0])\n sf_data_list = deepcopy(sf_data)\n for idx, d in enumerate(data):\n split_sent = d[1].split()\n data[idx][1] = ' '.join(split_sent)\n\n sf_data = []\n for sf in sf_data_list:\n temp = dict()\n for attr_pair in sf:\n temp[attr_pair[0]] = attr_pair[1]\n sf_data.append(temp)\n\n return data, sf_data\n\n\ndef parse_text(raw_text, is_spacy):\n text = []\n '''\n if is_spacy:\n spacy_parser = spacy.load('en')\n '''\n for idx, dialog in enumerate(raw_text):\n if idx % 1000 == 0:\n print_time_info(\n \"Processed {}/{} text\".format(\n idx, len(raw_text)))\n spacy_parsed_dialog = []\n nltk_parsed_dialog = []\n # encoder input\n spacy_parsed_dialog.append(dialog[0])\n # output label\n line = dialog[1]\n spacy_line, nltk_line = [], []\n if is_spacy:\n line = [\n [word] for word in line.split()\n ]\n spacy_parsed_dialog.append(line)\n else:\n nltk_line = pos_tag(word_tokenize(line), tagset='universal')\n nltk_line = [\n [d[0], d[1]]\n if d[1] != '.' else [d[0], 'PUNCT']\n for d in nltk_line]\n nltk_parsed_dialog.append(nltk_line)\n\n if spacy_parsed_dialog != []:\n text.append(spacy_parsed_dialog)\n else:\n text.append(nltk_parsed_dialog)\n\n return text\n\n\ndef build_dataset(text, is_lemma, use_punct, min_length):\n input_data = []\n input_attr_seqs = []\n output_labels = []\n spacy_parser = spacy.load('en')\n for idx, dialog in enumerate(text):\n if idx % 1000 == 0:\n print_time_info(\"{}/{}\".format(idx, len(text)))\n attrs = []\n attrs_seq = []\n for attr_pair in dialog[0]:\n attrs_seq.append(attr_pair[0])\n attrs_seq.append(attr_pair[1])\n attrs.append('{}:{}'.format(attr_pair[0], attr_pair[1]))\n input_data.append(attrs)\n input_attr_seqs.append(attrs_seq)\n output_label = []\n for w in dialog[1]:\n output_label.append(w[0])\n\n output_labels.append(deepcopy(output_label))\n\n if min_length == -1:\n print_time_info(\n \"No minimal length, data count: {}\".format(len(text)))\n else:\n print_time_info(\"Minimal length is {}\".format(min_length))\n idxs = []\n for idx, sent in enumerate(input_data):\n if len(output_labels[idx]) > min_length:\n idxs.append(idx)\n input_data = [input_data[i] for i in idxs]\n input_attr_seqs = [input_attr_seqs[i] for i in idxs]\n output_labels = [output_labels[i] for i in idxs]\n print_time_info(\"Data count: {}\".format(len(idxs)))\n return input_data, input_attr_seqs, output_labels\n","repo_name":"scofield7419/StruMatchDL","sub_path":"data/T2TData.py","file_name":"T2TData.py","file_ext":"py","file_size_in_byte":5506,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"77"}
+{"seq_id":"20499945969","text":"\"\"\"\n# String Methods\n • Python has a built-in string class named str\n • The built-in string class (str) has a set of built-in methods that we can use\n • A string object is immutable, methods of string cannot change the original string, therefore, they return new values\n\n\"\"\"\n\n\n\n# capitalize(): Converts the first character of the string to uppercase.\noriginal_string = \"hello world\"\ncapitalized_string = original_string.capitalize()\nprint(capitalized_string) # Output: \"Hello world\"\n\n# casefold(): Returns a casefolded version of the string, suitable for case-insensitive comparisons.\noriginal_string = \"HELLO\"\ncasefolded_string = original_string.casefold()\nprint(casefolded_string) # Output: \"hello\"\n\n# center(width): Returns a centered string within a specified width.\noriginal_string = \"Python\"\ncentered_string = original_string.center(10)\nprint(centered_string) # Output: \" Python \"\n\n# count(substring): Returns the number of occurrences of a substring in the string.\noriginal_string = \"banana\"\ncount_occurrences = original_string.count(\"a\")\nprint(count_occurrences) # Output: 3\n\n# encode(encoding): Returns an encoded version of the string using the specified encoding.\noriginal_string = \"hello\"\nencoded_string = original_string.encode(\"utf-8\")\nprint(encoded_string) # Output: b'hello'\n\n# endswith(suffix): Checks if the string ends with a specified suffix.\noriginal_string = \"world\"\nends_with_ld = original_string.endswith(\"ld\")\nprint(ends_with_ld) # Output: True\n\n# expandtabs(tabsize): Expands tabs in the string to a specified number of spaces.\noriginal_string = \"tab\\texample\"\nexpanded_string = original_string.expandtabs(4)\nprint(expanded_string) # Output: \"tab example\"\n\n# find(substring): Returns the lowest index of the substring in the string, or -1 if not found.\noriginal_string = \"hello\"\nindex_of_l = original_string.find(\"l\")\nprint(index_of_l) # Output: 2\n\n# format(*args, **kwargs): Formats the string using the supplied arguments and keyword arguments.\nformatted_string = \"{} {}\".format(\"Hello\", \"world\")\nprint(formatted_string) # Output: \"Hello world\"\n\n# format_map(mapping): Formats the string using a mapping of keys to values.\nformatted_string = \"{name} is {age} years old\".format_map({\"name\": \"Alice\", \"age\": 30})\nprint(formatted_string) # Output: \"Alice is 30 years old\"\n\n# index(substring): Returns the lowest index of the substring in the string, or raises an error if not found.\noriginal_string = \"hello\"\nindex_of_e = original_string.index(\"e\")\nprint(index_of_e) # Output: 1\n\n# isalnum(): Checks if all characters in the string are alphanumeric.\nalphanumeric_string = \"abc123\"\nis_alnum = alphanumeric_string.isalnum()\nprint(is_alnum) # Output: True\n\n# isalpha(): Checks if all characters in the string are alphabetic.\nalpha_string = \"abc\"\nis_alpha = alpha_string.isalpha()\nprint(is_alpha) # Output: True\n\n# isascii(): Checks if all characters in the string are ASCII.\nascii_string = \"hello\"\nis_ascii = ascii_string.isascii()\nprint(is_ascii) # Output: True\n\n# isdecimal(): Checks if all characters in the string are decimal.\ndecimal_string = \"123\"\nis_decimal = decimal_string.isdecimal()\nprint(is_decimal) # Output: True\n\n# isdigit(): Checks if all characters in the string are digits.\nnumeric_string = \"123\"\nis_digit = numeric_string.isdigit()\nprint(is_digit) # Output: True\n\n# isidentifier(): Checks if the string is a valid identifier.\nidentifier_string = \"variable_name\"\nis_identifier = identifier_string.isidentifier()\nprint(is_identifier) # Output: True\n\n# islower(): Checks if all characters in the string are lowercase.\nlowercase_string = \"hello\"\nis_lower = lowercase_string.islower()\nprint(is_lower) # Output: True\n\n# isnumeric(): Checks if all characters in the string are numeric.\nnumeric_string = \"123\"\nis_numeric = numeric_string.isnumeric()\nprint(is_numeric) # Output: True\n\n# isprintable(): Checks if all characters in the string are printable.\nprintable_string = \"Hello\\nWorld\"\nis_printable = printable_string.isprintable()\nprint(is_printable) # Output: False\n\n# isspace(): Checks if all characters in the string are whitespaces.\nwhitespace_string = \" \"\nis_space = whitespace_string.isspace()\nprint(is_space) # Output: True\n\n# istitle(): Checks if the string is in title case.\ntitle_string = \"Title Case\"\nis_title = title_string.istitle()\nprint(is_title) # Output: True\n\n# isupper(): Checks if all characters in the string are uppercase.\nuppercase_string = \"HELLO\"\nis_upper = uppercase_string.isupper()\nprint(is_upper) # Output: True\n\n# join(iterable): Joins the elements of an iterable (e.g., a list) with the string as a separator.\nwords = [\"apple\", \"orange\", \"banana\"]\njoined_string = \"-\".join(words)\nprint(joined_string) # Output: \"apple-orange-banana\"\n\n# ljust(width): Left-aligns the string within a specified width.\noriginal_string = \"hello\"\nleft_aligned_string = original_string.ljust(10)\nprint(left_aligned_string) # Output: \"hello \"\n\n# lower(): Converts all characters in the string to lowercase.\noriginal_string = \"Hello\"\nlowercase_string = original_string.lower()\nprint(lowercase_string) # Output: \"hello\"\n\n# lstrip(): Removes leading whitespaces from the string.\noriginal_string = \" hello\"\nleft_stripped_string = original_string.lstrip()\nprint(left_stripped_string) # Output: \"hello\"\n\n# maketrans(x[, y[, z]]): Returns a translation table for use in translate() method.\ntranslation_table = str.maketrans(\"aeiou\", \"12345\")\noriginal_string = \"hello\"\ntranslated_string = original_string.translate(translation_table)\nprint(translated_string) # Output: \"h2ll4\"\n\n# partition(separator): Splits the string at the first occurrence of the separator and returns a tuple.\noriginal_string = \"apple,orange,banana\"\npartitioned_tuple = original_string.partition(\",\")\nprint(partitioned_tuple) # Output: ('apple', ',', 'orange,banana')\n\n# replace(old, new): Replaces occurrences of a specified substring with another substring.\noriginal_string = \"Hello, World!\"\nnew_string = original_string.replace(\"Hello\", \"Hi\")\nprint(new_string) # Output: \"Hi, World!\"\n\n# rfind(substring): Returns the highest index of the substring in the string, or -1 if not found.\noriginal_string = \"hello\"\nrindex_of_l = original_string.rfind(\"l\")\nprint(rindex_of_l) # Output: 3\n\n# rindex(substring): Returns the highest index of the substring in the string, or raises an error if not found.\noriginal_string = \"hello\"\nrindex_of_e = original_string.rindex(\"e\")\nprint(rindex_of_e) # Output: 1\n\n# rjust(width): Right-aligns the string within a specified width.\noriginal_string = \"hello\"\nright_aligned_string = original_string.rjust(10)\nprint(right_aligned_string) # Output: \" hello\"\n\n# rpartition(separator): Splits the string at the last occurrence of the separator and returns a tuple.\noriginal_string = \"apple,orange,banana\"\nrpartitioned_tuple = original_string.rpartition(\",\")\nprint(rpartitioned_tuple) # Output: ('apple,orange', ',', 'banana')\n\n# rsplit([separator[, maxsplit]]): Splits the string from the right at the specified separator.\noriginal_string = \"apple orange banana\"\nrsplit_list = original_string.rsplit(\" \", 1)\nprint(rsplit_list) # Output: ['apple orange', 'banana']\n\n# rstrip(): Removes trailing whitespaces from the string.\noriginal_string = \"hello \"\nright_stripped_string = original_string.rstrip()\nprint(right_stripped_string) # Output: \"hello\"\n\n# split([separator[, maxsplit]]): Splits the string at the specified separator.\noriginal_string = \"apple,orange,banana\"\nsplit_list = original_string.split(\",\")\nprint(split_list) # Output: ['apple', 'orange', 'banana']\n\n# splitlines([keepends]): Splits the string at line breaks and returns a list of lines.\noriginal_string = \"Hello\\nWorld\"\nsplit_lines_list = original_string.splitlines()\nprint(split_lines_list) # Output: ['Hello', 'World']\n\n# startswith(prefix): Checks if the string starts with a specified prefix.\noriginal_string = \"Hello, World!\"\nstarts_with_hello = original_string.startswith(\"Hello\")\nprint(starts_with_hello) # Output: True\n\n# strip(): Removes leading and trailing whitespaces from the string.\noriginal_string = \" hello \"\nstripped_string = original_string.strip()\nprint(stripped_string) # Output: \"hello\"\n\n# swapcase(): Swaps the case of all characters in the string.\noriginal_string = \"Hello, World!\"\nswapped_case_string = original_string.swapcase()\nprint(swapped_case_string) # Output: \"hELLO, wORLD!\"\n\n# title(): Converts the first character of each word to uppercase.\noriginal_string = \"hello world\"\ntitle_case_string = original_string.title()\nprint(title_case_string) # Output: \"Hello World\"\n\n# translate(table): Applies a translation table to the string.\ntranslation_table = str.maketrans(\"aeiou\", \"12345\")\noriginal_string = \"hello\"\ntranslated_string = original_string.translate(translation_table)\nprint(translated_string) # Output: \"h2ll4\"\n\n# upper(): Converts all characters in the string to uppercase.\noriginal_string = \"hello\"\nuppercase_string = original_string.upper()\nprint(uppercase_string) # Output: \"HELLO\"\n\n# zfill(width): Pads the string with zeros on the left to a specified width.\noriginal_string = \"42\"\nzfilled_string = original_string.zfill(5)\nprint(zfilled_string) # Output: \"00042\"\n","repo_name":"hsnakd/Python_Bootcamp","sub_path":"day02/00_string_methods_with_examples.py","file_name":"00_string_methods_with_examples.py","file_ext":"py","file_size_in_byte":9188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"798509707","text":"import time\n\nimport pytest\n\nfrom pgdoc_datatype_parser import pgdoc_datatypes, versions\n\nfrom tests.conftest import _asserter\n\n\ndef assert_datatype_name(value):\n _asserter.non_empty_string(value)\n\n\ndef assert_aliases(value):\n if value is not None:\n if isinstance(value, list):\n assert len(value) > 0\n for v in value:\n _asserter.non_empty_string(v)\n else:\n _asserter.non_empty_string(value)\n\n\ndef asser_description(value):\n _asserter.non_empty_string(value)\n\n\n@pytest.mark.parametrize(\"version\", versions())\ndef test_release(version):\n datatypes, max_attemps, attempts, err = (None, 10, 0, None)\n while max_attemps > attempts:\n try:\n datatypes = pgdoc_datatypes(version=version)\n except Exception as exception:\n attempts += 1\n err = exception\n time.sleep(1)\n else:\n err = None\n break\n if err:\n raise err\n for dtname, dtspec in datatypes.items():\n assert_datatype_name(dtname)\n assert_aliases(dtspec[\"aliases\"])\n asser_description(dtspec[\"description\"])\n","repo_name":"mondeja/pgdoc-datatype-parser","sub_path":"tests/test_parser.py","file_name":"test_parser.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"71644977848","text":"# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nfrom collections import deque\n\n\nclass Solution(object):\n def zigzagLevelOrder(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n if not root: return None\n q = deque([root])\n res = []\n depth = 0 # to mark tree depth, if even, prepend the element; if odd, append the element as usual.\n while q:\n l = len(q) # record all nodes in the same level\n rec = []\n for _ in range(l):\n node = q.popleft()\n if node.left: q.append(node.left)\n if node.right: q.append(node.right)\n if depth % 2:\n rec.appendleft(node.val)\n else:\n rec.append(node.val)\n res.append(list(rec))\n depth += 1\n return res\n","repo_name":"darrenfu/LeetcodePy","sub_path":"leetcode/bfs_dfs/binary_tree_zigzag_level_order_traversal_bfs.py","file_name":"binary_tree_zigzag_level_order_traversal_bfs.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"39780434935","text":"\"\"\"UAV_controller controller.\"\"\"\nimport os\nimport inspect\n\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\nos.sys.path.insert(0, parentdir)\n\nfrom controller import Robot\nimport cv2\nimport math\nimport numpy as np\nfrom gamepad_reader import Gamepad\nfrom locomotion import Locomotion\nfrom teleop_control import Teleop\nfrom pid_control import PID_Controller\nfrom moving_window_filter import MovingWindowFilter\nfrom orientation_tools import rot_to_rpy\n\ndef sensor_factory(robot, timestep):\n def sensor_builder(name):\n sensor = robot.getDevice(name)\n sensor.enable(timestep)\n return sensor\n\n return sensor_builder\n\ndef near_zero(val):\n if abs(val) < 0.05:\n return 0\n else:\n return val\n\nuse_gamepad = False\nuse_aruco = True\nDTYPE = np.float32\n\n# create the Robot instance.\nrobot = Robot()\n# get the time step of the current world.\ntimestep = int(robot.getBasicTimeStep())\n\n# Motors\nmotor_name = [\"font_motor\", \"rear_motor\", \"left_motor\", \"right_motor\"]\nmotors = []\nfor name in motor_name:\n motor = robot.getDevice(name)\n motor.setPosition(float('+inf')) # Velocity control mode.\n motor.setVelocity(0.0)\n motors.append(robot.getDevice(name))\n\n# Sensors\nsensor_builder = sensor_factory(robot, timestep)\ngps = sensor_builder(\"gps\")\ngyro = sensor_builder(\"gyro\")\ninertial_unit = sensor_builder(\"inertia_unit\")\ncamera = sensor_builder(\"camera\") # (240, 320, 3)\n\n# Camera params\ncx = camera.getWidth() / 2\ncy = camera.getHeight() / 2\n# f = camera.getFocalLength()\nf = cx/math.tan(camera.getFov()/2)\ncameraMatrix = np.array([f, 0, cx, 0, f, cy, 0, 0, 1], dtype=DTYPE).reshape((3,3))\ndistCoeffs = np.zeros(4, dtype=DTYPE)\nARUCO_TAG = cv2.aruco.DICT_6X6_50\naruco_dictionary = cv2.aruco.Dictionary_get(ARUCO_TAG)\naruco_parameters = cv2.aruco.DetectorParameters_create()\n\n# Gamepad and Keyboard\nif use_gamepad:\n gamepad = Gamepad(1, 1, 1)\nelse:\n keyboard = robot.getKeyboard()\n keyboard.enable(timestep)\n teleop = Teleop(robot, keyboard)\n\n# Locomotion\nlocomotion = Locomotion(robot, motors)\nlin_speed = [0, 0, 0]\nang_speed = 0\ne_stop = False\n\n# PID\npd_dx = PID_Controller(1, 0.1, 0.0)\npd_dy = PID_Controller(1.0, 0.1, 0.0)\npd_phi = PID_Controller(1.0, 0.5, 0.0)\nDX_TARGET = 0.35\nDX_MOVE_BACK = 0.5\nDY_THRESHOLD = 0.1\nPHI_THRESHOLD = 2/180*math.pi\n\n\n# Main loop:\nwhile robot.step(timestep) != -1:\n\n if use_gamepad:\n lin_speed, ang_speed, e_stop = gamepad.get_command()\n else:\n lin_speed, ang_speed, e_stop = teleop.get_command()\n\n # (320, 480, 3)\n image = np.frombuffer(camera.getImage(), np.uint8).reshape((camera.getHeight(), camera.getWidth(), 4))[:,:,:3].copy()\n \n if use_aruco:\n corners, ids, _ = cv2.aruco.detectMarkers(image, aruco_dictionary, parameters=aruco_parameters)\n # print(corners)\n\n if len(corners) > 0:\n cv2.aruco.drawDetectedMarkers(image, corners, ids)\n rvecs, tvecs, _ = cv2.aruco.estimatePoseSingleMarkers(corners, 0.03, cameraMatrix, distCoeffs)\n rot_mat, _ = cv2.Rodrigues(rvecs[0]) # (3,3)\n rpy = rot_to_rpy(rot_mat)\n # print(\"yaw: %.3f\"%rpy[1])\n yaw = near_zero(float(rpy[1]))\n distance = tvecs[0].squeeze() # (3,)\n # distance = (rot_mat @ distance).squeeze()\n # print(distance.shape)\n dx = (distance[-1] - DX_TARGET - 0.4)\n dy = (distance[0]) \n\n # print(\"dx dy yaw: %.3f, %.3f, %.3f\"%(dx+0.2, dy, yaw))\n\n lin_speed[1] = -pd_dy.apply(dy)\n # lin_speed[0] = -pd_dx.apply(dx)\n if dx > 0.0:\n if dy[2],来得到我们的酶活了!真不错!\", unsafe_allow_html=True\n )\n popt, pcov = curve_fit(\n model,\n t,\n Abs,\n p0=[1e-3, 1e-3],\n bounds=(0, np.inf),\n )\n st.line_chart(\n pd.DataFrame(\n {\n \"产物浓度\": Abs / epislon / L,\n \"拟合结果\": model(t, popt[0], popt[1], epislon, L) / epislon / L,\n }\n )\n )\n st.latex(r\"[P]=\\left(1-e^{-\" f\"{popt[0]:.4f}\" r\"t}\\right)\\times\" f\"{popt[1]:.4f}\")\n \"当然这边的 $K$ 代表的是体系中的总酶量,与我们加入的酶量 $E_0$ 有关,因此我们也可以用 $K/E_0$ 来表示单位酶活\"\n\n \"---\"\n st.caption(\n \"1. Habdous M, Vincent-Viry M, Visvikis S, Siest G. Rapid spectrophotometric method for serum glutathione S-transferases activity. Clin Chim Acta. 2002 Dec;326(1-2):131-42. doi: 10.1016/s0009-8981(02)00329-7. PMID: 12417104.\"\n )\n st.caption(\n \"2. 这里我们将 $S_0$ 也设为自由量,因为体系中实际能发生反应底物浓度可能与加入的底物浓度不尽相同,因此我们将其设为自由量以获得更好的拟合结果\"\n )\n\nwith C3:\n st.subheader(\"汇总数据\")\n \"通过前面的这些操作,我们已经能够通过实验数据计算得到酶活了,最后就是联系我们前面所提的假设检验来验证我们的猜想了。\"\n \"比方说我们在不同 pH 值的情况下测定了酶活,得到了如下的数据:\"\n pH = np.arange(6, 8, 0.5)\n K_mean = stats.norm.pdf(pH, loc=7, scale=1)\n K_std = (K_mean / np.max(K_mean)) ** 2 / 10\n Ks = np.random.normal(K_mean, K_std, size=(10, len(pH))).clip(0, None)\n\n fig = go.Figure(layout=plotly_layout)\n for i in range(len(pH)):\n fig.add_trace(\n go.Box(\n y=Ks[:, i],\n name=f\"pH={pH[i]:.1f}\",\n boxpoints=\"all\",\n jitter=0.3,\n pointpos=-1.8,\n )\n )\n fig.update_layout(\n yaxis_title=\"归一化后酶活\",\n showlegend=False,\n )\n st.plotly_chart(fig)\n\n st.subheader(\"假设与显著性水平\")\n \"有了汇总的数据之后,我们可以再次明确我们的假设。这里我们想要研究的是 pH 值对酶活是否有影响,因此我们的假设可以设定为:\"\n st.latex(\n r\"\\begin{cases}H_0:&\\text{所有 pH 下酶活均相等}\\\\H_\\alpha:&\\text{至少有一种 pH 下酶活不同于其他}\\end{cases}\"\n )\n \"像这种多个组别之间的假设检验就没法使用 t-检验了,不过我们可以使用方差分析(Analysis of Variance, ANOVA)来完成这一工作,这一种检验方式的具体细节可以参考[1]。\"\n \"至于显著性水平,由于这边的样本量正合适,因此我们可以使用 0.05 作为显著性水平。当然你也可以选择一个自己喜欢的显著性水平。\"\n alpha = st.select_slider(\"显著性水平\", options=[0.01, 0.05, 0.1], value=0.05)\n\n st.subheader(\"写点代码\")\n \"顺带一提,在这类数据分析中,我们通常会遇到以下两种数据形式,由于纵表允许嵌套分组,并且可拓展性更好(任意添加字段或选用不同字段进行分析),因此我们一般会选择纵表来进行分析。\"\n L, R = st.columns(2, gap=\"medium\")\n with L:\n with st.expander(\"纵表 ✔️\"):\n \"列头为各个字段,每一行为一个样本,比如:\"\n st.dataframe(\n pd.DataFrame({\"activity\": Ks.flatten(), \"pH\": np.repeat(pH, 10)})\n )\n with R:\n with st.expander(\"横表 ❌\"):\n \"每一列为一组实验条件,每一格数据都是一个样本,比如:\"\n st.dataframe(pd.DataFrame(Ks, columns=pH))\n\n \"好了,我们来写点代码来完成这一步骤吧!\"\n lang = st.radio(\"选择语言\", [\"Python\", \"R 语言\"], horizontal=True)\n if lang == \"Python\":\n st.code(\n f\"\"\"\nfrom scipy import stats\n\nstats.f_oneway(\n *data.groupby(\"pH\")[\"activity\"] # 将数据按照 pH 分组,\n .apply(list), # 然后将酶活转换为列表\n).pvalue # 取结果中的 P 值\n\"\"\"\n )\n else:\n st.code(\n f\"\"\"\naov(\n activity ~ pH, # 公式,表示研究酶活性与 pH 之间的关系\n data, # 数据来源(必须包含公式中的字段)\n)$p.value # 取结果中的 P 值\n\"\"\",\n language=\"r\",\n )\n p_val = stats.f_oneway(*Ks.T).pvalue\n \"然后我们就可以得到需要的 P 值了!\"\n st.metric(\n \"P 值\",\n f\"{p_val:.3e}\",\n f\"{'不' if p_val >= alpha else ''}显著\",\n delta_color=(\"inverse\" if p_val >= alpha else \"normal\"),\n )\n \"这里结果是显然是统计上显著的,这意味着至少有一个 pH 条件下酶活的水平有显著区别。那么如果想要进一步细分具体是哪个 pH 值组导致结果的显著性,我们可以将其排除后再进行一次方差分析,这样就可以更进一步细化我们的结果了!\"\n groups = st.multiselect(\"选择要排除的 pH 组\", pH, default=pH[0], help=\"多于两个组的选择将默认只保留前两个\")\n indices = [i for i, p in enumerate(pH) if p not in groups[:2]]\n p_val = stats.f_oneway(*Ks.T[indices]).pvalue\n st.metric(\n \"P 值\",\n f\"{p_val:.3e}\",\n f\"{'不' if p_val >= alpha else ''}显著\",\n delta_color=(\"inverse\" if p_val >= alpha else \"normal\"),\n )\n\n fig = go.Figure(layout=plotly_layout)\n for i in indices:\n fig.add_trace(\n go.Box(\n y=Ks[:, i],\n name=f\"pH={pH[i]:.1f}\",\n boxpoints=\"all\",\n jitter=0.3,\n pointpos=-1.8,\n )\n )\n fig.update_layout(\n yaxis_title=\"归一化后酶活\",\n showlegend=False,\n )\n st.plotly_chart(fig)\n\n \"---\"\n st.caption(\n r\"1. [Wikipedia: 方差分析](https://zh.wikipedia.org/wiki/%E6%96%B9%E5%B7%AE%E5%88%86%E6%9E%90)\"\n )\n","repo_name":"TeddyHuang-00/DiveIntoBiostat","sub_path":"src/pages/3_📊_Getting_data.py","file_name":"3_📊_Getting_data.py","file_ext":"py","file_size_in_byte":14027,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"7885928031","text":"# %% 1. Import libraries\r\nimport logging\r\nfrom configs.getconfig import get_default_config, modify_config, update_iotype_argument\r\nfrom utils.io import create_folder\r\n\r\nimport nni\r\nimport argparse\r\nimport torch\r\nimport yaml, json\r\nfrom pathlib import Path, PurePath\r\nfrom datetime import date\r\nimport numpy as np\r\nfrom utils.io import load_data_from_table\r\nfrom icecream import ic\r\nimport pprint\r\n\r\n# %% 2. Load config\r\n\r\n_logger = logging.getLogger('mnist_example')\r\n_logger.setLevel(logging.INFO)\r\nfrom utils.augmentation import update_augment_argument, parse_augment_argument_json\r\n\r\ndef get_params():\r\n # Training settings\r\n parser = argparse.ArgumentParser(description='PyTorch MNIST Example')\r\n # parser.add_argument(\"--inputType\", type=str,\r\n # default='strainMat', help=\"data directory\")\r\n parser.add_argument('--n_conv_layers', type=int, default=3, metavar='NCL',\r\n help='n_conv_layers (default: 3)')\r\n parser.add_argument('--n_conv_channels', type=int, default=3, metavar='NCC',\r\n help='n_conv_channels (default: 3)')\r\n parser.add_argument('--learning_rate', type=float, default=1e-4, metavar='LR',\r\n help='learning rate (default: 1e-4)')\r\n parser.add_argument('--augmentatuon', type=str, default='', metavar='AUG',\r\n help='aug (default: \"\")')\r\n parser.add_argument('--aug_more_on_data_with_scar', type=bool, default=False, metavar='AS',\r\n help='aug_more_on_data_with_scar (default: False)')\r\n parser.add_argument('--scar_free', type=str, default=\"True\", metavar='SCAR',\r\n help='Avoid Data with scar or not (default: \"True\")')\r\n parser.add_argument('--input_types', type=str, default=\"strainMat\", metavar='IN',\r\n help='Input types (Split by \"+\")')\r\n parser.add_argument('--output_types', type=str, default=\"TOS\", metavar='OUT',\r\n help='Output types (Split by \"+\")')\r\n\r\n for network_para in ['joint_n_conv_layers', 'joint_n_conv_channels', 'joint_conv_size',\r\n 'reg_n_conv_layers', 'reg_n_conv_channels', 'reg_conv_size', 'reg_n_linear_layers',\r\n 'cls_n_conv_layers', 'cls_n_conv_channels', 'cls_conv_size', 'cls_n_linear_layers']:\r\n parser.add_argument(f'--{network_para}', type=int, default=-1)\r\n\r\n parser.add_argument('--regularize_weight', type=float, default=0, metavar='WREGU',\r\n help='Regularize_weight (default: 0)')\r\n parser.add_argument('--cls_weight', type=float, default=1e1, metavar='CLSW',\r\n help='Classification_weight (default: 1e1)')\r\n\r\n # parser.add_argument('--train_test_split', type=str, default='fixedPatient', metavar='SPL',\r\n # help='aug (default: 0)')\r\n # parser.add_argument('--paddingMethod', type=str, default='zero', metavar='PAD',\r\n # help='aug (default: 0)')\r\n args, _ = parser.parse_known_args()\r\n return args\r\n\r\n\r\n# debug_path_to_exp = '../../experiment_results/NNI_test'\r\ndebug_path_to_exp = './exp-results/NNI_test'\r\ndataset_dir = './data'\r\n\r\n\r\ntuned_params = nni.get_next_parameter()\r\nif tuned_params == {}:\r\n debug_mode = True\r\nelse:\r\n debug_mode = False\r\n\r\n# exp_type = 'strainmat_to_TOS'\r\n# exp_type = 'multitask_reg_clsDistMap'\r\n# exp_type = 'multitask_reg_cls'\r\n# exp_type = 'scar_cls'\r\n# exp_type = 'scar_distmap_reg'\r\nexp_type = tuned_params.get('exp_type', 'reg')\r\n# exp_type = tuned_params['exp_type']\r\nconfig = get_default_config(exp_type)\r\n# config['training']['epochs_num'] = 50\r\n\r\n# Fetch hyper-parameters from HPO tuner\r\n# comment out following two lines to run the code without NNI framework\r\n\r\n\r\nmodify_config(config, exp_type, tuned_params)\r\n# load_num = -1\r\nload_data_num = None\r\nconfig['exp_type'] = exp_type\r\nconfig['data']['train_test_split']['paras']['test_patient_names'] = [\r\n 'Pre_CRT_LBBB_with_scar-49_KJ_MR', 'Pre_CRT_LBBB_with_scar-114_42_BC_MR', 'Pre_CRT_LBBB_with_scar-121_53_DY_MR', 'SET01-CT02', 'SET02-CT28']\r\n\r\nif debug_mode:\r\n \r\n # path_to_exp = '/home/jrxing/WorkSpace/Research/Cardiac/experiment_results/NNI_test'\r\n # path_to_exp = '/home/jrxing/Research/Projects/Cardiac/Reperiment_Results/'\r\n # path_to_exp = '../../experiment_results/NNI_test'\r\n load_data_num = [20, -20]\r\n config['data']['train_test_split']['paras']['test_patient_names'] = [\r\n 'SET01-CT02']\r\n # exp_type = 'multitask-reg-cls'\r\n exp_type = 'reg'\r\n config['exp_parent_path'] = debug_path_to_exp\r\n create_folder(debug_path_to_exp + '/training_results', recursive=False, action_when_exist='pass')\r\n create_folder(debug_path_to_exp + '/test_results', recursive=False, action_when_exist='pass')\r\n create_folder(debug_path_to_exp + '/training_results_CAM', recursive=False, action_when_exist='pass')\r\n create_folder(debug_path_to_exp + '/test_results_CAM', recursive=False, action_when_exist='pass')\r\n create_folder(debug_path_to_exp + '/networks', recursive=False, action_when_exist='pass')\r\n create_folder(debug_path_to_exp + '/configs', recursive=False, action_when_exist='pass')\r\n config['training']['epochs_num'] = 51\r\n config['training']['batch_size'] = 64\r\n config['training']['learning_rate'] = 1e-4\r\n \r\n # config['data']['input_info'][0]['type'] = 'strainMatFullResolutionSVD'\r\n config['data']['input_info'] = [{'type': 'strainMatFullResolutionSVD', 'tag': 'strainmat', 'config': {}}]\r\n # config['data']['input_info'][0]['type'] = 'strainMatFullResolution'\r\n # config['data']['input_type'] = 'strainMat'\r\n # config['data']['output_type'] = 'TOS18_Jerry'\r\n config['data']['output_info'] = [{'type': 'TOS126', 'config':{}, 'tag': 'reg'}]\r\n # config['data']['output_info'] = [{'type': 'has_scar', 'config':{}}]\r\n # config['data']['output_info'] = [{'type': 'late_activation_sector_label', 'config':{}}]\r\n # config['data']['output_info'] = [{'type': 'scar_sector_label', 'config':{}}]\r\n # config['data']['output_info'] = [{'type': 'late_activation_sector_label', 'config':{}, 'tag': 'cls'}, \r\n # {'type':'TOS126', 'config':{}, 'tag': 'reg'}]\r\n \r\n \r\n config['data']['use_data_with_scar'] = 'all'\r\n # config['data']['scar_free'] = False\r\n # config['data']['scar_must'] = True\r\n # config['data']['scar_must_must'] = True\r\n config['data']['force_onehot'] = False\r\n config['data']['remove_sector_label_spikes'] = False\r\n # config['data']['train_test_split']['paras']['test_patient_names'] = ['SET01-CT11', 'SET02-CT28', 'SET03-EC21',\r\n # 'SET01-CT02', 'SET01-CT16', 'SET01-CT18']\r\n\r\n\r\n # config['data']['filename'] = 'D://dataFull-201-2020-12-23-Jerry.npy'\r\n\r\n # config['data']['filename'] = 'D://dataFull-201-2020-12-23-Jerry.npy'\r\n # config['data']['filename'] = PurePath('/home/jrxing/WorkSpace/Research/Cardiac/Dataset', 'dataFull-201-2020-12-23-Jerry.npy')\r\n # config['data']['filename'] = str(PurePath('../../Dataset', 'dataFull-201-2020-12-23-Jerry.npy'))\r\n # config['data']['input_info'] = update_iotype_argument('strainMatFullResolution')\r\n # config['data']['TOS_info'] = update_iotype_argument('TOS126')\r\n \r\n # config['data']['output_types'] = 'TOSfullRes_Jerry+late_acti_label'.split('+')\r\n # config['data']['output_types'] = 'TOSfullRes_Jerry+late_acti_label'.split('+')\r\n # config['data']['output_types'] = 'TOSfullRes_Jerry+strain_curve_type_label'.split('+')\r\n # config['data']['output_info'] = update_iotype_argument('TOSfullRes_Jerry+scar-AHA-step=50')\r\n # config['data']['output_info'] = update_iotype_argument('TOS126+scar_sector_percentage')\r\n # config['data']['output_info'] = update_iotype_argument('TOS126+scar_sector_label')\r\n # config['data']['output_types'] = 'TOSfullRes_Jerry+strain_curve_type_dist_map'.split('+')\r\n # config['data']['output_types'] = 'polyfit_coefs+late_acti_label'.split('+')\r\n # config['data']['output_types'] = 'TOSfullRes_Jerry+late_acti_dist_map'.split('+')\r\n # config['data']['input_types'] = 'strainMat'.split('+')\r\n # config['data']['output_types'] = 'TOS18_Jerry+late_acti_label'.split('+')\r\n # config['data']['output_types'] = 'TOS18_Jerry+late_acti_dist_map'.split('+')\r\n # config['data']['augmentation'] = update_augment_argument('shift-sector=-32_32_5+mixup=0.2_500', [])\r\n # aug_args_json_str = '\\\r\n # {\"method\":\"shift_sector\", \"paras\":\"-48,48,3\", \"include_data_conditions\":\"has_scar_sector_label\"}+\\\r\n # {\"method\":\"mixup\", \"paras\":\"0.5,500\", \"include_data_conditions\":\"has_scar_sector_label\"}+\\\r\n # {\"method\":\"shift_sector\", \"paras\":\"-32,32,10\", \"include_data_conditions\":\"no_scar_sector_label\"}+\\\r\n # {\"method\":\"mixup\", \"paras\":\"0.5,100\", \"include_data_conditions\":\"no_scar_sector_label\"}\\\r\n # '\r\n aug_args_json_str = '\\\r\n {\"method\":\"shift_sector\", \"paras\":\"-48,48,3\", \"include_data_conditions\":\"has_scar\"}+\\\r\n {\"method\":\"mixup\", \"paras\":\"0.5,500\", \"include_data_conditions\":\"has_scar\"}+\\\r\n {\"method\":\"shift_sector\", \"paras\":\"-32,32,10\", \"include_data_conditions\":\"no_scar\"}+\\\r\n {\"method\":\"mixup\", \"paras\":\"0.5,100\", \"include_data_conditions\":\"no_scar\"}\\\r\n '\r\n config['data']['augmentation'] = parse_augment_argument_json(aug_args_json_str)\r\n # config['data']['augmentation'] = update_augment_argument('shift-sector=-32_32_5+mixup=0.2_500', [])\r\n # config['data']['augmentation'] = update_augment_argument('shift-sector_-32_32_5', [])\r\n # print('AUG', update_augment_argument('shift-sector=-32_32_5+mixup=0.1_1000', []))\r\n # logger = _logger\r\n # assert 1>10\r\n # config['data']['train_test_split']['paras']['test_patient_names'] = [\r\n # 'SET01-CT02']\r\n \r\n # config['net'] = {'type': 'NetStrainMat2ClsReg',\r\n # 'paras': {\r\n # 'n_sector': 18,\r\n # 'n_frames': 64,\r\n # 'batch_norm': True,\r\n # 'activation_func': 'relu',\r\n # 'n_conv_layers': 3,\r\n # 'n_linear_layers': 3,\r\n # 'n_sectors_in': 128,\r\n # 'n_sectors_out': 128,\r\n # 'n_classes': 1}\r\n # }\r\n\r\n # config['net']['type'] = 'NetStrainMat2ClsReg'\r\n # config['net']['type'] = 'NetStrainMat2ClsReg'\r\n config['net']['type'] = 'NetStrainMat2Reg'\r\n \r\n \r\n # CLs network\r\n # config['net']['paras']['batch_norm'] = True\r\n # # config['net']['paras']['activation_func'] = 'leaky_relu'\r\n # config['net']['paras']['activation_func'] = 'relu'\r\n # config['net']['paras']['conv_layer_num'] = 4\r\n # config['net']['paras']['pooling_layer_num_max'] = None\r\n # # config['net']['paras']['n_conv_layers'] = 3\r\n # config['net']['paras']['linear_layer_num'] = 4\r\n \r\n # Multi reg-cls network\r\n config['net']['paras']['joint_init_conv_channel_num'] = 4\r\n config['net']['paras']['joint_conv_layer_num'] = 4\r\n config['net']['paras']['joint_pooling_layer_num_max'] = None\r\n config['net']['paras']['reg_conv_layer_num'] = 4\r\n config['net']['paras']['reg_linear_layer_num'] = 2\r\n config['net']['paras']['reg_pooling_layer_num_max'] = None\r\n config['net']['paras']['cls_conv_layer_num'] = 4\r\n config['net']['paras']['cls_linear_layer_num'] = 2\r\n config['net']['paras']['cls_pooling_layer_num_max'] = None\r\n\r\n \r\n # config['net']['paras']['force_onehot'] = False\r\n # config['eval']['paras']['cls_weight'] = 1e2\r\n # config['eval'] = {'method': 'MSE', 'paras': {}, 'target_tag': 'cls'}\r\n # config['eval'] = {'method': 'cls', 'paras': {'type': 'Cross Entropy'}, 'target_tag': 'cls'}\r\n # config['eval'] = {'method': 'cls', 'paras': {'type': 'Negative log likelihood'}, 'target_tag': 'cls'}\r\n # config['eval'] = {\r\n # 'method': 'multitask-reg-cls',\r\n # 'paras': [\r\n # {'type': 'MSE', 'weight': 1, 'target_tag': 'reg'},\r\n # {'type': 'Negative log likelihood', 'weight': 0, 'target_tag': 'cls'}\r\n # ]\r\n # }\r\n config['eval'] = {\r\n 'method': 'reg',\r\n 'paras': [\r\n {'type': 'MSE', 'weight': 1, 'target_tag': 'reg'}\r\n ]\r\n }\r\n # config['eval'] = [{'method': 'MSE', 'paras': {}, 'target_tag': 'reg'},\r\n # {'method': 'Cross Entropy', 'paras': {}, 'target_tag': 'cls'}]\r\n # config['data']['aug_more_on_data_with_scar'] = True\r\n config['show'] = {}\r\n config['show']['CAM_target_sector'] = 'late_activation_center'\r\nelse:\r\n exp_info_filename = PurePath(str(Path.home()), f'nni-config-{date.today().strftime(\"%Y-%m\")}.yml')\r\n # exp_info_filename = f'./NNI/configs/nni-config-{date.today().strftime(\"%Y-%m\")}.yml'\r\n with open(exp_info_filename) as file:\r\n exp_info = yaml.full_load(file)\r\n config['exp_parent_path'] = exp_info['exp_parent_path']\r\n# config['data']['filename'] = '../../Dataset/dataFull-201-2020-12-23-Jerry.npy'\r\n# dataset_dir = 'C:\\\\Users\\\\remus\\\\OneDrive\\\\Documents\\\\Study\\\\Researches\\\\Projects\\\\cardiac\\\\Dataset\\\\CRT_TOS_Data_Jerry'\r\n# # data_records_filename = str(Path(dataset_dir, 'record_sheets\\\\cardiac-strainmat-dataset-2021-04-20.xlsx'))\r\n# data_records_filename = str(Path(dataset_dir, 'record_sheets', 'cardiac-strainmat-dataset-2021-06-13-scar-classification.xlsx'))\r\ndata_records_filename = tuned_params.get('data_records_filename', 'cardiac-strainmat-dataset-2021-07-04-late-activation-region-classification.xlsx')\r\ndata_records_filename_full = str(Path(dataset_dir, 'record_sheets', data_records_filename))\r\nconfig['data']['filename'] = data_records_filename_full\r\n# config['data']['train_test_split']['paras']['test_patient_names'] = ['SET01-CT11', 'SET02-CT28', 'SET03-EC21',\r\n# 'SET03-UP34']\r\n# config['data']['train_test_split']['paras']['test_patient_names'] = [\r\n# 'SET01-CT11', 'SET02-CT28', 'SET03-EC21', 'SET03-UP34', \r\n# 'Pre_CRT_LBBB_with_scar-34_CM_MR', 'Pre_CRT_LBBB_with_scar-86_RS_MR']\r\n\r\n\r\n\r\n\r\nconfig['NNI'] = {\r\n 'experiment_id': nni.get_experiment_id(),\r\n 'trial_id': nni.get_trial_id(),\r\n 'sequence_id': nni.get_sequence_id()\r\n}\r\nconfig['NNI'][\r\n 'trial_name'] = f\"exp-{str(config['NNI']['experiment_id']).strip()}-idx-{config['NNI']['sequence_id']:03d}-trial-{str(config['NNI']['trial_id']).strip()}\"\r\n\r\n# _logger.info('Hyper-parameters: %s', config)\r\n\r\npprint.pprint(config)\r\n\r\n# %% 3. Run Experiment\r\nconfig = config\r\nNNI = True\r\nlogger = _logger\r\nsave_model = True\r\nsave_prediction = True\r\nsave_config = True\r\ntrained_model_filename = None\r\n\r\n# %% 3.0. Get experiment folder if needed\r\ntrail_name = config['NNI'].get('trial_name',\r\n f\"exp-{str(config['NNI']['experiment_id']).strip()}-idx-{config['NNI']['sequence_id']:03d}-trial-{str(config['NNI']['trial_id']).strip()}\")\r\n\r\n# %% 3.1. Set device\r\n# gpuIdx = 0\r\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n# device = torch.device(\"cpu\")\r\n\r\n# %% 4. Load data\r\nif logger is not None:\r\n logger.info('Load Data')\r\nprint('(PRINT) Load Data')\r\n\r\nincluded_data_info = config['data']['input_info'] + config['data']['output_info']\r\nincluded_data_types = [data_type['type'] for data_type in included_data_info]\r\ndataFilename = config['data']['filename']\r\ndataFull = load_data_from_table(dataFilename, dataset_dir=dataset_dir, data_info=included_data_info, load_num=load_data_num)\r\n\r\nfrom utils.data import get_data_type_by_category\r\ndef check_has_scar(datum, strict=False):\r\n # scar_data_type = get_data_type('scar_sector_percentage')\r\n if 'scar_sector_percentage' not in datum.keys():\r\n return False\r\n \r\n if strict and np.sum(datum['scar_sector_percentage']) < 0.1:\r\n return False\r\n else:\r\n return True\r\n \r\nuse_data_with_scar = config['data'].get('use_data_with_scar', 'scar_free')\r\nif use_data_with_scar == 'scar_free':\r\n dataFull = [datum for datum in dataFull if int(datum['hasScar']) == 0]\r\nelif use_data_with_scar == 'scar_must':\r\n dataFull = [datum for datum in dataFull if datum['hasScar'] != 0]\r\nelif use_data_with_scar == 'scar_must_must':\r\n dataFull = [datum for datum in dataFull if check_has_scar(datum, strict=True)]\r\n# if config['data'].get('scar_free', False):\r\n# dataFull = [datum for datum in dataFull if datum['hasScar'] == 0]\r\n\r\n# if config['data'].get('scar_must', False):\r\n# dataFull = [datum for datum in dataFull if datum['hasScar'] != 0]\r\n \r\n# if config['data'].get('scar_must_must', False):\r\n# dataFull = [datum for datum in dataFull if np.sum(datum['scar_sector_percentage']) > 0.1] \r\n# if debug_mode:\r\n# dataFull = [datum for datum in dataFull if not datum['patient_name'].startswith('Pre_CRT')]\r\n# config['data']['train_test_split']['paras']['test_patient_names'] = [\r\n# 'SET01-CT11', 'SET02-CT28', 'SET03-EC21', 'SET03-UP34']\r\nfrom utils.data import report_data_info\r\nreport_data_info(dataFull)\r\n\r\n# %% 5. Add class label or distance map\r\nfrom utils.data import add_classification_label\r\n# if config['eval']['method'] in ['multitask-reg-cls', 'cls']:\r\nif exp_type in ['multitask-reg-cls', 'cls']:\r\n add_classification_label(data=dataFull, data_info=included_data_info, remove_spikes=config['data'].get('remove_sector_label_spikes', False), force_onehot=config['data'].get('force_onehot', True))\r\n\r\n# %% 6. Pre-processing\r\nfrom utils.preprocessing import unify_n_frame, unify_n_sector, remove_last_frames\r\nremove_last_frames(dataFull, included_data_types, n_frames_to_remove=5)\r\nunify_n_frame(dataFull, included_data_types, n_frames_target='power_of_2')\r\nunify_n_sector(dataFull, included_data_types, n_sectors_target='power_of_2', method='copy_boundary')\r\n\r\n# %% 7. Add distance map\r\nfrom utils.data import add_distance_map\r\nif exp_type in ['multitask-reg-clsDistMap', 'reg']:\r\n add_distance_map(dataFull, included_data_info, remove_spikes=config['data'].get('remove_sector_label_spikes', False))\r\n\r\n# %% 7. Train-test split\r\nfrom utils.data import train_test_split\r\ntraining_data_raw, test_data = train_test_split(config['data']['train_test_split'], dataFull)\r\nprint('training_data_raw len:', len(training_data_raw))\r\nprint('test_data len:', len(test_data))\r\n\r\n# %% 8. Augmentation\r\nfor datum in dataFull:\r\n datum['augmented'] = False\r\n\r\nfrom utils.augmentation import augment\r\n# if not debug_mode:\r\ntraining_data_aug, training_data_aug_samples = augment(training_data_raw, included_data_types,\r\n config['data']['augmentation'])\r\n# else:\r\n # training_data_aug = []\r\n # training_data_aug_samples = []\r\nprint('training_data_aug len:', len(training_data_aug))\r\nprint('training_data_aug_samples len:', len(training_data_aug_samples))\r\n\r\ntraining_data = training_data_raw + training_data_aug\r\n\r\n# %% 8.1 Re-label for some types\r\nfrom utils.data import add_polyfit_coefficient\r\nfor data_type in included_data_types:\r\n if data_type == 'polyfit_coefs':\r\n add_polyfit_coefficient(training_data + test_data, included_data_types, degree=10)\r\n\r\n# %% 9. Set Dataset\r\nfrom modules.dataset import Dataset\r\ndataset_precision = np.float16\r\n# dataset_precision = np.float32\r\n# dataset_precision = None\r\ntraining_dataset = Dataset(training_data, config['data']['input_info'], config['data']['output_info'], precision=dataset_precision)\r\ntest_dataset = Dataset(test_data, config['data']['input_info'], config['data']['output_info'], precision=dataset_precision)\r\n\r\ntraining_dataset.input_info = config['data']['input_info']\r\ntraining_dataset.output_info = config['data']['output_info']\r\ntest_dataset.input_info = config['data']['input_info']\r\ntest_dataset.output_info = config['data']['output_info']\r\n\r\n# Reshape data\r\nfor data_type in training_dataset.input_types + training_dataset.output_types:\r\n # print(np.ndim(training_dataset[0][data_type]))\r\n if data_type in ['TOS126'] and np.ndim(training_dataset[0][data_type]) == 1:\r\n for datum in training_dataset:\r\n datum[data_type] = datum[data_type][None, :]\r\n for datum in test_dataset:\r\n datum[data_type] = datum[data_type][None, :]\r\n\r\n# %% 10. Set Network\r\nfrom utils.data import get_data_type_by_category, get_data_category_by_type, get_data_info_by_tag\r\nif trained_model_filename is None:\r\n from modules.networks.get_network import get_network_by_name\r\n # Input parameters\r\n # config['net']['paras']['n_sectors_in'] = training_data[0][config['data']['input_info'][0]['type']].shape[-2]\r\n # config['net']['paras']['n_sectors_out'] = training_data[0][config['data']['input_info'][0]['type']].shape[-2]\r\n # config['net']['paras']['n_frames'] = training_data[0][config['data']['input_info'][0]['type']].shape[-1]\r\n config['net']['paras']['input_channel_num'] = training_data[0][config['data']['input_info'][0]['type']].shape[-3]\r\n config['net']['paras']['input_sector_num'] = training_data[0][config['data']['input_info'][0]['type']].shape[-2]\r\n config['net']['paras']['input_frame_num'] = training_data[0][config['data']['input_info'][0]['type']].shape[-1]\r\n # config['net']['paras']['n_sectors_out'] = training_data[0][config['data']['input_info'][0]['type']].shape[-2]\r\n \r\n \r\n # Output parameters\r\n # config['net']['paras']['degree'] = 10\r\n # if config['eval']['method'] in ['multitask-reg-cls', 'multitask-reg-clsDistMap']:\r\n if False:\r\n if exp_type in ['multitask-reg-cls', 'multitask-reg-clsDistMap']:\r\n if exp_type in ['multitask-reg-cls']:\r\n cls_out_data_type = get_data_type_by_category('sector_label', config['data']['output_info'])\r\n # cls_out_data_type = get_data_info_by_tag('cls', config['data']['output_info'])['type']\r\n config['net']['paras']['n_classes'] = training_data[0][cls_out_data_type].shape[-2]\r\n elif config['eval']['method'] in ['multitask-reg-clsDistMap']:\r\n cls_out_data_type = get_data_type_by_category('sector_dist_map', config['data']['output_info'])\r\n config['net']['paras']['n_classes'] = training_data[0][cls_out_data_type].shape[-2]\r\n # config['net']['paras']['n_sectors_out'] = 22\r\n config['net']['paras']['reg_n_dim_out'] = training_data[0][config['data']['input_info'][0]['type']].shape[-2]\r\n config['net']['paras']['cls_n_dim_out'] = training_data[0][config['data']['input_info'][0]['type']].shape[-2] * \\\r\n training_data[0][cls_out_data_type].shape[-2] \r\n config['net']['paras']['force_onehot'] = config['data'].get('force_onehot', True)\r\n # elif config['eval']['method'] in ['cls']:\r\n elif exp_type in ['cls']:\r\n cls_out_data_type = get_data_type_by_category('sector_label', config['data']['output_info'])\r\n if cls_out_data_type is not None:\r\n config['net']['paras']['n_classes'] = training_data[0][cls_out_data_type].shape[-2]\r\n config['net']['paras']['cls_n_dim_out'] = training_data[0][config['data']['input_info'][0]['type']].shape[-2] * \\\r\n training_data[0][cls_out_data_type].shape[-2]\r\n else:\r\n cls_out_data_type = get_data_type_by_category('data_label', config['data']['output_info'])\r\n config['net']['paras']['n_classes'] = training_data[0][cls_out_data_type].shape[-2]\r\n config['net']['paras']['cls_n_dim_out'] = training_data[0][cls_out_data_type].shape[-2]\r\n config['net']['paras']['force_onehot'] = config['data'].get('force_onehot', True)\r\n # elif config['eval']['method'] in ['reg']:\r\n elif exp_type in ['reg']:\r\n try:\r\n reg_out_data_type = get_data_type_by_category('sector_dist_map', config['data']['output_info'])\r\n except:\r\n reg_out_data_type = get_data_type_by_category('sector_value', config['data']['output_info'])\r\n if get_data_category_by_type(reg_out_data_type) == 'TOS':\r\n config['net']['paras']['add_last_relu'] = True\r\n config['net']['paras']['n_classes'] = training_data[0][reg_out_data_type].shape[-2]\r\n config['net']['paras']['reg_n_dim_out'] = training_data[0][config['data']['input_info'][0]['type']].shape[-2] * \\\r\n training_data[0][reg_out_data_type].shape[-2]\r\n else:\r\n raise ValueError(f'Unsupported exp type: {exp_type}')\r\n \r\n if config['net']['type'] in ['NetStrainMat2Cls']:\r\n cls_out_data_type = get_data_type_by_category('sector_label', config['data']['output_info'])\r\n classes_num = training_data[0][cls_out_data_type].shape[-2]\r\n config['net']['paras']['input_sector_num'] = training_data[0][config['data']['input_info'][0]['type']].shape[-2]\r\n config['net']['paras']['input_frame_num'] = training_data[0][config['data']['input_info'][0]['type']].shape[-1]\r\n config['net']['paras']['force_onehot'] = config['data'].get('force_onehot', True)\r\n # if not config['data'].get('force_onehot', True) and classes_num == 2:\r\n if not config['data'].get('force_onehot', True) and classes_num <= 2:\r\n config['net']['paras']['cls_output_dim'] = config['net']['paras']['input_sector_num']\r\n else:\r\n config['net']['paras']['cls_output_dim'] = \\\r\n config['net']['paras']['input_sector_num'] * classes_num\r\n \r\n elif config['net']['type'] in ['NetStrainMat2ClsReg']:\r\n cls_out_data_type = get_data_info_by_tag('cls', config['data']['output_info'])['type']\r\n classes_num = training_data[0][cls_out_data_type].shape[-2]\r\n # config['net']['paras']['input_sector_num'] = training_data[0][config['data']['input_info'][0]['type']].shape[-2]\r\n # config['net']['paras']['input_frame_num'] = training_data[0][config['data']['input_info'][0]['type']].shape[-1]\r\n config['net']['paras']['cls_force_onehot'] = config['data'].get('force_onehot', True)\r\n config['net']['paras']['cls_class_normlize_layer'] = config['net']['paras'].get('cls_class_normlize_layer', 'log softmax')\r\n \r\n # if not config['data'].get('force_onehot', True) and classes_num == 2:\r\n if not config['data'].get('force_onehot', True) and classes_num <= 2:\r\n config['net']['paras']['cls_output_dim'] = config['net']['paras']['input_sector_num']\r\n else:\r\n config['net']['paras']['cls_output_dim'] = \\\r\n config['net']['paras']['input_sector_num'] * classes_num\r\n config['net']['paras']['reg_output_dim'] = config['net']['paras']['input_sector_num']\r\n reg_out_data_type = get_data_info_by_tag('reg', config['data']['output_info'])['type']\r\n if np.ndim(training_data[0][reg_out_data_type]) == 2:\r\n config['net']['paras']['reg_output_additional_dim'] = False\r\n else:\r\n config['net']['paras']['reg_output_additional_dim'] = True\r\n elif config['net']['type'] in ['NetStrainMat2Reg']:\r\n reg_out_data_type = get_data_info_by_tag('reg', config['data']['output_info'])['type']\r\n strainmat_data_type = get_data_info_by_tag('strainmat', config['data']['input_info'])['type']\r\n classes_num = training_data[0][reg_out_data_type].shape[-2] if np.ndim(training_data[0][reg_out_data_type]) >= 3 else 1\r\n \r\n config['net']['paras']['input_sector_num'] = training_data[0][strainmat_data_type].shape[-2]\r\n config['net']['paras']['input_frame_num'] = training_data[0][strainmat_data_type].shape[-1]\r\n config['net']['paras']['force_onehot'] = config['data'].get('force_onehot', False)\r\n config['net']['paras']['classes_num'] = classes_num \r\n \r\n # if not config['data'].get('force_onehot', True) and classes_num == 2:\r\n if not config['data'].get('force_onehot', False) and classes_num <= 2:\r\n config['net']['paras']['reg_output_dim'] = config['net']['paras']['input_sector_num']\r\n else:\r\n config['net']['paras']['reg_output_dim'] = \\\r\n config['net']['paras']['input_sector_num'] * classes_num\r\n \r\n \r\n network = get_network_by_name(config['net']['type'], config['net'])\r\n network.set_input_types(training_dataset.input_types, [datum_info['tag'] for datum_info in config['data']['input_info']])\r\n network.set_output_types(training_dataset.output_types, [datum_info['tag'] for datum_info in config['data']['output_info']])\r\n network.to(device)\r\n print(network)\r\nelse:\r\n network = torch.load(trained_model_filename)\r\n\r\n\r\n# %% 11. Set Network Module\r\nfrom modules.net import NetModule\r\nnet = NetModule(network=network, evaluation_config=config['eval'], regularization_config=config['regularization'],\r\n device=device)\r\n\r\n# %% 12. Training\r\nif trained_model_filename is None:\r\n net.network.train()\r\n training_loss_final, training_loss_history, valid_loss_final, valid_loss_history, valid_reg_loss_final, past_time = \\\r\n net.train(training_dataset=training_dataset, valid_dataset=test_dataset, training_config=config['training'],\r\n NNI=NNI, logger=logger)\r\nelse:\r\n training_loss_final, valid_loss_final = None, None\r\n\r\n# %% 13. Save Prediction Results\r\n# Prediction\r\nnet.network.eval()\r\n# training_data_to_save = training_data_raw[:12] + training_data_aug[:5] + training_data_aug_samples\r\ntraining_patients_to_show = ['SET01-CT02', 'SET01-CT16']\r\ntraining_data_to_save = training_data_raw[::5][:12] + [d for d in training_data_raw if d['patient_name'] in training_patients_to_show]\r\n# training_dataset_raw = [datum for datum in training_dataset if datum['augmented'] == False]\r\n# training_data_to_save = training_dataset_raw[::5][:12] + [d for d in training_dataset_raw if d['patient_name'] in training_patients_to_show]\r\nfor datum in training_data_raw + test_data + training_data_to_save:\r\n datum_pred = net.pred(datum, training_dataset.input_types, training_dataset.output_info)\r\n for output_data_key in datum_pred['data'].keys():\r\n datum[output_data_key + '_pred'] = datum_pred['data'][output_data_key]\r\n datum['loss_pred'] = datum_pred['loss']\r\n\r\n# %%\r\nshow_config = config.get('show', {})\r\n# expPath = '../nni_logs/' + config['NNI']['experiment_id'] + '/trials/' + config['NNI']['trial_id'] + '/'\r\nfrom utils.plot import save_multi_strainmat_with_curves\r\nfrom utils.plot import save_multi_strainmat_with_curves_and_activation_map\r\ncurve_types_to_plot = []\r\nfor output_data_type in [data_info['type'] for data_info in config['data']['output_info']]:\r\n curve_types_to_plot.append(output_data_type)\r\n curve_types_to_plot.append(output_data_type + '_pred')\r\n\r\n\r\nif save_prediction:\r\n save_test_results_filename_full = str(\r\n PurePath(config['exp_parent_path'], 'test_results', f\"{trail_name}-test-results.pdf\"))\r\n save_training_results_filename_full = str(\r\n PurePath(config['exp_parent_path'], 'training_results', f\"{trail_name}-train-results.pdf\"))\r\n \r\n strainmat_type = config['data']['input_info'][0]['type']\r\n save_multi_strainmat_with_curves(data=test_data,\r\n strainmat_type=strainmat_type,\r\n curve_types=curve_types_to_plot,\r\n legends=curve_types_to_plot,\r\n save_filename=save_test_results_filename_full,\r\n subtitles=[datum['patient_slice_name'] for datum in test_data])\r\n\r\n \r\n save_multi_strainmat_with_curves(data=training_data_to_save,\r\n strainmat_type=strainmat_type,\r\n curve_types=curve_types_to_plot,\r\n legends=curve_types_to_plot,\r\n save_filename=save_training_results_filename_full,\r\n subtitles=[datum['patient_slice_name'] for datum in training_data_to_save])\r\n\r\n\r\ndebug_show_accuracy = False\r\nif debug_show_accuracy:\r\n # training_label = [int(datum['has_scar'][0,-1,0]) for datum in training_data_to_save]\r\n # training_label_pred = [int(datum['has_scar_pred'][0,-1,0]>=0.5) for datum in training_data_to_save]\r\n # test_label = [int(datum['has_scar'][0,-1,0]) for datum in test_data]\r\n # test_label_pred = [int(datum['has_scar_pred'][0,-1,0]>=0.5) for datum in test_data]\r\n training_label = [int(datum['has_scar'][0,0]) for datum in training_data_to_save]\r\n training_label_pred = [int(datum['has_scar_pred'][0,0]>=0.5) for datum in training_data_to_save]\r\n test_label = [int(datum['has_scar'][0,0]) for datum in test_data]\r\n test_label_pred = [int(datum['has_scar_pred'][0,0]>=0.5) for datum in test_data]\r\n\r\ndebug_plot_pred = False\r\nif debug_plot_pred: \r\n from utils.plot import plot_multi_strainmat_with_curves\r\n plot_multi_strainmat_with_curves(\r\n data=training_data_to_save, strainmat_type=config['data']['input_info'][0]['type'], curve_types=curve_types_to_plot, \r\n fig=None, axs=None, \r\n legends=None, title=None, subtitles=[datum['patient_slice_name'] for datum in training_data_to_save], \r\n vmin=-0.2, vmax=0.2, flipTOS=False, flipStrainMat=False, \r\n colors=None)\r\n plot_multi_strainmat_with_curves(\r\n data=test_data, strainmat_type=config['data']['input_info'][0]['type'], curve_types=curve_types_to_plot, \r\n fig=None, axs=None, \r\n legends=None, title=None, subtitles=[datum['patient_slice_name'] for datum in test_data], \r\n vmin=-0.2, vmax=0.2, flipTOS=False, flipStrainMat=False, \r\n colors=None)\r\n\r\ndebug_plot_CAM = False\r\nif debug_plot_CAM:\r\n from utils.CAM_utils import get_target_sector\r\n from modules.visualization.pytorch_grad_cam import GradCAM, ScoreCAM, GradCAMPlusPlus, AblationCAM, XGradCAM, EigenCAM\r\n # from utils.scar_utils import find_connected_components_binary_1d\r\n net.network.double()\r\n linear_layer_idx = np.where([type(layer) is torch.nn.modules.linear.Linear for layer in net.network.layers])[0]\r\n if type(net.network.layers[linear_layer_idx[0] - 1]) is torch.nn.modules.flatten.Flatten:\r\n layer_before_first_linear = net.network.layers[linear_layer_idx[0] - 2]\r\n else:\r\n layer_before_first_linear = net.network.layers[linear_layer_idx[0] - 1]\r\n conv_layers = [layer for layer in net.network.layers if type(layer) is torch.nn.modules.conv.Conv2d]\r\n linear_layers = [layer for layer in net.network.layers if type(layer) is torch.nn.modules.linear.Linear]\r\n last_conv_layer = conv_layers[-1]\r\n first_conv_layer = conv_layers[0]\r\n target_layer = last_conv_layer\r\n # target_layer = layer_before_first_linear\r\n cam = GradCAM(model=net.network, target_layer=target_layer, use_cuda=True)\r\n \r\n if exp_type in ['reg']:\r\n cam_outout_type = 'reg'\r\n elif exp_type in ['cls']:\r\n cam_outout_type = 'cls'\r\n \r\n \r\n for target_category in [-1]:\r\n ic(target_category)\r\n # for datum in training_data_raw + test_data + training_data_to_save:\r\n for datum in test_data + training_data_to_save:\r\n input_data = datum\r\n input_tensor = torch.tensor(datum[config['data']['input_info'][0]['type']])\r\n # scar_regions = find_connected_components_binary_1d((datum['scar_sector_label']).astype(np.int)[0,1,:], order = 'size')[0]\r\n # if len(scar_regions) > 0:\r\n # largest_scar_region_center = scar_regions[0]['center']\r\n # else:\r\n # largest_scar_region_center = 60\r\n target_sector_type = show_config.get('CAM_target_sector', 'center_sector')\r\n target_sector = get_target_sector(datum, config['data']['output_info'][0]['type'], target_sector_type)\r\n # target_sector = 0\r\n \r\n # datum_pred = net.pred(datum, training_dataset.input_types, training_dataset.output_types)\r\n cam_scar_center = cam(input_datum = input_data, \r\n input_types = training_dataset.input_types,\r\n output_types = training_dataset.output_types,\r\n device = device,\r\n task_type = cam_outout_type, \r\n sector_idx = target_sector, \r\n target_category=target_category, \r\n aug_smooth=False, eigen_smooth=False, \r\n counter_factual=False,\r\n evaluation_config = config['eval'])\r\n \r\n # cam_scar_center = cam(input_tensor=input_tensor, output_type = cam_outout_type, sector_idx = largest_scar_region_center, target_category=target_category, aug_smooth=False, eigen_smooth=True, counter_factual=False)\r\n # counter_cam_scar_center = cam(input_tensor=input_tensor, output_type = cam_outout_type, sector_idx = largest_scar_region_center, target_category=target_category, aug_smooth=False, eigen_smooth=True, counter_factual=True)\r\n datum['cam'] = cam_scar_center\r\n datum['cam']['sector'] = target_sector\r\n \r\n from utils.plot import plot_multi_strainmat_with_curves_and_activation_map\r\n data_to_show = test_data[:4]\r\n # data_to_show = test_data[-4:]\r\n # data_to_show = training_data_to_save[:4]\r\n plot_multi_strainmat_with_curves_and_activation_map(\r\n data=data_to_show, strainmat_type=config['data']['input_info'][0]['type'], curve_types=curve_types_to_plot, \r\n cam_data_types=training_dataset.output_types + ['total_loss'], counter_cam_data_types=training_dataset.output_types, \r\n fig=None, axs=None, \r\n legends=None, title=None, subtitles=[datum['patient_slice_name'] for datum in data_to_show], \r\n vmin=-0.2, vmax=0.2, flipTOS=False, flipStrainMat=False, \r\n colors=None,\r\n check_activation_sectors = [datum['cam']['sector'] for datum in data_to_show])\r\n \r\n \r\n\r\nsave_CAM = False\r\nif save_CAM: \r\n save_test_results_CAM_filename_full = str(\r\n PurePath(config['exp_parent_path'], 'test_results_CAM', f\"{trail_name}-test-results.png\"))\r\n save_training_results_CAM_filename_full = str(\r\n PurePath(config['exp_parent_path'], 'training_results_CAM', f\"{trail_name}-train-results.png\"))\r\n \r\n from modules.visualization.pytorch_grad_cam import GradCAM, ScoreCAM, GradCAMPlusPlus, AblationCAM, XGradCAM, EigenCAM\r\n from utils.scar_utils import find_connected_components_binary_1d\r\n net.network.double()\r\n \r\n last_conv_layer = [layer for layer in net.network.layers if type(layer) is torch.nn.modules.conv.Conv2d][-1]\r\n target_layer = last_conv_layer\r\n cam = GradCAM(model=net.network, target_layer=target_layer, use_cuda=True)\r\n \r\n if exp_type in ['reg']:\r\n cam_outout_type = 'reg'\r\n elif exp_type in ['cls']:\r\n cam_outout_type = 'cls'\r\n \r\n target_category = -1\r\n # for datum in training_data_raw + test_data + training_data_to_save:\r\n for datum in test_data + training_data_to_save:\r\n input_data = datum\r\n input_tensor = torch.tensor(datum[config['data']['input_info'][0]['type']])\r\n \r\n # if any([scar_type in training_dataset.output_types for scar_type in ['scar_sector_label', 'scar_sector_distmap']]):\r\n # target_sector = get_target_sector(datum, config['data']['output_info'][0]['type'], 'scar_center')\r\n # else:\r\n # target_sector = get_target_sector(datum, config['data']['output_info'][0]['type'], 'difference')\r\n target_sector_type = show_config.get('CAM_target_sector', 'center_sector')\r\n target_sector = get_target_sector(datum, config['data']['output_info'][0]['type'], target_sector_type)\r\n \r\n # datum_pred = net.pred(datum, training_dataset.input_types, training_dataset.output_types)\r\n cam_scar_center = cam(input_datum = input_data, \r\n input_types = training_dataset.input_types,\r\n output_types = training_dataset.output_types,\r\n device = device,\r\n task_type = cam_outout_type, \r\n sector_idx = target_sector, \r\n target_category=target_category, \r\n aug_smooth=False, eigen_smooth=True, \r\n counter_factual=False,\r\n evaluation_config = config['eval'])\r\n \r\n # cam_scar_center = cam(input_tensor=input_tensor, output_type = cam_outout_type, sector_idx = largest_scar_region_center, target_category=target_category, aug_smooth=False, eigen_smooth=True, counter_factual=False)\r\n # counter_cam_scar_center = cam(input_tensor=input_tensor, output_type = cam_outout_type, sector_idx = largest_scar_region_center, target_category=target_category, aug_smooth=False, eigen_smooth=True, counter_factual=True)\r\n datum['cam'] = cam_scar_center\r\n datum['cam']['sector'] = target_sector\r\n \r\n save_multi_strainmat_with_curves_and_activation_map(\r\n data=test_data, strainmat_type=config['data']['input_info'][0]['type'], curve_types=curve_types_to_plot, \r\n save_filename = save_test_results_CAM_filename_full,\r\n cam_data_types=training_dataset.output_types + ['total_loss'], counter_cam_data_types=training_dataset.output_types, \r\n fig=None, axs=None, \r\n legends=None, title=None, subtitles=[datum['patient_slice_name'] for datum in test_data], \r\n vmin=-0.2, vmax=0.2, flipTOS=False, flipStrainMat=False, \r\n colors=None,\r\n check_activation_sectors = [datum['cam']['sector'] for datum in test_data])\r\n \r\n save_multi_strainmat_with_curves_and_activation_map(\r\n data=training_data_to_save, strainmat_type=config['data']['input_info'][0]['type'], curve_types=curve_types_to_plot, \r\n save_filename = save_training_results_CAM_filename_full,\r\n cam_data_types=training_dataset.output_types + ['total_loss'], counter_cam_data_types=training_dataset.output_types, \r\n fig=None, axs=None, \r\n legends=None, title=None, subtitles=[datum['patient_slice_name'] for datum in training_data_to_save], \r\n vmin=-0.2, vmax=0.2, flipTOS=False, flipStrainMat=False, \r\n colors=None,\r\n check_activation_sectors = [datum['cam']['sector'] for datum in training_data_to_save])\r\n \r\n# %% 14. Save Config\r\nconfig['performance'] = {}\r\nconfig['performance']['training_loss'] = training_loss_final\r\nconfig['performance']['valid_loss'] = valid_loss_final\r\n# config['performance']['dafault_loss'] = valid_loss_final\r\nconfig['performance']['dafault_loss'] = valid_reg_loss_final\r\nif save_config:\r\n save_config_filename_full = str(PurePath(config['exp_parent_path'], 'configs', f\"{trail_name}-config.json\"))\r\n\r\n # https://stackoverflow.com/questions/26646362/numpy-array-is-not-json-serializable\r\n class NumpyEncoder(json.JSONEncoder):\r\n def default(self, obj):\r\n if isinstance(obj, np.ndarray):\r\n return obj.tolist()\r\n return json.JSONEncoder.default(self, obj)\r\n\r\n with open(save_config_filename_full, 'w') as file:\r\n # yaml.dump(config, file)\r\n json.dump(config, file, cls=NumpyEncoder)\r\n\r\n# return network, config['performance'], training_data_raw, test_data\r\n\r\n# %% Load performance log file\r\n# exp_trial_performance_log_filename = PurePath(config['exp_parent_path'], 'trial_performance_log.yml')\r\nexp_trial_performance_log_filename = config['exp_parent_path'] + 'trial_performance_log.yml'\r\ntry:\r\n with open(exp_trial_performance_log_filename, 'r') as yamlfile:\r\n exp_trial_performance_log = yaml.safe_load(yamlfile) # Note the safe_load\r\nexcept:\r\n exp_trial_performance_log = None\r\n\r\nif exp_trial_performance_log is None:\r\n exp_trial_performance_log = {config['NNI']['trial_id']: config['performance']}\r\n trail_is_first = True\r\nelse:\r\n exp_trial_performance_log[config['NNI']['trial_id']] = config['performance']\r\n trail_is_first = False\r\n\r\n# Save network model if current performance is better than the best one\r\nif trail_is_first:\r\n save_model = True\r\nelse:\r\n valid_performance_log = [exp_trial_performance_log[trial_id]['dafault_loss'] for trial_id in\r\n exp_trial_performance_log.keys()]\r\n if config['performance']['dafault_loss'] <= min(valid_performance_log):\r\n save_model = True\r\n else:\r\n save_model = False\r\n\r\nif save_model:\r\n save_model_filename = f\"{config['NNI']['trial_name']}-network.pth\"\r\n save_model_filename_full = str(PurePath(config['exp_parent_path'], 'networks', save_model_filename))\r\n # torch.save(network, save_model_filename_full)\r\n net.save_network(save_model_filename_full)\r\n\r\n# Save current performance\r\nwith open(exp_trial_performance_log_filename, 'w') as yamlfile:\r\n yaml.safe_dump(exp_trial_performance_log, yamlfile) # Also note the safe_dump\r\n \r\n#%%\r\n","repo_name":"jr-xing/Multitask-Learning-for-Improved-Late-Mechanical-Activation-Detection-of-Heart-from-Cine-Dense-MRI","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":45561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"2332412204","text":"import tkinter as tk\r\nfrom tkinter import filedialog, Text, messagebox\r\nimport os\r\n\r\nroot = tk.Tk()\r\napps = []\r\n\r\nbuttons = []\r\nbuttonValues = []\r\nbuttonOpenList = []\r\nbuttonLocalizationsList = []\r\nbuttonCount = 0\r\n\r\n#wyciaganie buttonow z txt\r\nif os.path.isfile('buttonLocalizations.txt'):\r\n with open('buttonLocalizations.txt', 'r') as f:\r\n tempLocalizations = f.read()\r\n tempLocalizations = tempLocalizations.split('*')\r\n Lozalizations = [x for x in tempLocalizations if x.strip()]\r\n for i in Lozalizations:\r\n i = i.split(',')\r\n if (i != \"\"):\r\n buttonLocalizationsList.append(i[0])\r\n buttonLocalizationsList.append(i[1])\r\n buttonCount += 1\r\n\r\nif os.path.isfile('buttonOpenLists.txt'):\r\n with open('buttonOpenLists.txt', 'r') as f:\r\n tempOpenLists = f.read()\r\n tempOpenLists = tempOpenLists.split('*')\r\n OpenLists = [x for x in tempOpenLists if x.strip()]\r\n for i in OpenLists:\r\n print(i)\r\n if(i != \"\"):\r\n buttonOpenList.append(i)\r\n\r\nif os.path.isfile('buttonValues.txt'):\r\n with open('buttonValues.txt', 'r') as f:\r\n tempValues = f.read()\r\n tempValues = tempValues.split('*')\r\n Values = [x for x in tempValues if x.strip()]\r\n for i in Values :\r\n i = i.split(',')\r\n if(i != \"\"):\r\n buttonValues.append(i[0])\r\n buttonValues.append(i[1])\r\n\r\ndef addApp():\r\n\r\n for widget in frame.winfo_children():\r\n widget.destroy()\r\n\r\n filename = filedialog.askopenfilename(initialdir=\"/\", title=\"Select File\",\r\n filetypes=((\"executables\", \"*exe\"), (\"siusiak\", \".\")))\r\n apps.append(filename)\r\n for app in apps:\r\n label = tk.Label(frame, text=app, bg=\"gray\")\r\n label.pack()\r\n\r\ndef clearApp():\r\n global apps\r\n apps = []\r\n for widget in frame.winfo_children():\r\n widget.destroy()\r\n\r\n with open('save.txt', 'w') as f:\r\n for app in apps:\r\n f.write(app + ',')\r\n\r\ndef runApps():\r\n for app in apps:\r\n os.startfile(app)\r\n\r\ndef runAppsWithOpenList(widget):\r\n list = \"\"\r\n for i in range(len(buttons)):\r\n if (buttons[i] == widget):\r\n list = buttonOpenList[i]\r\n break\r\n print(list)\r\n if(list =='1'):\r\n list = \"\"\r\n list = list.split(\",\")\r\n lapps = [x for x in list if x.strip()]\r\n for app in lapps:\r\n print(app)\r\n os.startfile(app)\r\n\r\ndef drag_start(event):\r\n widget = event.widget\r\n widget.startX = event.x\r\n widget.startY = event.y\r\n\r\ndef drag_motion(event):\r\n widget = event.widget\r\n zmianaX = True\r\n zmianaY = True\r\n x = widget.winfo_x() - widget.startX + event.x\r\n y = widget.winfo_y() - widget.startY + event.y\r\n if(x >= 0 and x <= 295):\r\n zmianaX = True\r\n else:\r\n zmianaX = False\r\n\r\n if (y >= 0 and y <= 565):\r\n zmianaY = True\r\n else:\r\n zmianaY = False\r\n if(zmianaX and zmianaY):\r\n widget.place(x=x,y=y)\r\n else :\r\n if(zmianaX and zmianaY == False):\r\n widget.place(x = x, y=widget.winfo_y())\r\n else:\r\n if (zmianaX == False and zmianaY):\r\n widget.place(x=widget.winfo_x(), y=y)\r\n else:\r\n widget.place(x=widget.winfo_x(), y=widget.winfo_y())\r\n\r\ndef buttonDestroy(widget):\r\n global buttonCount\r\n j = 0\r\n for i in range(len(buttons)):\r\n if(buttons[i] == widget.widget):\r\n buttons.pop(i)\r\n break\r\n j += 1\r\n buttonOpenList.pop(j)\r\n buttonValues.pop(j*2)\r\n buttonValues.pop(j*2)\r\n buttonCount -= 1\r\n widget.widget.destroy()\r\n\r\ndef makeShort():\r\n frameShort = tk.Frame(root)\r\n frameShort.place(relwidth=0.6, relheight=0.95, relx=0.02, rely=0.02)\r\n tk.Label(frameShort, text=\"QuickPick Button Name\").grid(row=0)\r\n tk.Label(frameShort, text=\"Color of Button\").grid(row=1)\r\n e1 = tk.Entry(frameShort)\r\n e2 = tk.Entry(frameShort)\r\n e1.grid(row=0, column=1)\r\n e2.grid(row=1, column=1)\r\n\r\n def ConfirmButtonChoose():\r\n global buttonCount\r\n global apps\r\n nazwa = e1.get()\r\n kolor = e2.get()\r\n openList = \"\"\r\n for app in apps:\r\n openList = openList + app + \",\"\r\n try:\r\n ButtonMade = tk.Button(buttonFrame,text=nazwa, bg=kolor, padx=10, pady=5, fg=\"white\")\r\n except:\r\n messagebox.showerror(title = \"siusiak\", message = \"nie poprawnie wpisany kolor\")\r\n ButtonMade.place(relx = 0,rely = 0)\r\n buttonCount += 1\r\n buttonValues.append(nazwa)\r\n buttonValues.append(kolor)\r\n ButtonMade[\"command\"] = lambda widg=ButtonMade: runAppsWithOpenList(widg)\r\n ButtonMade.bind(\"\", drag_start)\r\n ButtonMade.bind(\"\", drag_motion)\r\n ButtonMade.bind(\"\", lambda widg = ButtonMade: buttonDestroy(widg))\r\n buttons.append(ButtonMade)\r\n openList = \"\"\r\n for app in apps:\r\n openList = openList + app + \",\"\r\n buttonOpenList.append(openList)\r\n clearApp()\r\n for widget in frameShort.winfo_children():\r\n widget.destroy()\r\n frameShort.destroy()\r\n\r\n\r\n Confirm = tk.Button(frameShort, text=\"Confirm Button\", padx=10, pady=5, fg=\"white\", bg=\"#893E42\", command=ConfirmButtonChoose)\r\n Confirm.place(relx=0.20, rely=0.10)\r\n\r\ndef OnQuit():\r\n #localizations\r\n with open(\"buttonLocalizations.txt\", \"w\") as f:\r\n for button in buttons:\r\n f.write(str(button.winfo_x()) + \",\")\r\n f.write(str(button.winfo_y()) + \"*\")\r\n\r\n with open(\"buttonValues.txt\", \"w\") as f:\r\n i = 1\r\n for buttonValue in buttonValues:\r\n f.write(str(buttonValue))\r\n if(i%2==0):\r\n f.write(\"*\")\r\n else:\r\n f.write(\",\")\r\n i += 1\r\n\r\n with open(\"buttonOpenLists.txt\", \"w\") as f:\r\n for buttonOpenLis in buttonOpenList:\r\n if(buttonOpenLis == \"\"):\r\n f.write(\"1\")\r\n f.write(str(buttonOpenLis) + \"*\")\r\n root.destroy()\r\n\r\ncanvas = tk.Canvas(root, height = 700, width= 1200, bg=\"#263D42\")\r\ncanvas.pack()\r\n\r\nframeShort = tk.Frame(root)\r\n\r\nframe = tk.Frame(root)\r\nframe.place(relwidth=0.6, relheight=0.95, relx = 0.02, rely = 0.02)\r\n\r\nbuttonFrame = tk.Frame(root, bg=\"#263D42\")\r\nbuttonFrame.place(relx = 0.65, rely = 0.15, relwidth=0.3, relheight=0.85)\r\n\r\nprint(\"tworzenie\")\r\n#tworzenie przyciskow z txt\r\nfor i in range(buttonCount):\r\n nazwa = buttonValues[i*2]\r\n kolor = buttonValues[i*2+1]\r\n x = int(buttonLocalizationsList[i*2])\r\n y = int(buttonLocalizationsList[i*2+1])\r\n ButtonMade = tk.Button(buttonFrame, text=nazwa, bg=kolor, padx=10, pady=5, fg=\"white\")\r\n ButtonMade[\"command\"] = lambda widg = ButtonMade: runAppsWithOpenList(widg)\r\n ButtonMade.place(x=x, y=y)\r\n ButtonMade.bind(\"\", drag_start)\r\n ButtonMade.bind(\"\", drag_motion)\r\n ButtonMade.bind(\"\", lambda widg=ButtonMade: buttonDestroy(widg))\r\n buttons.append(ButtonMade)\r\n\r\n\r\nopenFile = tk.Button(root, text=\"Open File\", padx=10, pady=5, fg=\"white\", bg=\"#453E42\", command = addApp)\r\nopenFile.place(relx = 0.65,rely = 0.02)\r\n\r\nrunApps = tk.Button(root, text=\"Run Apps\", padx=10, pady=5, fg=\"white\", bg=\"#453E42\", command=runApps)\r\nrunApps.place(relx = 0.75,rely = 0.02)\r\n\r\nclearApps = tk.Button(root, text=\"Clear App List\", padx=10, pady=5, fg=\"white\", bg=\"#453E42\", command=clearApp)\r\nclearApps.place(relx = 0.75,rely = 0.1)\r\n\r\nmakeShort = tk.Button(root, text=\"Make Own QuickPick Button\", padx=10, pady=5, fg=\"white\", bg=\"#453E42\", command=makeShort)\r\nmakeShort.place(relx = 0.84,rely = 0.02)\r\n\r\nfor app in apps:\r\n Label = tk.Label(frame, text=app)\r\n\r\nroot.protocol(\"WM_DELETE_WINDOW\", OnQuit)\r\nroot.mainloop()\r\n","repo_name":"Msaters/QuickOpenTool","sub_path":"PrzyciskiDoSciezek/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"14992399665","text":"# 909. Snakes and Ladders\n# 🟠Medium\n#\n# https://leetcode.com/problems/snakes-and-ladders/\n#\n# Tags: Array - Breadth-First Search - Matrix\n\nimport timeit\nfrom heapq import heappop, heappush\nfrom typing import List\n\n\n# We want to find the minimum distance to travel from a node to another\n# in an unweighted directed graph, each node has edges to the following\n# 6 nodes and some nodes have extra edges. BFS is a good option to\n# travel the unweighted graph because we move one edge at a time and\n# count the number of edges (rolls) we take until we land in the target.\n#\n# Time complexity: O(n^2) - Potentially, from each node we can reach\n# any other node but bfs will travel only one path because we only\n# enqueue a node the first time we see it. The board is n*n so n^2 cells.\n# Space complexity: O(n^2) - The dictionary could end up having one\n# entry per cell in the input, the queue can hold an entire level, which\n# could be more than half the board, for example in a 3x3 board.\n#\n# Runtime 105 ms Beats 97.10%\n# Memory 14 MB Beats 67.63%\nclass BFS:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n # Store the length of one row.\n n = len(board)\n # Store the target index.\n target = n * n\n # Dictionary of {cells visited: number of rolls to land there}.\n visited = {1: 0}\n # A queue of cells that we landed at in the last roll.\n q = [1]\n for start_idx in q:\n for landing_idx in range(start_idx + 1, start_idx + 7):\n # Use the index to compute the corresponding position in\n # the board. This can be used as a template to convert\n # indexes between a flat array and a Boustrophedon style\n # matrix.\n row, col = (landing_idx - 1) // n, (landing_idx - 1) % n\n cell_value = board[~row][col if row % 2 == 0 else ~col]\n # If the cell is the start of a snake or ladder, we will\n # be landing at its end cell.\n if cell_value != -1:\n landing_idx = cell_value\n # If we land in the target cell, return the number of\n # rolls needed to get there.\n if landing_idx == target:\n return visited[start_idx] + 1\n # If this is the first time that we land in a given\n # position, mark it as visited and append it to the\n # queue.\n if landing_idx not in visited:\n visited[landing_idx] = visited[start_idx] + 1\n q.append(landing_idx)\n return -1\n\n\n# Runtime 106 ms Beats 96.68%\n# Memory 14.4 MB Beats 5.60%\nclass Dijkstra:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n n = len(board)\n target = n * n\n # Flatten the input board to access snakes and ladders easily.\n cells = [-1] + [\n item\n for i, row in enumerate(reversed(board))\n for item in (row[::-1] if i % 2 else row)\n ]\n least_rolls = [0] + [float(\"inf\")] * (n * n)\n # A recursive function that walks 6 steps from the start\n # branching into any directions that the player could go.\n def move(pos: int, rolls: int, steps: int) -> None:\n if steps == 0 or pos > target:\n return\n # We can reach this position in this many rolls.\n heappush(heap, (rolls, pos))\n # If this position has a snake or a ladder, we can reach\n # that position in the same number of rolls.\n if cells[pos] != -1:\n move(cells[pos], rolls, steps)\n # We can reach the next position with one more move.\n move(pos + 1, rolls, steps - 1)\n\n # A priority queue with tuples that contain:\n # (number of rolls to get here, position) initialized with the\n # position 1 and 0 rolls.\n heap = [(0, -1)]\n # We are guaranteed to be able to reach the target.\n while heap:\n rolls_prev, start = heappop(heap)\n rolls = rolls_prev + 1\n for i in range(1, 7):\n landing_pos = -start + i\n if cells[landing_pos] != -1:\n landing_pos = cells[landing_pos]\n if landing_pos == target:\n return rolls\n # Regular cell.\n if rolls < least_rolls[landing_pos]:\n least_rolls[landing_pos] = rolls\n heappush(heap, (rolls, -landing_pos))\n return -1\n\n\ndef test():\n executors = [\n BFS,\n Dijkstra,\n ]\n tests = [\n [[[-1, -1], [-1, 3]], 1],\n [[[1, 1, -1], [1, 1, 1], [-1, 1, 1]], -1],\n [\n [\n [-1, -1, -1, -1, -1, -1],\n [-1, -1, -1, -1, -1, -1],\n [-1, -1, -1, -1, -1, -1],\n [-1, 35, -1, -1, 13, -1],\n [-1, -1, -1, -1, -1, -1],\n [-1, 15, -1, -1, -1, -1],\n ],\n 4,\n ],\n ]\n for executor in executors:\n start = timeit.default_timer()\n for _ in range(1):\n for col, t in enumerate(tests):\n sol = executor()\n result = sol.snakesAndLadders(t[0])\n exp = t[1]\n assert result == exp, (\n f\"\\033[93m» {result} <> {exp}\\033[91m for\"\n + f\" test {col} using \\033[1m{executor.__name__}\"\n )\n stop = timeit.default_timer()\n used = str(round(stop - start, 5))\n cols = \"{0:20}{1:10}{2:10}\"\n res = cols.format(executor.__name__, used, \"seconds\")\n print(f\"\\033[92m» {res}\\033[0m\")\n\n\ntest()\n","repo_name":"raul-sauco/coding-challenges","sub_path":"leetcode/snakes-and-ladders.py","file_name":"snakes-and-ladders.py","file_ext":"py","file_size_in_byte":5761,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"19723372561","text":"#!/usr/bin/env python\n\nimport json\nimport plistlib\nimport subprocess\n\noutput = []\nall_images = []\nfor image in plistlib.readPlistFromString(\n subprocess.check_output([\"/usr/bin/hdiutil\", \"info\",\n \"-plist\"]))[\"images\"]:\n entities_length = len(image[\"system-entities\"])\n volume_path = image[\"system-entities\"][entities_length - 1][\"mount-point\"]\n image_file_path = image[\"image-path\"]\n imageinfo = {\n \"volume_path\": volume_path,\n \"image_file_path\": image_file_path\n }\n all_images.append(imageinfo)\n item = {\n \"title\": volume_path,\n \"subtitle\": image_file_path,\n \"icon\": image[\"icon-path\"],\n \"images\": [imageinfo],\n \"action\": \"eject.py\",\n \"actionRunsInBackground\": True,\n \"actionRetrunsItems\": False\n }\n output.append(item)\n\nif len(output) > 1:\n item = {\n \"title\": \"Eject & Trash All\",\n \"images\": all_images,\n \"action\": \"eject.py\",\n \"actionRunsInBackground\": True,\n \"actionRetrunsItems\": False\n }\n output.append(item)\n\nprint(json.dumps(output))\n","repo_name":"rishifter/launchbar-actions","sub_path":"eject-and-trash.lbaction/Contents/Scripts/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"77"}
+{"seq_id":"36385883584","text":"import sqlite3\n\n\ndef createdb():\n db = sqlite3.connect('database.db')\n c = db.cursor()\n c.execute('''CREATE TABLE IF NOT EXISTS users\n (id INTEGER PRIMARY KEY, user_id INTEGER, user_status TEXT, lst_page INTEGER)''')\n db.commit()\n db.close()\n\n\ndef page(user_id):\n db = sqlite3.connect('database.db')\n c = db.cursor()\n c.execute('SELECT lst_page FROM users WHERE user_id = ?', (user_id,))\n result = c.fetchone()\n db.close()\n if result:\n return result[0]\n else:\n return None\n\ndef update_lst_page(user_id, new_lst_page):\n db = sqlite3.connect('database.db')\n c = db.cursor()\n c.execute('UPDATE users SET user_status = ? WHERE user_id = ?', (new_lst_page, user_id))\n db.commit()\n db.close()\n\n\ndef get_user_status(user_id):\n db = sqlite3.connect('database.db')\n c = db.cursor()\n c.execute('SELECT user_status FROM users WHERE user_id = ?', (user_id,))\n result = c.fetchone()\n db.close()\n if result:\n return result[0]\n else:\n return None\n\n\nimport sqlite3\n\ndef update_user_status(user_id, new_status):\n db = sqlite3.connect('database.db')\n c = db.cursor()\n c.execute('UPDATE users SET user_status = ? WHERE user_id = ?', (new_status, user_id))\n db.commit()\n db.close()\n\ndef add_user(user_id, user_status):\n db = sqlite3.connect('database.db')\n c = db.cursor()\n\n c.execute('SELECT COUNT(*) FROM users WHERE user_id = ?', (user_id,))\n result = c.fetchone()\n if result[0] > 0:\n db.close()\n return\n c.execute('INSERT OR IGNORE INTO users (user_id, user_status, lst_page) VALUES (?, ?, ?)', (user_id, user_status,\n 0))\n db.commit()\n db.close()","repo_name":"lulislaw/VM_monitor","sub_path":"bot/status_base.py","file_name":"status_base.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"15584872116","text":"def OpenXL(data):\r\n try:\r\n# this is opening a txt and splitting it at , \r\n with open(data) as txt:\r\n read = txt.readline()\r\n splitter = read.strip().split(\",\")\r\n return(splitter)\r\n except IOError as err:\r\n print('file error'+err)\r\n\r\n\r\ndef Convert(time_string):\r\n # this is converting the - and : characters to .\r\n if '-' in time_string:\r\n splitter = '-'\r\n elif ':' in time_string:\r\n splitter = ':' \r\n else:\r\n return(time_string) \r\n (mins,secs)= time_string.split(splitter)\r\n return(mins + '.' + secs)\r\n\r\n\r\ndef Run(file='c:/'):\r\n# This is opening a txt file and calling both of the above\r\n# methods, then converting it into a readable dictionary \r\n name=OpenXL(file) \r\n (name1,dob1)=name.pop(0),name.pop(0)\r\n info={'Name':name1,'Dob':dob1,'Fastest Times':str(sorted(set([Convert(t)for t in name]))[:3])}\r\n print(info) # The above : means equals \r\n \r\nRun('c:/PHF/james2.txt')\r\nRun(\"c:/PHF/julie2.txt\")\r\nRun(\"c:/PHF/mikey2.txt\")\r\nRun(\"c:/PHF/sarah2.txt\")\r\n\r\n","repo_name":"TDBJR/Study","sub_path":"Dictionary2.py","file_name":"Dictionary2.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"1638655892","text":"from keras.models import Sequential\nfrom keras.layers import ZeroPadding2D\nfrom keras.layers import Conv2D, MaxPooling2D, UpSampling2D, Dropout, Flatten, Dense\nfrom keras.layers import Input, Conv2DTranspose, concatenate\nfrom keras.models import Model\n\ndef model_init(input_shape):\n\n model = Sequential()\n model.add(Conv2D(32, kernel_size=(3, 3),\n activation='relu',\n input_shape=input_shape))\n model.add(Conv2D(64, (3, 3), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n model.add(Flatten())\n model.add(Dense(128, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(10, activation='softmax'))\n\n return model","repo_name":"jiameng1010/modality_networks_project","sub_path":"source/model2.py","file_name":"model2.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"23916404616","text":"# l1=[1,2,3]\n# l2=[1,3,4]\n# l1.extend(l2)\n# print(l1)\n# print(l1+l2)\n# l1.clear()\n# print\n\nx=[12,10,5,3]\ns1=[]\nfor i in range(len(x)):\n s=x[::]\n s.pop(i)\n total =sum(s)\n s1.append(total)\n #s.append(x)\nprint(\"output\",s1)\n\n\n","repo_name":"revathigit98/revathi","sub_path":"hellopy/new.py","file_name":"new.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"15263842069","text":"n=int(input())\narr = list(map(int, input().split()))\narr.sort()\n# print(arr)\n# num_set=set([])\nsum_val=0\nfor i in range(-1,-len(arr)-1,-1):\n # print(sum(arr[:i]))\n if sum(arr[:i]) answer:\n print('小一点')\n else:\n print('猜对了')\n break\n\nif counter > 7:\n print('您的智商有待提高!!')\n\n","repo_name":"xuzhang0636/100-days-python-practice","sub_path":"day4/day4-3.py","file_name":"day4-3.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"18093797458","text":"\"\"\"Tests checking for link access from outside.\"\"\"\nimport fauxfactory\nimport pytest\nfrom widgetastic.utils import partial_match\n\nfrom cfme import test_requirements\nfrom cfme.infrastructure.provider import InfraProvider\nfrom cfme.infrastructure.provider.rhevm import RHEVMProvider\nfrom cfme.infrastructure.provider.virtualcenter import VMwareProvider\nfrom cfme.markers.env_markers.provider import ONE\nfrom cfme.utils.appliance.implementations.ui import navigate_to\nfrom cfme.utils.browser import browser\nfrom cfme.utils.wait import wait_for\n\npytestmark = [\n pytest.mark.meta(server_roles=\"-automate\"), # To prevent the provisioning itself.\n test_requirements.service,\n pytest.mark.provider(classes=[InfraProvider], scope=\"module\", selector=ONE),\n pytest.mark.usefixtures('setup_provider_modscope')\n]\n\n\n@pytest.fixture(scope=\"module\")\ndef provisioning(provider):\n return provider.data.get(\"provisioning\", {})\n\n\n@pytest.fixture(scope=\"module\")\ndef template_name(provisioning):\n return provisioning.get(\"template\")\n\n\n@pytest.fixture(scope=\"module\")\ndef vm_name():\n return fauxfactory.gen_alphanumeric(length=16)\n\n\n@pytest.fixture(scope=\"module\")\ndef generated_request(appliance, provider, provisioning, template_name, vm_name):\n \"\"\"Creates a provision request, that is not automatically approved, and returns the search data.\n\n After finishing the test, request should be automatically deleted.\n\n Slightly modified code from :py:module:`cfme.tests.infrastructure.test_provisioning`\n \"\"\"\n if provider.one_of(RHEVMProvider) and provisioning.get('vlan') is None:\n pytest.skip('rhevm requires a vlan value in provisioning info')\n first_name = fauxfactory.gen_alphanumeric()\n last_name = fauxfactory.gen_alphanumeric()\n notes = fauxfactory.gen_alphanumeric()\n e_mail = f\"{first_name}@{last_name}.test\"\n host, datastore = list(map(provisioning.get, ('host', 'datastore')))\n vm = appliance.collections.infra_vms.instantiate(name=vm_name,\n provider=provider,\n template_name=template_name)\n view = navigate_to(vm.parent, 'Provision')\n\n provisioning_data = {\n 'request': {\n 'email': e_mail,\n 'first_name': first_name,\n 'last_name': last_name,\n 'notes': notes},\n 'catalog': {\n 'vm_name': vm_name,\n 'num_vms': '10'},\n 'environment':\n {'host_name': {'name': host},\n 'datastore_name': {'name': datastore}},\n 'network':\n {'vlan': partial_match(provisioning['vlan'] if provisioning.get('vlan') else None)}\n }\n\n # Same thing, different names. :\\\n if provider.one_of(RHEVMProvider):\n provisioning_data['catalog']['provision_type'] = 'Native Clone'\n elif provider.one_of(VMwareProvider):\n provisioning_data['catalog']['provision_type'] = 'VMware'\n\n # template and provider names for template selection\n provisioning_data['template_name'] = template_name\n provisioning_data['provider_name'] = provider.name\n\n view.form.fill_with(provisioning_data, on_change=view.form.submit_button)\n request_cells = {\n \"Description\": f\"Provision from [{template_name}] to [{vm_name}###]\",\n }\n provision_request = appliance.collections.requests.instantiate(cells=request_cells)\n yield provision_request\n\n browser().get(appliance.url)\n appliance.server.login_admin()\n\n provision_request.remove_request()\n\n\n@pytest.mark.tier(3)\ndef test_services_request_direct_url(appliance, generated_request):\n \"\"\"Go to the request page, save the url and try to access it directly.\n\n Polarion:\n assignee: nansari\n initialEstimate: 1/8h\n casecomponent: Services\n \"\"\"\n widgetastic = appliance.browser.widgetastic\n selenium = widgetastic.selenium\n assert navigate_to(generated_request, 'Details'), \"could not find the request!\"\n request_url = selenium.current_url\n navigate_to(appliance.server, 'Configuration') # Nav to some other page\n selenium.get(request_url) # Ok, direct access now.\n wait_for(\n lambda: widgetastic.is_displayed(\"//body[contains(@onload, 'miqOnLoad')]\"),\n num_sec=20,\n message=\"wait for a CFME page appear\",\n delay=0.5\n )\n\n\n@pytest.mark.tier(3)\ndef test_copy_request(request, generated_request, vm_name, template_name):\n \"\"\"Check if request gets properly copied.\n\n Polarion:\n assignee: nansari\n initialEstimate: 1/4h\n casecomponent: Services\n \"\"\"\n new_vm_name = f'{vm_name}-xx'\n modifications = {'catalog': {'vm_name': new_vm_name}}\n new_request = generated_request.copy_request(values=modifications)\n request.addfinalizer(new_request.remove_request)\n assert navigate_to(new_request, 'Details')\n","repo_name":"ManageIQ/integration_tests","sub_path":"cfme/tests/services/test_operations.py","file_name":"test_operations.py","file_ext":"py","file_size_in_byte":4852,"program_lang":"python","lang":"en","doc_type":"code","stars":70,"dataset":"github-code","pt":"77"}
+{"seq_id":"5360039595","text":"class Card():\n def __init__(self,card_id,info,status=0, cur_damage=0, cur_life=0):\n self.card_id = card_id\n self.cur_damage = cur_damage\n self.cur_life = cur_life\n self.status = status\n if card_id in [0,-1]:\n card_id = 57\n self.name = info.at[card_id-1,\"Name\"]\n self.gold = info.at[card_id-1,\"Gold\"]\n self.main_class = info.at[card_id-1,\"Main class\"]\n self.initial_damage = info.at[card_id-1,\"Initial damage\"]\n self.initial_life = info.at[card_id-1,\"Initial life\"]\n self.raider = info.at[card_id-1,\"Raider\"]\n self.champion = info.at[card_id-1,\"Champion\"]\n self.pioneer = info.at[card_id-1,\"Pioneer\"]\n self.warchief = info.at[card_id-1,\"Warchief\"]\n self.guard = info.at[card_id-1,\"Guard\"]\n self.deal_damage = info.at[card_id-1,\"Deal Damage\"]\n self.deal_spell_damage = info.at[card_id-1,\"Deal Spell Damage\"]\n self.heal_minion = info.at[card_id-1,\"Heal minion\"]\n self.heal_player = info.at[card_id-1,\"Heal player\"]\n self.buff_damage = info.at[card_id-1,\"Buff Damage\"]\n self.summoner = info.at[card_id-1,\"Summoner\"]\n self.reduce_money = info.at[card_id-1,\"Reduce money\"]\n self.card_draw = info.at[card_id-1,\"Card draw\"]\n self.reduce_enemies_damage = info.at[card_id-1,\"Reduce enemies damage\"]\n self.block_enemies_damage = info.at[card_id-1,\"Block enemies damage\"]\n self.disable_enemies = info.at[card_id-1,\"Disable enemies\"]\n\n def isGuard(self):\n return 1 if self.guard==1 else 0\n\n def totalValue(self):\n return self.deal_damage + self.deal_spell_damage + self.heal_minion + self.heal_player + self.buff_damage + self.summoner + self.reduce_money + self.card_draw + self.reduce_enemies_damage + self.block_enemies_damage + self.disable_enemies\n \n def isNotPioneer(self):\n return 1 if self.pioneer == 0 else 0\n\n def isHellhound(self):\n return 1 if self.card_id == 25 else 0\n\n def isFinalDuel(self):\n return 1 if self.card_id == 56 else 0\n\n def pioneerValue(self):\n if self.card_id == 3:\n return self.card_draw\n elif self.card_id == 4:\n return self.deal_damage\n elif self.card_id == 10:\n return self.reduce_money\n elif self.card_id == 14:\n return self.buff_damage\n elif self.card_id == 19:\n return self.deal_damage\n elif self.card_id == 24:\n return self.summoner\n elif self.card_id == 27:\n return self.disable_enemies\n elif self.card_id == 29:\n return self.deal_damage\n else:\n return 0\n\n def sacrifiedRighteousImmolation(self):\n if self.main_class == 1 or self.gold < 4 :\n return -100\n \n if self.main_class == 2:\n return self.block_enemies_damage * 2\n \n elif self.main_class == 3:\n return self.buff_damage\n \n elif self.main_class == 4:\n return self.deal_damage - 5\n \n elif self.main_class == 5:\n return self.reduce_money\n\n elif self.main_class == 6:\n return self.deal_damage - 5\n\n else:\n return -100\n\n def sacrifiedFinalDuel(self):\n if self.main_class == 1:\n return -100\n \n if self.main_class == 2:\n return self.reduce_enemies_damage\n \n elif self.main_class == 3:\n return self.reduce_enemies_damage\n \n elif self.main_class == 4:\n return self.reduce_money - 20\n \n elif self.main_class == 5:\n return self.card_draw * 6\n\n elif self.main_class == 6:\n return self.reduce_money - 7\n else:\n return -100\n \n def statusList(self):\n return [self.gold,self.main_class,self.initial_damage,self.initial_life,self.raider,self.champion,self.pioneer,self.warchief,self.guard ,self.deal_damage,self.deal_spell_damage ,self.heal_minion,self.heal_player,self.buff_damage,self.summoner,self.reduce_money,self.card_draw,self.reduce_enemies_damage,self.block_enemies_damage,self.disable_enemies]","repo_name":"anhtrangbac99/Quest_of_the_Divinity","sub_path":"Agent/Card/card.py","file_name":"card.py","file_ext":"py","file_size_in_byte":4232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"674885425","text":"\"\"\"\nSample eval data.\n\nThis will sample a jsonl train or eval data based on the slices in the data.\nThis is useful for subsampling a smaller eval dataset.py.\n\nThe output of this file is a files with a subset of sentences from the\ninput file samples such that for each slice in --args.slice, a minimum\nof args.min_sample_size mentions are in the slice (if possible). Once\nthat is satisfied, we sample to get approximately --args.sample_perc of\nmentions from each slice.\n\"\"\"\n\nimport argparse\nimport multiprocessing\nimport os\nimport random\nimport shutil\nfrom collections import defaultdict\n\nimport numpy as np\nimport ujson\nfrom tqdm.auto import tqdm\n\nfrom bootleg.utils import utils\n\nFINAL_COUNTS_PREFIX = \"final_counts\"\nFINAL_SLICE_TO_SENT_PREFIX = \"final_slice_to_sent\"\nFINAL_SENT_TO_SLICE_PREFIX = \"final_sent_to_slices\"\n\n\ndef parse_args():\n \"\"\"Parse args.\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--file\", type=str, default=\"merged.jsonl\")\n parser.add_argument(\n \"--data_dir\",\n type=str,\n default=\"/dfs/scratch0/lorr1/projects/bootleg-data/data/wiki_title_0122\",\n help=\"Where files saved\",\n )\n parser.add_argument(\n \"--out_file_name\",\n type=str,\n default=\"merged_sample.jsonl\",\n help=\"Where files saved\",\n )\n parser.add_argument(\n \"--sample_perc\", type=float, default=0.005, help=\"Perc of each slice to sample\"\n )\n parser.add_argument(\n \"--min_sample_size\",\n type=int,\n default=5000,\n help=\"Min number of mentions per slice\",\n )\n parser.add_argument(\n \"--slice\",\n default=[],\n action=\"append\",\n required=True,\n help=\"Slices to consider when sampling\",\n )\n\n args = parser.parse_args()\n return args\n\n\ndef get_slice_stats(num_processes, file):\n \"\"\"Get true anchor slice counts.\"\"\"\n pool = multiprocessing.Pool(processes=num_processes)\n final_counts = defaultdict(int)\n final_slice_to_sent = defaultdict(set)\n final_sent_to_slices = defaultdict(lambda: defaultdict(int))\n temp_out_dir = os.path.join(os.path.dirname(file), \"_temp\")\n os.mkdir(temp_out_dir)\n\n all_lines = [li for li in open(file)]\n num_lines = len(all_lines)\n chunk_size = int(np.ceil(num_lines / num_processes))\n line_chunks = [\n all_lines[i : i + chunk_size] for i in range(0, num_lines, chunk_size)\n ]\n\n input_args = [\n [i, line_chunks[i], i * chunk_size, temp_out_dir]\n for i in range(len(line_chunks))\n ]\n\n for i in tqdm(\n pool.imap_unordered(get_slice_stats_hlp, input_args, chunksize=1),\n total=len(line_chunks),\n desc=\"Gathering slice counts\",\n ):\n cnt_res = utils.load_json_file(\n os.path.join(temp_out_dir, f\"{FINAL_COUNTS_PREFIX}_{i}.json\")\n )\n sent_to_slices = utils.load_json_file(\n os.path.join(temp_out_dir, f\"{FINAL_SENT_TO_SLICE_PREFIX}_{i}.json\")\n )\n slice_to_sent = utils.load_json_file(\n os.path.join(temp_out_dir, f\"{FINAL_SLICE_TO_SENT_PREFIX}_{i}.json\")\n )\n for k in cnt_res:\n final_counts[k] += cnt_res[k]\n for k in slice_to_sent:\n final_slice_to_sent[k].update(set(slice_to_sent[k]))\n for k in sent_to_slices:\n final_sent_to_slices[k].update(sent_to_slices[k])\n pool.close()\n pool.join()\n shutil.rmtree(temp_out_dir)\n return dict(final_counts), dict(final_slice_to_sent), dict(final_sent_to_slices)\n\n\ndef get_slice_stats_hlp(args):\n \"\"\"Get slice count helper.\"\"\"\n i, lines, offset, temp_out_dir = args\n\n res = defaultdict(int) # slice -> cnt\n slice_to_sent = defaultdict(set) # slice -> sent_idx (for sampling)\n sent_to_slices = defaultdict(\n lambda: defaultdict(int)\n ) # sent_idx -> slice -> cnt (for sampling)\n for line in tqdm(lines, total=len(lines), desc=f\"Processing lines for {i}\"):\n line = ujson.loads(line)\n slices = line.get(\"slices\", {})\n anchors = line[\"gold\"]\n for slice_name in slices:\n for al_str in slices[slice_name]:\n if anchors[int(al_str)] is True and slices[slice_name][al_str] > 0.5:\n res[slice_name] += 1\n slice_to_sent[slice_name].add(int(line[\"sent_idx_unq\"]))\n sent_to_slices[int(line[\"sent_idx_unq\"])].update(res)\n\n utils.dump_json_file(\n os.path.join(temp_out_dir, f\"{FINAL_COUNTS_PREFIX}_{i}.json\"), res\n )\n utils.dump_json_file(\n os.path.join(temp_out_dir, f\"{FINAL_SENT_TO_SLICE_PREFIX}_{i}.json\"),\n sent_to_slices,\n )\n # Turn into list for dumping\n for slice_name in slice_to_sent:\n slice_to_sent[slice_name] = list(slice_to_sent[slice_name])\n utils.dump_json_file(\n os.path.join(temp_out_dir, f\"{FINAL_SLICE_TO_SENT_PREFIX}_{i}.json\"),\n slice_to_sent,\n )\n return i\n\n\ndef main():\n \"\"\"Run.\"\"\"\n args = parse_args()\n print(ujson.dumps(vars(args), indent=4))\n num_processes = int(0.8 * multiprocessing.cpu_count())\n\n in_file = os.path.join(args.data_dir, args.file)\n print(f\"Getting slice counts from {in_file}\")\n slice_counts, slice_to_sents, sent_to_slices = get_slice_stats(\n num_processes, in_file\n )\n\n print(\"****SLICE COUNTS*****\")\n print(ujson.dumps(slice_counts, indent=4))\n\n desired_slices = args.slice\n final_sentences = set()\n new_counts = defaultdict(int)\n for sl_name in desired_slices:\n cur_count = new_counts[sl_name]\n sample_size = max(\n min(args.min_sample_size - cur_count, len(slice_to_sents[sl_name])),\n min(\n int(args.sample_perc * slice_counts[sl_name]) - cur_count,\n len(slice_to_sents[sl_name]),\n ),\n 0,\n )\n if sample_size > 0:\n sents_to_add = random.sample(list(slice_to_sents[sl_name]), k=sample_size)\n final_sentences.update(sents_to_add)\n new_counts = defaultdict(int)\n for sent_id in final_sentences:\n for sl_name2 in sent_to_slices.get(sent_id, {}):\n new_counts[sl_name2] += sent_to_slices.get(sent_id, {}).get(\n sl_name2, 0\n )\n\n out_file = os.path.join(args.data_dir, args.out_file_name)\n print(f\"Outputting results to {out_file}\")\n num_lines = sum([1 for _ in open(in_file)])\n final_cnt = 0\n final_slice_cnts = defaultdict(int)\n with open(out_file, \"w\") as out_f:\n for line in tqdm(\n [ujson.loads(li.strip()) for li in open(in_file)],\n desc=\"Writing out file\",\n total=num_lines,\n ):\n if int(line[\"sent_idx_unq\"]) in final_sentences:\n out_f.write(ujson.dumps(line, ensure_ascii=False) + \"\\n\")\n for sl_name in line.get(\"slices\", {}):\n for al_idx in line[\"slices\"][sl_name]:\n if (\n line[\"slices\"][sl_name][al_idx] > 0.5\n and line[\"gold\"][int(al_idx)] is True\n ):\n final_slice_cnts[sl_name] += 1\n final_cnt += 1\n print(f\"Wrote out {final_cnt} lines to {out_file}\")\n print(\"****FINAL SLICE COUNTS*****\")\n print(ujson.dumps(final_slice_cnts, indent=4))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"HazyResearch/bootleg","sub_path":"bootleg/utils/preprocessing/sample_eval_data.py","file_name":"sample_eval_data.py","file_ext":"py","file_size_in_byte":7403,"program_lang":"python","lang":"en","doc_type":"code","stars":207,"dataset":"github-code","pt":"77"}
+{"seq_id":"41674988485","text":"#!/usr/bin/env python\n\n\"\"\"\n Base class for all of the bot's extensions\n\"\"\"\n\nimport logging\nimport time\n\nlogger = logging.getLogger(__name__)\n\n\nclass ModbotExtension:\n \"\"\"\n Describes the \"interface\" of a bot's module.\n\n All Bot modules must inherit from this class.\n\n It ensures methods mandatory for linking with the main class exist.\n Most of the methods will not perform anything.\n\n Attributes:\n name The name of the extension\n settings Configuration data for a module.\n state Short-lived data common to all modules\n state_last_refresh Last refresh of state (determines when to clean it)\n web_client The client used to send messages\n\n \"\"\"\n\n name = ''\n settings = {}\n state = {'channels': {}, 'users': {}}\n state_last_refresh = 0\n web_client = {}\n\n def __init__(self, web_client, settings):\n \"\"\"\n Stores a reference to the web client (for sending data) and settings\n\n This method should be executed by all inheriting classes.\n The data originates from the main Bot class\n\n :param ModbotWebclient web_client: Slack web client for sending data\n :param dict settings: The settings to be applied by the module\n :return: None\n \"\"\"\n self.web_client = web_client\n self.settings = settings\n self.state_last_refresh = time.time()\n\n def on_message(self, event):\n \"\"\"Does nothing. Triggered when receiving messages from Slack.\"\"\"\n pass\n\n def on_message_deletion(self, event):\n \"\"\"Does nothing. Triggered when messages are deleted.\"\"\"\n pass\n\n def on_message_changed(self, event):\n \"\"\"Does nothing. Triggered when messages are edited.\"\"\"\n pass\n\n def help(self, event):\n \"\"\"Does nothing. Triggered when help is requested.\"\"\"\n pass\n\n def log_info(self, msg, *args, **kwargs):\n \"\"\"Log errors while replacing the user ID with its name.\"\"\"\n if 'user' in kwargs:\n user_data = self.get_user_info(kwargs['user'])\n if user_data:\n msg = msg.replace(\n '%user',\n user_data['profile']['real_name_normalized']\n + ' <' + kwargs['user'] + '>'\n )\n del kwargs['user']\n\n logger.info(msg, *args, **kwargs)\n\n def get_user_info(self, user):\n \"\"\"\n Gets user data, either from the cache or from Slack directly.\n\n Refer to https://api.slack.com/methods/users.info\n\n :param str user: The user ID of the user we're searching for\n :return: The data about the user, in Slack's format\n :rtype: dict\n\n \"\"\"\n if (self.state_last_refresh + 60*10) < time.time():\n self.state = {'channels': {}, 'users': {}}\n self.log_info('[BotExtension] Refreshing cache')\n\n if user not in self.state['users']:\n user_data = self.web_client.users_info(user=user)\n if user_data['ok']:\n self.state['users'][user] = user_data['user']\n return self.state['users'][user]\n else:\n logger.warning('[BotExtension] Couldn\\'t find user %s', user)\n return False\n else:\n return self.state['users'][user]\n\n return False\n\n def get_channel_info(self, channel):\n \"\"\"\n Gets data on a given channel.\n\n Refer to https://api.slack.com/methods/conversations.list\n\n :param str channel: The channel ID or label to find\n :return: The data about the channel, in Slack's format\n :rtype: dict\n\n \"\"\"\n if (self.state_last_refresh + 60*10) < time.time() \\\n or not self.state['channels']:\n self.state = {'channels': {}, 'users': {}}\n self.log_info('[BotExtension] Refreshing cache')\n self.state['channels'] = \\\n self.web_client.conversations_list()['channels']\n\n # Parse the channel name\n # Received either as #channel or <#channel_id|channel_name>\n if '<' in channel:\n channel = channel.split('|')[0][2:]\n elif channel[0] == '#':\n channel = channel[1:]\n\n # Check if the channel is there (either ID or name)\n channel_found = [chan\n for chan in self.state['channels']\n if chan['name'] == channel\n or chan['id'] == channel\n ]\n\n if channel_found:\n return channel_found[0]\n return False\n\n def user_is_admin(self, user):\n \"\"\"\n Returns True if the user is an admin, False otherwise\n\n :param str user: The user ID of the user we're searching for\n :return: True if the user is admin, False otherwise\n :rtype: Boolean\n\n \"\"\"\n user_data = self.get_user_info(user)\n\n if user_data:\n return user_data['is_admin']\n else:\n return False\n\n def user_is_owner(self, user):\n \"\"\"\n Returns True if the user is an owner, False otherwise\n\n :param str user: The user ID of the user we're searching for\n :return: True if the user is owner, False otherwise\n :rtype: Boolean\n\n \"\"\"\n user_data = self.get_user_info(user)\n\n if user_data:\n return user_data['is_owner']\n else:\n return False\n\n\nclass ExtensionStore(object):\n \"\"\"\n The extension store\n\n All modbot classes must register themselves via register_extension\n\n Attributes:\n extensions All registered extensions\n\n \"\"\"\n\n extensions = {}\n\n def register_extension(self, extension_class):\n \"\"\"\n Registers an extension\n\n All extensions must call this method to get registered\n\n :param object extension_class: The extension's class\n \"\"\"\n if extension_class.name not in self.extensions:\n self.extensions[extension_class.name.lower()] = {\n 'class': extension_class,\n 'loaded': False,\n 'enabled': False,\n 'enabled_for_im': True,\n 'enabled_for_channels': set(),\n }\n logging.info(\n '[ExtStore] Extension ' + extension_class.name + ' registered'\n )\n\n def load_extension(self, name, slack_web_client, ext_settings={}):\n \"\"\"\n Loads an extension\n\n This allows the extension to link with the web client\n\n :param object slack_web_client: The Modbot web client\n :param dict ext_settings: Extension settings as set in main program\n \"\"\"\n if not self.is_registered(name):\n logging.info('[ExtStore] Extension ' + name + ' unknown')\n return False\n if not self.is_loaded(name):\n self.extensions[name.lower()].update({\n 'instance': self.extensions[name.lower()]['class'](\n slack_web_client, ext_settings\n ),\n 'loaded': True,\n })\n logging.info('[ExtStore] Extension ' + name + ' loaded')\n return True\n\n def enable_extension(self, name):\n \"\"\"\n Enables an extension\n\n This allows the extension to receive data from Slack\n\n :param str name: The extension's name\n :return: True if extension was enabled, False otherwise\n :rtype: Boolean\n \"\"\"\n if not self.is_registered(name):\n logging.info(\n '[ExtStore] Extension ' + name + ' not registered'\n )\n return False\n elif not self.is_loaded(name):\n logging.info(\n '[ExtStore] Extension ' + name + ' not loaded'\n )\n return False\n else:\n self.extensions[name.lower()].update({\n 'enabled': True,\n })\n logging.info(\n '[ExtStore] Extension ' + name + ' enabled'\n )\n return True\n\n def enable_extension_for(self, name, channel):\n \"\"\"\n Enables an extension for a given channel\n\n This allows the extension to receive data from Slack for this channel\n\n :param str name: The extension's name\n :return: True if extension was enabled, False otherwise\n :rtype: Boolean\n \"\"\"\n if not self.is_registered(name):\n logging.info(\n '[ExtStore] Extension ' + name + ' not registered'\n )\n return False\n elif not self.is_loaded(name):\n logging.info(\n '[ExtStore] Extension ' + name + ' not loaded'\n )\n return False\n else:\n self.extensions[name.lower()]['enabled_for_channels'].add(channel)\n logging.info(\n '[ExtStore] Extension ' + name + ' enabled for ' + channel\n )\n return True\n\n def enable_extension_for_im(self, name):\n \"\"\"\n Enables an extension for IM messages\n\n This allows the extension to receive data from Slack for IM messages\n\n :param str name: The extension's name\n :return: True if extension was enabled, False otherwise\n :rtype: Boolean\n \"\"\"\n if not self.is_registered(name):\n logging.info(\n '[ExtStore] Extension ' + name + ' not registered'\n )\n return False\n elif not self.is_loaded(name):\n logging.info(\n '[ExtStore] Extension ' + name + ' not loaded'\n )\n return False\n else:\n self.extensions[name.lower()]['enabled_for_im'] = True\n logging.info(\n '[ExtStore] Extension ' + name + ' enabled for IMs'\n )\n return True\n\n def disable_extension(self, name):\n \"\"\"\n Disables an extension\n\n This prevents the extension to receive data from Slack\n\n :param str name: The extension's name\n :return: True if extension was disabled, False otherwise\n :rtype: Boolean\n \"\"\"\n if not self.is_registered(name):\n logging.info(\n '[ExtStore] Extension ' + name + ' not registered'\n )\n return False\n elif not self.is_enabled(name):\n logging.info(\n '[ExtStore] Extension ' + name + ' not enabled'\n )\n return False\n else:\n self.extensions[name.lower()].update({\n 'enabled': False,\n })\n logging.info(\n '[ExtStore] Extension ' + name + ' disabled'\n )\n return True\n\n def disable_extension_for(self, name, channel):\n \"\"\"\n Disables an extension for a given channel\n\n This prevents the extension to receive data from Slack on some channels\n\n :param str name: The extension's name\n :return: True if extension was disabled, False otherwise\n :rtype: Boolean\n \"\"\"\n if not self.is_registered(name):\n logging.info(\n '[ExtStore] Extension ' + name + ' not registered'\n )\n return False\n elif not self.is_enabled(name):\n logging.info(\n '[ExtStore] Extension ' + name + ' not enabled'\n )\n return False\n else:\n self.extensions[name.lower()]['enabled_for_channels'].remove(channel)\n logging.info(\n '[ExtStore] Extension ' + name + ' disabled for ' + channel\n )\n return True\n\n def disable_extension_for_im(self, name):\n \"\"\"\n Disables an extension for a given channel\n\n This prevents the extension to receive data from Slack for IMs\n\n :param str name: The extension's name\n :return: True if extension was disabled, False otherwise\n :rtype: Boolean\n \"\"\"\n if not self.is_registered(name):\n logging.info(\n '[ExtStore] Extension ' + name + ' not registered'\n )\n return False\n elif not self.is_enabled(name):\n logging.info(\n '[ExtStore] Extension ' + name + ' not enabled'\n )\n return False\n else:\n self.extensions[name.lower()]['enabled_for_im'] = False\n logging.info(\n '[ExtStore] Extension ' + name + ' disabled for IMs'\n )\n return True\n\n def load_all(self, slack_web_client, ext_settings):\n \"\"\"\n Loads all registered extensions\n\n :param object slack_web_client: The Modbot web client\n :param dict ext_settings: Extension settings as set in main program\n \"\"\"\n for extension in self.extensions:\n self.load_extension(extension, slack_web_client, ext_settings)\n\n def enable_all(self):\n \"\"\"\n Enables all loaded extensions\n\n This allows the extension to receive data from Slack\n\n :param str name: The extension's name\n :return: True if extension was enabled, False otherwise\n :rtype: Boolean\n \"\"\"\n for name in self.extensions:\n if self.is_loaded(name):\n self.enable_extension(name)\n\n def disable_all(self):\n \"\"\"\n Disables all loaded extensions\n\n This prevents all extensions to receive data from Slack\n\n :param str name: The extension's name\n :return: True if extension was enabled, False otherwise\n :rtype: Boolean\n \"\"\"\n for name in self.extensions:\n if self.is_enabled(name):\n self.disable_extension(name)\n\n def is_registered(self, name):\n \"\"\"\n Indicates whether an extension is registered or not\n\n :param str name: The extension's name\n :return: True if extension is registered, False otherwise\n :rtype: Boolean\n \"\"\"\n return (name.lower() in self.extensions)\n\n def is_loaded(self, name):\n \"\"\"\n Indicates whether an extension is loaded or not\n\n :param str name: The extension's name\n :return: True if extension is enabled, False otherwise\n :rtype: Boolean\n \"\"\"\n if self.is_registered(name) \\\n and self.extensions[name.lower()]['loaded']:\n return True\n return False\n\n def is_enabled(self, name):\n \"\"\"\n Indicates whether an extension is enabled or not\n\n :param str name: The extension's name\n :return: True if extension is enabled, False otherwise\n :rtype: Boolean\n \"\"\"\n if self.is_registered(name) \\\n and self.extensions[name.lower()]['enabled']:\n return True\n return False\n\n def is_enabled_for(self, name, event):\n \"\"\"\n Indicates whether an extension is enabled in a given context\n\n :param str name: The extension's name\n :param dict event: The received event\n :return: True if extension is enabled for this event, False otherwise\n :rtype: Boolean\n \"\"\"\n ext = self.extensions[name.lower()]\n if self.is_registered(name) and ext['enabled']:\n if event['channel_type'] == 'im':\n return ext['enabled_for_im']\n else:\n return event['channel'] in ext['enabled_for_channels']\n return False\n\n def is_enabled_in_im(self, name):\n \"\"\"\n Indicates whether an extension is enabled in IM (direct messages)\n\n :param str name: The extension's name\n :param dict event: The received event\n :return: True if extension is enabled in IM, False otherwise\n :rtype: Boolean\n \"\"\"\n ext = self.extensions[name.lower()]\n if self.is_registered(name) and ext['enabled']:\n return ext['enabled_for_im']\n return False\n\n def list_enabled_for(self, name):\n \"\"\"\n Indicates on which channels an extension is enabled\n\n :param str name: The extension's name\n :return: A set of channels where the extension is enabled\n :rtype: set\n \"\"\"\n ext = self.extensions[name.lower()]\n if self.is_registered(name) and ext['enabled']:\n return ext['enabled_for_channels']\n return False\n\n\nclass ExtensionManager(ModbotExtension):\n \"\"\"\n Manages extensions\n\n Attributes:\n name The name of the extension\n web_client The client used to send messages\n\n \"\"\"\n name = 'ExtensionManager'\n web_client = {}\n\n name = 'ExtensionManager'\n replies = {\n 'config_in_public': '\\n'.join((\n 'Hello!',\n 'Please configure me here, not in public (I\\'m a bit shy...)'\n )),\n 'extension_help': '\\n'.join((\n 'Hello!',\n 'Type *help* for help.',\n 'Type *help* _extension_ for help on a specific extension.',\n '',\n 'For the extension manager (admins only!):',\n '- Type *extension list* for the list of extensions',\n '- Type *extension load* _extension_ to load an extension',\n '- Type *extension enable* _extension_ to enable an extension',\n '- Type *extension disable* _extension_ to enable an extension',\n 'List of extensions: {extensions}',\n )),\n 'extension_help_no_extension_found': '\\n'.join((\n 'There is no extension with that name. Try *help* for the list',\n )),\n 'extension_list': '\\n'.join((\n 'Hello!',\n 'Here are all identified extensions:',\n '{extensions}',\n )),\n 'extension_enabled': '\\n'.join((\n 'Enabled globally',\n )),\n 'extension_enabled_for': '\\n'.join((\n 'enabled on channels',\n )),\n 'extension_enabled_in_im': '\\n'.join((\n 'enabled in direct messages',\n )),\n 'extension_disabled': '\\n'.join((\n 'Disabled globally',\n )),\n 'extension_load_missing_param': '\\n'.join((\n 'I didn\\'t understand your request, could you retry?',\n )),\n 'extension_load_success': '\\n'.join((\n 'Success: Extension {extension} loaded successfully',\n )),\n 'extension_load_failure': '\\n'.join((\n 'Fail: Extension {extension} could not be loaded',\n )),\n 'extension_enable_missing_param': '\\n'.join((\n 'I didn\\'t understand your request, could you retry?',\n )),\n 'extension_enable_success': '\\n'.join((\n 'Success: Extension {extension} enabled successfully',\n )),\n 'extension_enable_failure': '\\n'.join((\n 'Fail: Extension {extension} could not be enabled',\n )),\n 'extension_enable_for_missing_param': '\\n'.join((\n 'I didn\\'t understand your request, could you retry?',\n )),\n 'extension_enable_for_success': '\\n'.join((\n 'Success: Extension {extension} enabled successfully on channel {channel}',\n )),\n 'extension_enable_for_failure': '\\n'.join((\n 'Fail: Extension {extension} could not be enabled',\n )),\n 'extension_enable_for_im_missing_param': '\\n'.join((\n 'I didn\\'t understand your request, could you retry?',\n )),\n 'extension_enable_for_im_success': '\\n'.join((\n 'Success: Extension {extension} enabled successfully for IMs',\n )),\n 'extension_enable_for_im_failure': '\\n'.join((\n 'Fail: Extension {extension} could not be enabled',\n )),\n 'extension_disable_missing_param': '\\n'.join((\n 'I didn\\'t understand your request, could you retry?',\n )),\n 'extension_disable_success': '\\n'.join((\n 'Success: Extension {extension} disabled successfully',\n )),\n 'extension_disable_failure': '\\n'.join((\n 'Fail: Extension {extension} could not be disabled',\n )),\n 'extension_disable_for_missing_param': '\\n'.join((\n 'I didn\\'t understand your request, could you retry?',\n )),\n 'extension_disable_for_success': '\\n'.join((\n 'Success: Extension {extension} disabled successfully on channel {channel}',\n )),\n 'extension_disable_for_failure': '\\n'.join((\n 'Fail: Extension {extension} could not be disabled',\n )),\n 'extension_disable_for_im_missing_param': '\\n'.join((\n 'I didn\\'t understand your request, could you retry?',\n )),\n 'extension_disable_for_im_success': '\\n'.join((\n 'Success: Extension {extension} disabled successfully for IMs',\n )),\n 'extension_disable_for_im_failure': '\\n'.join((\n 'Fail: Extension {extension} could not be disabled',\n )),\n }\n\n def __init__(self, slack_web_client, settings):\n \"\"\"\n Doesn't do much, except calling the superclass' method\n\n :param ModbotWebclient slack_web_client: Slack web client\n :param dict settings: The settings to be applied by the module\n :return: None\n \"\"\"\n super().__init__(slack_web_client, settings)\n self.log_info('[ExtManager] Module started and ready to go')\n\n def on_message(self, event):\n \"\"\"\n Processes received events and sends a reply\n\n :param dict event: The event received\n :return: True if a message was sent, False otherwise\n :rtype: Boolean\n \"\"\"\n reply_message = {\n 'channel': event['channel'],\n 'user': event['user'],\n 'ready_to_send': False,\n 'type': 'ephemeral',\n }\n reply_data = False\n\n # Handle received messages\n if event['text'] in ['help', 'extension help', 'help extension']:\n reply_data = self.help(event)\n elif event['text'].startswith('help '):\n reply_data = self.help_other_extension(event)\n elif event['text'].startswith('extension'):\n if event['text'].startswith('extension list'):\n reply_data = self.extension_list(event)\n elif event['text'].startswith('extension load '):\n reply_data = self.extension_add(event)\n elif event['text'].startswith('extension enable '):\n reply_data = self.extension_enable(event)\n elif event['text'].startswith('extension enable_for '):\n reply_data = self.extension_enable_for(event)\n elif event['text'].startswith('extension enable_for_im '):\n reply_data = self.extension_enable_for_im(event)\n elif event['text'].startswith('extension disable '):\n reply_data = self.extension_disable(event)\n elif event['text'].startswith('extension disable_for '):\n reply_data = self.extension_disable_for(event)\n elif event['text'].startswith('extension disable_for_im '):\n reply_data = self.extension_disable_for_im(event)\n\n # We have a config message to send\n if reply_data and reply_data['ready_to_send']:\n reply_message.update(reply_data)\n if reply_message['ready_to_send']:\n self._send_reply_message(reply_message)\n return True\n\n # No reply found\n else:\n return False\n\n def help(self, event):\n \"\"\"\n Reacts to 'help' messages\n\n :param dict event: The event received\n :return: Message to be sent, False otherwise\n :rtype: False or dict\n \"\"\"\n global extension_store\n reply_data = {'type': 'regular'}\n\n # Redirect to a private chat so that we're not discussing in public\n if event['channel_type'] == 'channel':\n return self.switch_to_im(event)\n\n self.log_info('[ExtManager] Help viewed by %user', user=event['user'])\n\n extensions_list = ', '.join(extension_store.extensions)\n\n reply_text = self.replies['extension_help'] \\\n .replace('{extensions}', extensions_list)\n reply_data.update({'text': reply_text})\n\n reply_data.update({'ready_to_send': True})\n return reply_data\n\n def help_other_extension(self, event):\n \"\"\"\n Reacts to 'help extension' messages\n\n :param dict event: The event received\n :return: Message to be sent, False otherwise\n :rtype: False or dict\n \"\"\"\n global extension_store\n reply_data = {'type': 'regular'}\n\n # Redirect to a private chat so that we're not discussing in public\n if event['channel_type'] == 'channel':\n return self.switch_to_im(event)\n\n self.log_info('[ExtManager] Help viewed by %user', user=event['user'])\n\n _, extension, *_ = event['text'].split(' ')\n if extension in extension_store.extensions:\n reply_data = extension_store \\\n .extensions[extension]['instance'] \\\n .help(event)\n else:\n reply_text = self.replies['extension_help_no_extension_found']\n reply_data.update({'text': reply_text})\n\n reply_data.update({'ready_to_send': True})\n return reply_data\n\n def extension_list(self, event):\n \"\"\"\n Reacts to 'extension list' messages\n\n :param dict event: The event received\n :return: Message to be sent, False otherwise\n :rtype: False or dict\n \"\"\"\n global extension_store\n reply_data = {'type': 'regular'}\n\n # Exclude non-authorized people\n if not self.user_is_admin(event['user']) \\\n and not self.user_is_owner(event['user']):\n self.log_info(\n '[ExtManager] Config: \"list\" by non-admin user %user',\n user=event['user'])\n return False\n\n # Redirect to a private chat so that we're not discussing in public\n if event['channel_type'] == 'channel':\n return self.switch_to_im(event)\n\n # Just make the list and send it\n self.log_info('[ExtManager] List viewed by %user', user=event['user'])\n ext_list = []\n for extension in extension_store.extensions:\n ext_message = '*' + extension + '* : '\n if extension_store.is_enabled(extension):\n ext_message += self.replies['extension_enabled']\n if extension_store.is_enabled_in_im(extension):\n ext_message += ', ' \\\n + self.replies['extension_enabled_in_im']\n list_channels = extension_store.list_enabled_for(extension)\n if list_channels:\n ext_message += ', ' + self.replies['extension_enabled_for']\n ext_message += ' <#' + '> <#'.join(list_channels) + '>'\n else:\n ext_message += self.replies['extension_disabled']\n ext_list.append(ext_message)\n\n ext_list = '\\n'.join(ext_list)\n\n reply_text = self.replies['extension_list'] \\\n .replace('{extensions}', ext_list)\n reply_data.update({'text': reply_text})\n\n reply_data.update({'ready_to_send': True})\n return reply_data\n\n def extension_load(self, event):\n \"\"\"\n Reacts to 'extension load' messages\n\n :param dict event: The event received\n :return: Message to be sent, False otherwise\n :rtype: False or dict\n \"\"\"\n global extension_store\n reply_data = {'type': 'regular'}\n\n # Exclude non-authorized people\n if not self.user_is_admin(event['user']) \\\n and not self.user_is_owner(event['user']):\n self.log_info(\n '[ExtManager] Config: \"load\" by non-admin %user',\n user=event['user'])\n return False\n\n # Redirect to a private chat so that we're not discussing in public\n if event['channel_type'] == 'channel':\n return self.switch_to_im(event)\n\n # Missing argument\n if len(event['text'].split(' ')) < 3:\n self.log_info(\n '[ExtManager] Config: Load missing info by user %user',\n user=event['user']\n )\n reply_text = self.replies['extension_load_missing_param']\n reply_data.update({'text': reply_text})\n else:\n ext_name = event['text'].split(' ')[2].lower()\n load_status = extension_store.load_extension(\n ext_name,\n self.web_client,\n self.settings['extensions'][ext_name]\n )\n if load_status:\n self.log_info(\n '[ExtManager] Extension %s loaded by %user',\n ext_name,\n user=event['user']\n )\n reply_text = self.replies['extension_load_success'] \\\n .replace('{extension}', ext_name)\n reply_data.update({'text': reply_text})\n else:\n reply_text = self.replies['extension_load_failure'] \\\n .replace('{extension}', ext_name)\n reply_data.update({'text': reply_text})\n\n reply_data.update({'ready_to_send': True})\n return reply_data\n\n def extension_enable(self, event):\n \"\"\"\n Reacts to 'extension enable' messages\n\n :param dict event: The event received\n :return: Message to be sent, False otherwise\n :rtype: False or dict\n \"\"\"\n global extension_store\n reply_data = {'type': 'regular'}\n\n # Exclude non-authorized people\n if not self.user_is_admin(event['user']) \\\n and not self.user_is_owner(event['user']):\n self.log_info(\n '[ExtManager] Config: \"enable\" by non-admin user %user',\n user=event['user'])\n return False\n\n # Redirect to a private chat so that we're not discussing in public\n if event['channel_type'] == 'channel':\n return self.switch_to_im(event)\n\n # Missing argument\n if len(event['text'].split(' ')) < 3:\n self.log_info(\n '[ExtManager] Config: Enable missing info by user %user',\n user=event['user'])\n reply_text = self.replies['extension_enable_missing_param']\n reply_data.update({'text': reply_text})\n else:\n ext_name = event['text'].split(' ')[2].lower()\n enable_status = extension_store.enable_extension(ext_name)\n if enable_status:\n self.log_info(\n '[ExtManager] Extension %s enabled by %user',\n ext_name,\n user=event['user']\n )\n reply_text = self.replies['extension_enable_success'] \\\n .replace('{extension}', ext_name)\n reply_data.update({'text': reply_text})\n else:\n reply_text = self.replies['extension_enable_failure'] \\\n .replace('{extension}', ext_name)\n reply_data.update({'text': reply_text})\n\n reply_data.update({'ready_to_send': True})\n return reply_data\n\n def extension_enable_for(self, event):\n \"\"\"\n Reacts to 'extension enable_for' messages\n\n :param dict event: The event received\n :return: Message to be sent, False otherwise\n :rtype: False or dict\n \"\"\"\n global extension_store\n reply_data = {'type': 'regular'}\n\n # Exclude non-authorized people\n if not self.user_is_admin(event['user']) \\\n and not self.user_is_owner(event['user']):\n self.log_info(\n '[ExtManager] Config: \"enable_for\" by non-admin user %user',\n user=event['user'])\n return False\n\n # Redirect to a private chat so that we're not discussing in public\n if event['channel_type'] == 'channel':\n return self.switch_to_im(event)\n\n # Missing argument\n if len(event['text'].split(' ')) < 4:\n self.log_info(\n '[ExtManager] Config: Enable_for missing info by user %user',\n user=event['user'])\n reply_text = self.replies['extension_enable_for_missing_param']\n reply_data.update({'text': reply_text})\n else:\n _, _, ext_name, channel, *_ = event['text'].split(' ')\n ext_name = ext_name.lower()\n channel = self.get_channel_info(channel)\n\n enable_status = extension_store. \\\n enable_extension_for(ext_name, channel['id'])\n if enable_status and channel:\n self.log_info(\n '[ExtManager] Extension %s enabled by %user on '\n + channel['name'],\n ext_name,\n user=event['user'],\n )\n reply_text = self.replies['extension_enable_for_success'] \\\n .replace('{extension}', ext_name) \\\n .replace('{channel}', '<#' + channel['id'] + '>')\n reply_data.update({'text': reply_text})\n else:\n reply_text = self.replies['extension_enable_for_failure'] \\\n .replace('{extension}', ext_name)\n reply_data.update({'text': reply_text})\n\n reply_data.update({'ready_to_send': True})\n return reply_data\n\n def extension_enable_for_im(self, event):\n \"\"\"\n Reacts to 'extension enable_for_im' messages\n\n :param dict event: The event received\n :return: Message to be sent, False otherwise\n :rtype: False or dict\n \"\"\"\n global extension_store\n reply_data = {'type': 'regular'}\n\n # Exclude non-authorized people\n if not self.user_is_admin(event['user']) \\\n and not self.user_is_owner(event['user']):\n self.log_info(\n '[ExtManager] Config: \"enable_for_im\" by non-admin user %user',\n user=event['user'])\n return False\n\n # Redirect to a private chat so that we're not discussing in public\n if event['channel_type'] == 'channel':\n return self.switch_to_im(event)\n\n # Missing argument\n if len(event['text'].split(' ')) < 3:\n self.log_info(\n '[ExtManager] Config: Enable_for_im missing info by user %user',\n user=event['user'])\n reply_text = self.replies['extension_enable_for_im_missing_param']\n reply_data.update({'text': reply_text})\n else:\n _, _, ext_name, *_ = event['text'].split(' ')\n ext_name = ext_name.lower()\n\n enable_status = extension_store.enable_extension_for_im(ext_name)\n if enable_status:\n self.log_info(\n '[ExtManager] Extension %s enabled by %user for IMs',\n ext_name,\n user=event['user'],\n )\n reply_text = self.replies['extension_enable_for_im_success'] \\\n .replace('{extension}', ext_name)\n reply_data.update({'text': reply_text})\n else:\n reply_text = self.replies['extension_enable_for_im_failure'] \\\n .replace('{extension}', ext_name)\n reply_data.update({'text': reply_text})\n\n reply_data.update({'ready_to_send': True})\n return reply_data\n\n def extension_disable(self, event):\n \"\"\"\n Reacts to 'extension disable' messages\n\n :param dict event: The event received\n :return: Message to be sent, False otherwise\n :rtype: False or dict\n \"\"\"\n global extension_store\n reply_data = {'type': 'regular'}\n\n # Exclude non-authorized people\n if not self.user_is_admin(event['user']) \\\n and not self.user_is_owner(event['user']):\n self.log_info(\n '[ExtManager] Config: \"disable\" by non-admin %user',\n user=event['user'])\n return False\n\n # Redirect to a private chat so that we're not discussing in public\n if event['channel_type'] == 'channel':\n return self.switch_to_im(event)\n\n # Missing argument\n if len(event['text'].split(' ')) < 3:\n self.log_info(\n '[ExtManager] Config: Disable missing info by %user',\n user=event['user'])\n reply_text = self.replies['extension_disable_missing_param']\n reply_data.update({'text': reply_text})\n else:\n ext_name = event['text'].split(' ')[2].lower()\n disable_status = extension_store.disable_extension(ext_name)\n if disable_status:\n self.log_info(\n '[ExtManager] Extension %s disabled by %user',\n ext_name,\n user=event['user']\n )\n reply_text = self.replies['extension_disable_success'] \\\n .replace('{extension}', ext_name)\n reply_data.update({'text': reply_text})\n else:\n reply_text = self.replies['extension_disable_failure'] \\\n .replace('{extension}', ext_name)\n reply_data.update({'text': reply_text})\n\n reply_data.update({'ready_to_send': True})\n return reply_data\n\n def extension_disable_for(self, event):\n \"\"\"\n Reacts to 'extension disable_for' messages\n\n :param dict event: The event received\n :return: Message to be sent, False otherwise\n :rtype: False or dict\n \"\"\"\n global extension_store\n reply_data = {'type': 'regular'}\n\n # Exclude non-authorized people\n if not self.user_is_admin(event['user']) \\\n and not self.user_is_owner(event['user']):\n self.log_info(\n '[ExtManager] Config: \"disable_for\" by non-admin user %user',\n user=event['user'])\n return False\n\n # Redirect to a private chat so that we're not discussing in public\n if event['channel_type'] == 'channel':\n return self.switch_to_im(event)\n\n # Missing argument\n if len(event['text'].split(' ')) < 4:\n self.log_info(\n '[ExtManager] Config: disable_for missing info by user %user',\n user=event['user'])\n reply_text = self.replies['extension_disable_for_missing_param']\n reply_data.update({'text': reply_text})\n else:\n _, _, ext_name, channel, *_ = event['text'].split(' ')\n ext_name = ext_name.lower()\n channel = self.get_channel_info(channel)\n\n disable_status = extension_store. \\\n disable_extension_for(ext_name, channel['id'])\n if disable_status and channel:\n self.log_info(\n '[ExtManager] Extension %s disabled by %user on '\n + channel['name'],\n ext_name,\n user=event['user'],\n )\n reply_text = self.replies['extension_disable_for_success'] \\\n .replace('{extension}', ext_name) \\\n .replace('{channel}', '<#' + channel['id'] + '>')\n reply_data.update({'text': reply_text})\n else:\n reply_text = self.replies['extension_disable_for_failure'] \\\n .replace('{extension}', ext_name)\n reply_data.update({'text': reply_text})\n\n reply_data.update({'ready_to_send': True})\n return reply_data\n\n def extension_disable_for_im(self, event):\n \"\"\"\n Reacts to 'extension disable_for_im' messages\n\n :param dict event: The event received\n :return: Message to be sent, False otherwise\n :rtype: False or dict\n \"\"\"\n global extension_store\n reply_data = {'type': 'regular'}\n\n # Exclude non-authorized people\n if not self.user_is_admin(event['user']) \\\n and not self.user_is_owner(event['user']):\n self.log_info(\n '[ExtManager] Config: \"disable_for_im\" by non-admin user %user',\n user=event['user'])\n return False\n\n # Redirect to a private chat so that we're not discussing in public\n if event['channel_type'] == 'channel':\n return self.switch_to_im(event)\n\n # Missing argument\n if len(event['text'].split(' ')) < 3:\n self.log_info(\n '[ExtManager] Config: disable_for_im missing info by user %user',\n user=event['user'])\n reply_text = self.replies['extension_disable_for_im_missing_param']\n reply_data.update({'text': reply_text})\n else:\n _, _, ext_name, *_ = event['text'].split(' ')\n ext_name = ext_name.lower()\n\n disable_status = extension_store.disable_extension_for_im(ext_name)\n if disable_status:\n self.log_info(\n '[ExtManager] Extension %s disabled for IMs by %user',\n ext_name,\n user=event['user'],\n )\n reply_text = self.replies['extension_disable_for_im_success'] \\\n .replace('{extension}', ext_name)\n reply_data.update({'text': reply_text})\n else:\n reply_text = self.replies['extension_disable_for_im_failure'] \\\n .replace('{extension}', ext_name)\n reply_data.update({'text': reply_text})\n\n reply_data.update({'ready_to_send': True})\n return reply_data\n\n def switch_to_im(self, event):\n \"\"\"\n Replies through IM when receiving config requests in public\n\n :param dict event: The event received\n :return: False for unauthorized users,\n a reply_data message otherwise\n :rtype: False or dict\n \"\"\"\n reply_data = {'type': 'regular'}\n\n # Open an IM (private) chat to get the channel ID\n try:\n open_IM_conversation = self.web_client.conversations_open({\n 'users': [event['user']],\n 'return_im': True\n })\n except SlackApiError as e:\n self.log_info(\n '[ExtManager] FAIL: User data query for %user - Abort IM',\n user=event['user'])\n return False\n # If IM chat could be open, simply send a message\n else:\n reply_data.update({\n 'channel': open_IM_conversation['channel']['id'],\n 'text': self.replies['config_in_public'],\n 'ready_to_send': True,\n })\n return reply_data\n\n def _send_reply_message(self, reply_message):\n \"\"\"\n Sends the reply in the proper type (regular or ephemeral)\n\n :param str reply_message: The message to be sent\n :return: None\n \"\"\"\n del reply_message['ready_to_send']\n if reply_message['type'] == 'regular':\n del reply_message['type']\n self.web_client.chat_postMessage(reply_message)\n else:\n del reply_message['type']\n self.web_client.chat_postEphemeral(reply_message)\n\n\nextension_store = ExtensionStore()\n","repo_name":"Piratmac/slack-modbot","sub_path":"modbot_extension.py","file_name":"modbot_extension.py","file_ext":"py","file_size_in_byte":43494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"31228381559","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[20]:\n\n\nclass ListDivideException(Exception):\n pass\n\nclass ZeroDivide(Exception):\n pass\n\n \ndef listDivide(numbers, divide=2):\n try: \n if not isinstance(numbers, list):\n raise ListDivideException\n \n if divide == 0:\n raise ZeroDivide\n \n divisiblenumbers = []\n if len(numbers) == 0:\n print(0)\n else: \n for x in numbers:\n if x%divide == 0:\n divisiblenumbers.append(x)\n \n print(len(divisiblenumbers))\n \n except ListDivideException:\n print(\"Type Error: First parameter must be a list\")\n except ZeroDivide:\n print(\"Value Error: Divide value cannot be zero\")\n \n\ndef ListDivideTest(numbers, divide=2):\n try: \n if not isinstance(numbers, list):\n raise ListDivideException\n \n if divide == 0:\n raise ZeroDivide\n \n divisibles = []\n if len(numbers) == 0:\n return 0\n else: \n for x in numbers:\n if x%divide == 0:\n divisiblenumbers.append(x)\n \n except ListDivideException:\n print(\"Type Error: First parameter must be a list\")\n except ZeroDivide:\n print(\"Value Error: Divide value cannot be zero\")\n except Exception as ex:\n print(str(ex))\n \nlistDivide([1,2,3,4,5])\nlistDivide([2,4,6,8,10])\nlistDivide([30, 54, 63,98, 100], divide=10)\nlistDivide([])\nlistDivide([1,2,3,4,5], 1)\n\n\ntestListDivide([1,2,3,4,5])\ntestListDivide('dog')\ntestListDivide([30, 54, 63,98, 100], divide=0)\n\n","repo_name":"Shanice-W/IS211_Assignment1","sub_path":"assignment1_part1.py","file_name":"assignment1_part1.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"31712056956","text":"#!/usr/bin/python\n\"\"\"\nSampled from Lyle Scott scrolling curses\n\"\"\"\nfrom __future__ import print_function\nimport curses\nimport sys\nimport random\nimport time\nimport locale\n\n\nclass InteractiveSearch:\n DOWN = 1\n UP = -1\n SPACE_KEY = 32\n ESC_KEY = 27\n ENTER_KEY = 10\n\n PREFIX_SELECTED = '_X_'\n PREFIX_DESELECTED = '___'\n\n outputLines = []\n commands = []\n screen = None\n\n def __init__(self, commands):\n\n self.commands = commands\n # Parse out our input\n self.outputLines = [x.__str__() for x in commands]\n self.nOutputLines = len(self.outputLines)\n\n self.topLineNum = 0\n self.highlightLineNum = 0\n self.markedLineNums = []\n\n def run(self):\n # Locale set to support utf-8 characters.\n locale.setlocale(locale.LC_ALL, \"\")\n return curses.wrapper(self._run)\n\n def _run(self, screen):\n self.screen = screen\n curses.cbreak()\n curses.start_color()\n curses.use_default_colors()\n self.screen.border(0)\n while True:\n self.displayScreen()\n # get user command\n c = self.screen.getch()\n if c == curses.KEY_UP or c == ord('k'):\n self.updown(self.UP)\n elif c == curses.KEY_DOWN or c == ord('j'):\n self.updown(self.DOWN)\n elif c == self.ENTER_KEY:\n return self.selectLine()\n elif c == self.ESC_KEY or c == ord('q'):\n sys.exit()\n\n def markLine(self):\n linenum = self.topLineNum + self.highlightLineNum\n if linenum in self.markedLineNums:\n self.markedLineNums.remove(linenum)\n else:\n self.markedLineNums.append(linenum)\n\n def selectLine(self):\n linenum = self.topLineNum + self.highlightLineNum\n self.screen.erase()\n self.restoreScreen()\n return self.commands[linenum]\n\n def displayScreen(self):\n # clear screen\n self.screen.erase()\n\n # now paint the rows\n top = self.topLineNum\n bottom = self.topLineNum + curses.LINES\n for (index, line, ) in enumerate(self.outputLines[top:bottom]):\n line = '%s' % (line, )\n\n # highlight current line\n if index != self.highlightLineNum:\n self.screen.addstr(index, 0, line)\n else:\n self.screen.addstr(index, 0, line, curses.A_STANDOUT)\n self.screen.refresh()\n\n # move highlight up/down one line\n def updown(self, increment):\n nextLineNum = self.highlightLineNum + increment\n\n # paging\n if increment == self.UP and self.highlightLineNum == 0 and self.topLineNum != 0:\n self.topLineNum += self.UP\n return\n elif increment == self.DOWN and nextLineNum == curses.LINES and (\n self.topLineNum + curses.LINES) != self.nOutputLines:\n self.topLineNum += self.DOWN\n return\n\n # scroll highlight line\n if increment == self.UP and (self.topLineNum != 0 or\n self.highlightLineNum != 0):\n self.highlightLineNum = nextLineNum\n elif increment == self.DOWN and (\n self.topLineNum + self.highlightLineNum + 1\n ) != self.nOutputLines and self.highlightLineNum != curses.LINES:\n self.highlightLineNum = nextLineNum\n\n def restoreScreen(self):\n curses.nocbreak()\n curses.echo()\n curses.endwin()\n\n # catch any weird termination situations\n def __del__(self):\n self.restoreScreen()\n","repo_name":"rcaloras/bashhub-client","sub_path":"bashhub/interactive_search.py","file_name":"interactive_search.py","file_ext":"py","file_size_in_byte":3588,"program_lang":"python","lang":"en","doc_type":"code","stars":1190,"dataset":"github-code","pt":"77"}
+{"seq_id":"19409298963","text":"\"\"\"Define the command-line interface for the datasummarizer program.\"\"\"\n\nfrom pathlib import Path\n\nimport typer\nimport pytest\n\nfrom rich.console import Console\n\nfrom dataanalysis import commander\nfrom dataanalysis import summarize\nfrom dataanalysis import transform\n\ncli = typer.Typer()\n\nconsole = Console()\n\n\n@cli.command()\ndef fiasco():\n \"\"\"Run the test suite with function fiasco.\"\"\"\n print(\"Run the test suite with function fiasco.\")\n commander.cause_testing_fiasco()\n\n\n@cli.command()\ndef bedlam():\n \"\"\"Run the test suite with branch bedlam.\"\"\"\n print(\"Run the test suite with branch bedlam.\")\n commander.cause_branch_bedlam()\n\n\n@cli.command()\ndef analyze(\n data_file: Path = typer.Option(...),\n):\n \"\"\"Summarize the data values stored in a file.\"\"\"\n # display details about the file provided on the command line\n data_text = \"\"\n # --> the file was not specified so we cannot continue using program\n if data_file is None:\n console.print(\"No data file specified!\")\n raise typer.Abort()\n # --> the file was specified and it is valid so we should read and check it\n if data_file.is_file():\n data_text = data_file.read_text()\n data_line_count = len(data_text.splitlines())\n console.print(\"\")\n console.print(\n f\":package: The data file contains {data_line_count} data values in it!\"\n )\n console.print(\"\")\n console.print(\":rocket: Let's do some sophisticated data analysis!\")\n # transform the data from a list of textual values to a list of numerical values\n data_list = transform.transform_string_to_number_list(data_text)\n # compute the mean from the list of numerical values\n computed_mean = summarize.compute_mean(data_list)\n # display the computed mean in the terminal window\n console.print(\"\")\n console.print(\":abacus: Here are the results of the data analysis:\")\n console.print(\"\")\n console.print(f\" The computed mean is {computed_mean:.2f}!\")\n # compute the median from the list of numerical values\n computed_median = summarize.compute_median(data_list)\n # display the computed median in the terminal window\n console.print(f\" The computed median is {computed_median:.2f}!\")\n console.print(\"\")\n # compute the variance from the list of numerical values\n computed_variance = summarize.compute_variance(data_list)\n # display the computed variance in the terminal window\n console.print(f\" The computed variance is {computed_variance:.2f}!\")\n # compute the standard deviation from the list of numerical values\n computed_standard_deviation = summarize.compute_standard_deviation(data_list)\n # display the computed standard deviation in the terminal window\n console.print(\n f\" The computed standard deviation is {computed_standard_deviation:.2f}!\"\n )\n console.print(\"\")\n console.print(\n \":light_bulb: What does this tell you about the population of this city?\"\n )\n console.print(\"\")\n # --> the file was specified but it does not exist so we cannot continue using program\n elif not data_file.exists():\n console.print(\":bomb: The data file does not exist!\")\n console.print(\"Did you incorrectly specify the name of the file?\")\n","repo_name":"ProactiveProgrammers/data-analysis-solution-branch-bedlam","sub_path":"dataanalysis/dataanalysis/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"44088639404","text":"import numpy as np\nimport scipy.io\nimport os.path\n\n\nclass Svd_AUC_Grid:\n def __init__(self, grid_cells=np.empty(2), within_left_grid=0, between_left_grid=0, permuted_g_auc_dif=np.empty(2), permuted_g_auc_between=np.empty(2),n_permutation=1000, n_grid=41):\n\n self.grid_cells = grid_cells[:, :n_grid, :]\n self.within_left_grid = within_left_grid\n self.between_left_grid = between_left_grid\n self.within_left_grid_plot = np.empty(2)\n self.between_left_grid_plot = np.empty(2)\n self.permuted_g_auc_dif = permuted_g_auc_dif\n self.permuted_g_auc_between = permuted_g_auc_between\n self.num_permutation = n_permutation\n\n \"\"\"\n permuted_g_auc - permute grid cells auc (we permute the cells in the PCs)\n\n \"\"\"\n\n def svd_analysis(self, data):\n \"\"\"\n Performs Singular Value Decomposition (SVD) analysis on the given data.\n\n Parameters:\n data (numpy.ndarray): The input data to perform SVD on. This should be a 2D numpy array where\n each row represents a trial and each column represents a feature.\n\n Returns:\n tuple: A tuple (t_u, t_v) where t_u and t_v are the transposed left singular vectors and right singular vectors, respectively.\n\n This function performs SVD on the input data using the numpy's linalg.svd method with full_matrices set to True,\n which means it produces u and vh matrices with shapes that are compatible with original data shape.\n The left singular vectors (u) and the right singular vectors (vh) are then transposed and returned.\n \"\"\"\n u, s, vh = np.linalg.svd(data, full_matrices=True)\n t_u = np.transpose(u)\n t_v = np.transpose(vh)\n return t_u, t_v\n\n def calculate_cumulative_variances(self, data, t_u, t_v):\n \"\"\"\n Calculates the cumulative variances for the transformed input data.\n\n Parameters:\n data (numpy.ndarray): The input data for which the cumulative variances are to be calculated.\n t_u (numpy.ndarray): The transposed left singular vectors obtained from SVD.\n t_v (numpy.ndarray): The transposed right singular vectors obtained from SVD.\n\n Returns:\n tuple: A tuple (cum_var_x, cum_var_y) where cum_var_x and cum_var_y are the cumulative variances for\n the left and right singular vectors transformations, respectively.\n\n The function first performs a dot product between the left and right singular vectors and the input data,\n calculating the sum of squares along the axis 1 (rows). It then calculates the cumulative sum of the variance,\n normalized by the square root of the data's shape[0] (number of rows), and finally normalizes the cumulative\n variance by its last value, to provide a percentage-like format.\n \"\"\"\n x = np.linalg.multi_dot([t_u, data])\n var_x = np.sum(x ** 2, axis=1)\n cum_var_x = np.cumsum(var_x) / np.sqrt(data.shape[0])\n cum_var_x = cum_var_x / cum_var_x[-1]\n\n y = np.linalg.multi_dot([data, t_v])\n var_y = np.sum(y ** 2, axis=1)\n cum_var_y = np.cumsum(var_y) / np.sqrt(data.shape[0])\n cum_var_y = cum_var_y / cum_var_y[-1]\n\n return cum_var_x, cum_var_y\n\n def grid_cells_SVDs(self, area_name):\n\n \"\"\"\n\n Parameters:\n area_name (str): whether to calculate the svd analysis over grid/place cells/permuted data\n trials(np.array): if not empty it should be the permuted data\n\n Returns:\n tuple: A tuple (cum_var_left, cum_var_right), where cum_var_left and cum_var_right are lists of cumulative\n variances for left and right singular vectors for each trial.\n\n Performs Singular Value Decomposition (SVD) analysis on place grid cell data.\n It then performs the SVD analysis for the first trial, and for\n each subsequent trial, it calculates the cumulative variances using the left and right singular vectors\n obtained from the first trial's SVD. The cumulative variances for each trial are then returned.\n \"\"\"\n #\n # Note that below I just selected the first 41 cells to make grid and place cell area under the curve comparable (as this is the total number of grid cells but there are more place cells in the data).\n # This is not ideal, we should do some shuffling instead.\n #\n\n trials = self.grid_cells\n\n t_u, t_v = self.svd_analysis(trials[0]) # SVD of the first trial\n print(t_u.shape)\n if area_name == 'permuted':\n t_u = t_u[np.random.permutation(t_u.shape[0])]\n\n cum_var_left = []\n cum_var_right = []\n for i, t in enumerate(trials[1:]): # SVD trials 2,3,4,5\n cum_var_x, cum_var_y = self.calculate_cumulative_variances(t, t_u, t_v)\n cum_var_left.append(cum_var_x)\n cum_var_right.append(cum_var_y)\n\n between_left = np.mean(cum_var_left[:3], 0) # 2,3 and 4 is a different arena hence this is between\n within_left = cum_var_left[-1] # Last trial is in the same arean as the first hence here this is within\n\n between_right = np.mean(cum_var_right[:3], 0) # 2,3 and 4 is a different arena hence this is between\n within_right = cum_var_right[-1] # Last trial is in the same arean as the first hence here this is within\n\n return between_left, within_left, between_right, within_right\n\n def cal_auc_real(self):\n \"\"\"\n This function calculate grid and place cells auc over the real data\n \"\"\"\n between_left_grid, within_left_grid, between_right_grid, within_right_grid = self.grid_cells_SVDs('grid')\n\n print(\n f\"within_left_grid sum: {np.sum(within_left_grid / within_left_grid.shape[0])} and shape: {within_left_grid.shape} \\\n between_left_grid sum: {np.sum(between_left_grid / within_left_grid.shape[0])} and shape: {between_left_grid.shape}\")\n self.within_left_grid_plot = within_left_grid\n self.between_left_grid_plot = between_left_grid\n self.within_left_grid = np.sum(within_left_grid) / within_left_grid.shape[0]\n self.between_left_grid = np.sum(between_left_grid) / within_left_grid.shape[0]\n auc_dif_grid = np.sum(within_left_grid - between_left_grid) / within_left_grid.shape[0]\n print(auc_dif_grid)\n return auc_dif_grid\n\n def cal_auc_permuted(self):\n \"\"\"\n This function calculate the auc of the permuted data\n\n Return: The auc difference\n \"\"\"\n between_left, within_left, between_right, within_right = self.grid_cells_SVDs(\n 'permuted')\n auc_dif = np.sum(within_left - between_left) / within_left.shape[0]\n between_left_auc = np.sum(between_left) / within_left.shape[0]\n return auc_dif, between_left_auc\n\n\n def cal_auc_permuted_vec(self):\n \"\"\"\n This function calculate the dif-auc over the permuted/sampled data\n If name_permutation = 'grid_place' the permutation is over grid and place cells\n if name_permutation = 'place' the place cells are sampled and the difference of place cells\n auc is calculated\n \"\"\"\n auc_dif_arr = np.array([self.cal_auc_permuted() for x in np.arange(self.num_permutation)])\n print(f\"auc_dif_arr shape: {auc_dif_arr.shape}\")\n self.permuted_g_auc_dif = auc_dif_arr[:, 0]\n self.permuted_g_auc_between = auc_dif_arr[:, 1]\n\n\n def create_permuted_auc_dist(self, name_permutation='between', n_bin=100):\n \"\"\"\n This function calculates the permuted dif-auc distribution.\n Parameters: name_permutation (str)\n If name_permutation = 'grid_place' the permutation is over grid and place cells\n if name_permutation = 'place' the place cells are sampled and the difference of place cells\n auc is calculated\n\n Return: the cdf\n \"\"\"\n if name_permutation == 'between':\n hist, bin_edges = np.histogram(self.permuted_g_auc_between, bins=n_bin)\n elif name_permutation == 'dif':\n hist, bin_edges = np.histogram(self.permuted_g_auc_dif, bins=n_bin)\n elif name_permutation == 'between_dif':\n hist, bin_edges = np.histogram(self.within_left_grid - self.permuted_g_auc_between, bins=n_bin)\n\n x = 0.5 * (bin_edges[1:] + bin_edges[:-1])\n prob = hist / np.sum(hist)\n return x, np.cumsum(prob)\n\n\n\n","repo_name":"alonbaram2/shirley_fmriPaper","sub_path":"grid_svd_auc_calc.py","file_name":"grid_svd_auc_calc.py","file_ext":"py","file_size_in_byte":8470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"72173937208","text":"from django.shortcuts import render, redirect\nfrom .models import Url, BoundingBox\nimport cv2\nfrom imutils import url_to_image \n\nface_cascade = cv2.CascadeClassifier('/haarcascade_frontalface_default.xml')\n\n\ndef index(request):\n if request.method == 'POST':\n\n url = Url.objects.create(image_url=request.POST.get('image_url'))\n url.save()\n\n img = url_to_image(request.POST.get('image_url'))\n ih, iw, _ = img.shape\n\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(gray, 1.3, 5)\n\n for (x, y, w, h) in faces:\n top = round(y * 100 / ih, 2)\n right = round((iw - x - w) * 100 / iw, 2)\n left = round(x * 100 / iw, 2)\n bottom = round((ih - y - h) * 100 / ih, 2)\n bounding_box = BoundingBox.objects.create(top=top,\n right=right,\n left=left,\n bottom=bottom,\n image=url)\n bounding_box.save()\n \n return redirect('/face')\n\n image_urls = Url.objects.all()\n\n context = {'image_urls': image_urls}\n return render(request, 'face/index.html', context=context)\n\n\ndef delete(request, url_id):\n item = Url.objects.get(pk=url_id)\n item.delete()\n return redirect('/face')","repo_name":"IlyaTorch/Face-Recognition","sub_path":"web/app/face/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"44540083225","text":"#%%\r\n\r\nimport numpy as np\r\n\r\ndef f(x):\r\n return np.exp(-x**2)\r\n\r\ndef integral_riemann(a=0, b=1, n=1000000):\r\n i = 0\r\n fx = 0\r\n while i <= (n - 1):\r\n delta_x = (b - a) / n\r\n xi = a + (i * delta_x)\r\n fa = f(xi) * delta_x\r\n fx += fa\r\n i += 1\r\n return fx\r\nprint(\"Punto 1:\")\r\nprint(integral_riemann())\r\n\r\ndef test1():\r\n try:\r\n assert np.abs(integral_riemann()-0.746824132812427)<1e-6\r\n print(\"Resultado Correcto\")\r\n except:\r\n print(\"Resultado Incorrecto\")\r\ntest1()\r\n\r\ndef integral_trapecio(a=0, b=1, n=1000000):\r\n i = 0\r\n fx = 0\r\n delta_x = (b - a) / n\r\n while i<= (n - 1):\r\n xi = a + (i * delta_x)\r\n fa = f(xi)\r\n i += 1\r\n fx += fa\r\n sum = (delta_x) * ((f(0) / 2) + (f(n) / 2) + fx)\r\n return sum\r\nprint(\"Punto 2:\")\r\nprint(integral_trapecio())\r\n\r\ndef test2():\r\n try:\r\n assert np.abs(integral_trapecio()-0.746824132812427)<1e-6\r\n print(\"Resultado Correcto\")\r\n except:\r\n print(\"Resultado Incorrecto\")\r\ntest2()\r\n# %%\r\n","repo_name":"ValeriaTorresG/MetodosComputacionales1","sub_path":"Complementaria/quiz_202110363.py","file_name":"quiz_202110363.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"74213053688","text":"'''\r\nUnittests for ChristmasTree.py\r\nDecember 2020 Jakub Kazimierski\r\n'''\r\n\r\nimport unittest\r\nimport ChristmasTree\r\n\r\nclass test_ChristmasTree(unittest.TestCase): \r\n '''\r\n Class with unittests for ChristmasTree.py\r\n '''\r\n\r\n # region Unittests\r\n def test_ExpectedOutput(self):\r\n '''\r\n Checks if returned output is as expected.\r\n '''\r\n output = ChristmasTree.ChristmasTree(10)\r\n self.assertEqual(output, 0)\r\n\r\n # endregion\r\n\r\nif __name__ == \"__main__\":\r\n '''\r\n Main method for test cases.\r\n '''\r\n unittest.main()","repo_name":"JakubKazimierski/PythonPortfolio","sub_path":"Coderbyte_algorithms/Easy/ChristmasTree/test_ChristmasTree.py","file_name":"test_ChristmasTree.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"77"}
+{"seq_id":"9919672875","text":"import open3d as o3d\n\ncap_num = int(input(\"Captured numbers : \"))\n\n# 포인트클라우드 시각화\npcd_list = []\nfor i in range(cap_num):\n pcd = o3d.io.read_point_cloud(\"fin_pc/\" + str(i+1) + \".pcd\")\n pcd_list.append(pcd)\n\nprint(\"[ Point-cloud Created ]\")\no3d.visualization.draw_geometries(pcd_list)","repo_name":"Jocodin/RGBD-multiview_3D-registration-ICP-","sub_path":"pc_play.py","file_name":"pc_play.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"10250604745","text":"import setuptools\n\nwith open('README.md', 'r') as fh:\n long_description = fh.read()\n\n\nsetuptools.setup(\n name='xlsxmetadata',\n version='0.0.5',\n author='spmassot',\n author_email='spmassot@gmail.com',\n description='Really lightweight lib for peeking into xlsx column/row size before you try to open the file with something else',\n long_description=long_description,\n url='https://github.com/spmassot/xlsxmetadata',\n packages=['xlsxmetadata'],\n zip_safe=False\n)\n","repo_name":"spmassot/xlsxmetadata","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"77"}
+{"seq_id":"16022629265","text":"def verify_word(user_word):\n while len(user_word) < 3:\n print('A palavra deve conter três ou mais caracteres')\n user_word = input('Digite novamente: ').upper()\n return user_word\n\ndef verify_index(words, prhase):\n index_found = []\n\n for word in words:\n if word in prhase:\n index_initial = prhase.index(word)\n index_end = index_initial + len(word) - 1\n index_found.append((word, index_initial, index_end))\n return index_found\n \n# palavra 01 \nuser_word01 = input('Digite a primeira palavra: ').upper()\nuser_word01 = verify_word(user_word01)\n\n# palavra 02\nuser_word02 = input('Digite a segunda palavra: ').upper()\nuser_word02 = verify_word(user_word02)\n\n# palavra 03\nuser_word03 = input('Digite a terceira palavra: ').upper()\nuser_word03 = verify_word(user_word03)\n\nlist_word = [user_word01, user_word02, user_word03]\n\n# input de frase e validação\nuser_phrase = input('Digite um frase: ').upper()\nif len(user_phrase) < 20:\n print('A frase deve conter 20 ou mais caracteres.')\n user_phrase = input('Digite a frase novamente: ')\n\nprint(user_phrase)\n\nresults = verify_index(list_word, user_phrase)\nprint()\n\nif results:\n for i, r in enumerate(results, start=1):\n print(f'A palavra { i } foi encontrada no intervalo de indices: { r }') \nelse:\n print('As palavras não estão na frase')","repo_name":"kaynann/PYTHON","sub_path":"aula12.11/atv01.py","file_name":"atv01.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"20868029364","text":"import math\n\nimport torch\nimport torch.nn as nn\n\nfrom modelzoo.common.pytorch.layers.RelativePositionEmbeddingLayer import (\n RelativePositionEmbeddingLayer,\n)\nfrom modelzoo.common.pytorch.model_utils.create_initializer import (\n create_initializer,\n)\n\n\nclass AlibiPositionEmbeddingLayer(nn.Module):\n \"\"\"Alibi Position Embedding Layer, Symmetric case with bidirectional supported\n\n alibi bias as in paper: https://arxiv.org/abs/2108.12409\n\n Args:\n num_heads (int): number of attention heads.\n slopes (Tensor): slope values to use for alibi heads. Shape: [num_heads, 1]. Default to `None`.\n alibi_trainable_slopes (bool): whether the alibi slopes are trainable parameters.\n slopes_initializer (str): initializer for alibi slopes if it's trainable. Defaults to ``xavier_uniform``.\n alibi_implementation (str): variant name for alibi implementation. Currently\n accepts ``embedding`` and ``expand``. Defaults to ``expand``.\n Returns:\n position_bias (Tensor): Relative position bias, to be used in attention masking\n \"\"\"\n\n def __init__(\n self,\n num_heads,\n slopes=None,\n alibi_trainable_slopes=False,\n slopes_initializer=\"xavier_uniform\",\n alibi_implementation=\"expand\",\n ):\n super(AlibiPositionEmbeddingLayer, self).__init__()\n\n _SUPPORTED_ALIBI_IMPLEMENTATIONS = [\"embedding\", \"expand\"]\n assert (\n alibi_implementation in _SUPPORTED_ALIBI_IMPLEMENTATIONS\n ), f\"Alibi implementation {alibi_implementation} is not supported.\"\n assert slopes is None, \"Customized slope is not supported yet.\"\n\n self.num_heads = num_heads\n self.alibi_trainable_slopes = alibi_trainable_slopes\n self.use_embedding_implementation = alibi_implementation == \"embedding\"\n if not slopes:\n if self.alibi_trainable_slopes:\n slopes = torch.zeros([num_heads, 1])\n self.slopes_initializer = slopes_initializer\n else:\n slopes = torch.tensor(\n AlibiPositionEmbeddingLayer._get_alibi_slopes(num_heads)\n ).unsqueeze(-1)\n else:\n if self.alibi_trainable_slopes:\n self.slopes_initializer = slopes_initializer\n\n self.slopes = nn.parameter.Parameter(\n slopes, requires_grad=self.alibi_trainable_slopes\n )\n\n self.__reset_parameters()\n\n def reset_parameters(self):\n self.__reset_parameters()\n\n def __reset_parameters(self):\n if self.alibi_trainable_slopes:\n create_initializer(self.slopes_initializer)(self.slopes.data)\n\n def forward(\n self, seq_length, key_length, past_kv=None,\n ):\n \"\"\"Return the position bias based on the alibi slopes.\n\n Args:\n seq_length (int): the length of query tokens.\n key_length (int): the length of key tokens.\n\n Returns:\n Position bias tensor with shape [num_heads, query_length, key_length]\n \"\"\"\n position_bias = self._compute_alibi_bias(seq_length, key_length)\n # if key and values are already calculated we want only\n # the last query position bias\n if past_kv is not None:\n position_bias = position_bias[:, :, -seq_length, :]\n\n return position_bias\n\n @staticmethod\n def _get_alibi_slopes(n):\n def get_slopes_power_of_2(n):\n start = 2 ** (-(2 ** -(math.log2(n) - 3)))\n ratio = start\n return [start * ratio ** i for i in range(n)]\n\n if math.log2(n).is_integer():\n return get_slopes_power_of_2(\n n\n ) # In the paper, we only train models that have 2^a heads for some a. This function has\n else: # some good properties that only occur when the input is a power of 2. To maintain that even\n closest_power_of_2 = 2 ** math.floor(\n math.log2(n)\n ) # when the number of heads is not a power of 2, we use this workaround.\n return (\n get_slopes_power_of_2(closest_power_of_2)\n + AlibiPositionEmbeddingLayer._get_alibi_slopes(\n 2 * closest_power_of_2\n )[0::2][: n - closest_power_of_2]\n )\n\n def _alibi_implementation_embedding(self, seq_length, key_length, slopes):\n # 1D tensor range(key_length): [0, 1, ... key_length - 1]\n range_k = torch.arange(\n key_length, dtype=torch.int32, device=slopes.device\n )\n\n # Compute bias for each head: slopes[head_index] * [0, 1, ... key_length - 1]\n # Shape: (key_length, num_heads)\n bias = slopes.permute([1, 0]) * range_k.unsqueeze(-1) * -1.0\n\n # Construct the broadcasting with compute_raw_relative_positions from RelativePositionEmbedding\n # Shape: (seq_length, key_length)\n relative_position = RelativePositionEmbeddingLayer.compute_raw_relative_positions(\n seq_length, key_length, device=slopes.device\n )\n # casting to int32 to bypass the wgt kernel gather limitation\n relative_position = torch.abs(relative_position).to(torch.int32)\n\n # Use embedding as a 2D to 3D broadcast.\n # Shape: (seq_length, key_length, num_heads)\n bias = nn.functional.embedding(relative_position, bias)\n\n # Transpose to the expected output order.\n # Shape: (num_heads, seq_length, key_length)\n bias = bias.permute([2, 0, 1])\n return bias\n\n def _alibi_implementation_expand(self, seq_length, key_length, slopes):\n relative_position = RelativePositionEmbeddingLayer.compute_raw_relative_positions(\n seq_length, key_length, device=slopes.device\n )\n relative_position = (\n torch.abs(relative_position)\n .unsqueeze(0)\n .expand(self.num_heads, -1, -1)\n )\n alibi = (slopes * -1.0).unsqueeze(1) * relative_position\n return alibi\n\n def _compute_alibi_bias(self, seq_length, key_length, slopes=None):\n if slopes is None:\n slopes = self.slopes\n\n if self.use_embedding_implementation:\n return self._alibi_implementation_embedding(\n seq_length, key_length, slopes\n )\n else:\n return self._alibi_implementation_expand(\n seq_length, key_length, slopes\n )\n","repo_name":"Cerebras/modelzoo","sub_path":"modelzoo/common/pytorch/layers/AlibiPositionEmbeddingLayer.py","file_name":"AlibiPositionEmbeddingLayer.py","file_ext":"py","file_size_in_byte":6428,"program_lang":"python","lang":"en","doc_type":"code","stars":747,"dataset":"github-code","pt":"77"}
+{"seq_id":"13750012409","text":"from behave import then\nfrom BDDCommon.CommonDAO.ordersDAO import OrdersDAO\n\n\n@then(\"I verify order is created in database\")\ndef verify_order_is_created_in_database(context):\n\n db_order = OrdersDAO().get_order_by_id(context.order_id)\n\n assert db_order, f\"Order id {context.order_id} not found in database\"\n assert db_order[0]['post_type'] == 'shop_order', f\"For order id '{context.order_id}', the 'post_type' field \" \\\n f\"value is not as expected. Expected 'shop_order' actual '{db_order[0]['post_type']}'\"\n","repo_name":"Guga-1994/ProjetoAutomacaoPython","sub_path":"BDDPractice/BDDCommon/CommonSteps/order_api_steps.py","file_name":"order_api_steps.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"3533731346","text":"from datetime import date, datetime, timedelta\n\nfrom markkk.logger import logger\nfrom pydantic import BaseModel, validator\n\nfrom ..functional import uid_gen\n\n\nclass Contract(BaseModel):\n uid: str\n created_at: datetime = None\n room_uid: str\n bed_id: str = \"\"\n student_id: str\n start_date: date\n end_date: date\n unit_price_per_day: float\n payment_received: bool = False\n # derived\n total_days: int = 0\n\n @validator(\"uid\", pre=True, always=True)\n def default_uid(cls, v):\n return v or uid_gen(\"C\")\n\n @validator(\"created_at\", pre=True, always=True)\n def default_created_at(cls, v):\n return v or datetime.now()\n\n @validator(\"total_days\", pre=True, always=True)\n def calculate_total_days(cls, v, *, values, **kwargs):\n start_date: date = values.get(\"start_date\")\n end_date: date = values.get(\"end_date\")\n delta: timedelta = end_date - start_date\n return int(delta.days)\n\n\nif __name__ == \"__main__\":\n start_date: date = date(2021, 1, 1)\n end_date: date = date.today()\n time_delta: timedelta = end_date - start_date\n print(time_delta.days)\n","repo_name":"MarkHershey/SUTDHousingPortal","sub_path":"src/api/models/contract.py","file_name":"contract.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"43740561360","text":"#!/usr/bin/env python3\n\nimport argparse\nimport subprocess\nimport os\n\nfrom utils import git, npm, docker\nfrom config import GIT_REMOTE_API, GIT_REMOTE_APP, GIT_REMOTE_CLIENT\n\n\nGIT_LOCAL_DIR_API = \"aq-widget-api\"\nGIT_LOCAL_DIR_APP = \"aq-widget-app\"\nGIT_LOCAL_DIR_CLIENT = \"aq-client-eea\"\n\nDOCKER_IMAGE_NAME = \"aq-widget\"\nDOCKER_FILE = \"bundle.Dockerfile\"\nDOCKER_BUILD_ONLY = False\n\nparser = argparse.ArgumentParser(\n description='Fetch source for aq-widget-api and aq-widget-app and bundle them to a Docker file.')\nparser.add_argument('--apiVersion', dest='apiVersion', type=str,\n help='the version (tag on master branch) of aq-widget-api')\nparser.add_argument('--appVersion', dest='appVersion', type=str,\n help='the version (tag on master branch) of aq-widget-app')\nparser.add_argument('--clientVersion', dest='clientVersion', type=str,\n help='the version (tag on master branch) of aq-client-eea')\nparser.add_argument('--apiBranch', dest='apiBranch', type=str, default=\"master\",\n help='the branch of aq-widget-api')\nparser.add_argument('--appBranch', dest='appBranch', type=str, default=\"master\",\n help='the branch of aq-widget-app')\nparser.add_argument('--clientBranch', dest='clientBranch', type=str, default=\"master\",\n help='the branch of aq-client-eea')\nparser.add_argument('--dockerImageName', dest='dockerImageName', type=str, default=DOCKER_IMAGE_NAME,\n help='the name of the resulting docker image')\nparser.add_argument('--dockerBuildOnly',\n dest='dockerBuildOnly',\n default=DOCKER_BUILD_ONLY,\n const=True,\n action=\"store_const\",\n help='only execute the docker build command and omit git/npm operations')\n\n\nargs = parser.parse_args()\napiVersion = args.apiVersion\nappVersion = args.appVersion\nclientVersion = args.clientVersion\napiBranch = args.apiBranch\nappBranch = args.appBranch\nclientBranch = args.clientBranch\nDOCKER_BUILD_ONLY = args.dockerBuildOnly\nDOCKER_IMAGE_NAME = args.dockerImageName\n\n\nprint(\"Running bundler...\")\nif DOCKER_BUILD_ONLY:\n print(\"Docker build only!\")\nelse:\n print(\"API version: \" + str(apiVersion))\n print(\"API branch: \" + str(apiBranch))\n print(\"App version: \" + str(appVersion))\n print(\"App branch: \" + str(appBranch))\n print(\"EEA client version: \" + str(clientVersion))\n print(\"EEA client branch: \" + str(clientBranch))\n\n\nif not DOCKER_BUILD_ONLY:\n git.load_source(GIT_REMOTE_API, GIT_LOCAL_DIR_API,\n branch=apiBranch, tag=apiVersion)\n git.load_source(GIT_REMOTE_APP, GIT_LOCAL_DIR_APP,\n branch=appBranch, tag=appVersion)\n git.load_source(GIT_REMOTE_CLIENT, GIT_LOCAL_DIR_CLIENT,\n branch=clientBranch, tag=clientVersion)\n\n npm.install(GIT_LOCAL_DIR_CLIENT)\n npm.build(GIT_LOCAL_DIR_CLIENT)\n\n npm.install(GIT_LOCAL_DIR_API)\n npm.build(GIT_LOCAL_DIR_API)\n\n npm.install(GIT_LOCAL_DIR_APP)\n npm.build(GIT_LOCAL_DIR_APP)\n\ndocker.build(DOCKER_IMAGE_NAME, DOCKER_FILE)\n","repo_name":"breeze-technologies/aq-widget-devops","sub_path":"build_bundle.py","file_name":"build_bundle.py","file_ext":"py","file_size_in_byte":3136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"31195052458","text":"# 1개월 달력 출력\n\ndates = int(input('최대 일수 입력 >> '))\nday = int(input('첫 날 1일의 시작 요일 >> (0일, 1월, 2화 , ... , 6토)'))\nday %= 7\n\n# 요일 출력\nfor lcv in '일월화수목금토':\n print('%s' % lcv, end = ' ')\nelse:\n print()\n\n\ncnt = 0\n# 빈 공간 출력\nif day != 0:\n print(' ' * day)\n\n# 1일부터 말일까지 출력\nfor i in range(1, dates+1):\n print('%2d' % i, end = ' ')\n cnt += 1\n if cnt % 7 == 0:\n print()\nelse:\n print()\n\n\n\n","repo_name":"sejyom/python","sub_path":"04-pl03-printOneMonth.py","file_name":"04-pl03-printOneMonth.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"20378285269","text":"#!/usr/bin/env python\n\nfrom sys import argv\nfrom yoloannotator.network import NetworkManagerBuilder\nfrom yoloannotator.converters import YoloToOpenCVBBoxConfidenceConverter\nfrom yoloannotator.supervisely import Project\n\n\ndef main():\n classnames = get_classes()\n network = NetworkManagerBuilder.init().with_network_type(\n 'darknet').with_bbox_converter(\n YoloToOpenCVBBoxConfidenceConverter(0.5, 0.3)).build()\n\n '''\n If you just want to display the bounding boxes in opencv\n Uncomment following commeted lines\n It's just taking one image from the resources dir\n Good way to make sure besic stuff are working before proceeding to\n generating the project\n '''\n # image = Image('resources/image.png')\n # boxes = network.get_image_bboxes(image)\n # image_data = ImageData(image, classnames, boxes)\n\n # print(image_data.get_image_json())\n\n # for box in boxes:\n # cv2.rectangle(image.get_image(), box.min_point,\n # box.max_point, (255, 0, 255), 2)\n\n # cv2.imshow('image', image.get_image())\n # cv2.waitKey(0)\n\n\n project = Project(network, classnames, './resources/training', './resources')\n project.generate()\n\n\ndef get_classes():\n with open('resources/obj.names', 'rt') as file:\n return file.read().splitlines()\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"s1n7ax/partially-annotate","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"4564461222","text":"#! /usr/local/bin/python2.7\n\n\"\"\"Filter and subset a NetCDF or GDS file\"\"\"\n\nimport QCpipeline\nimport sys\nimport os\nimport subprocess\nfrom optparse import OptionParser\n\nusage = \"\"\"%prog [options] config\n\nCreate subset netCDF or GDS file with chromosome anomalies filtered\nand scans excluded.\n\nRequired config parameters:\nannot_scan_file scan annotation file\nannot_snp_file snp annotation file\nin_file input genotype netCDF/GDS file\nout_file output genotype netCDF/GDS file\n\nOptional config parameters [default]:\nchrom_anom_file [NA] data frame of chromosome anomalies, with columns scanID, chromosome, left.base, right.base, whole.chrom, filter\nfilterYinF [TRUE] filter Y chromosome for females?\nscan_include_file [NA] vector of scanID to include (NA=all)\"\"\"\nparser = OptionParser(usage=usage)\nparser.add_option(\"-e\", \"--email\", dest=\"email\", default=None,\n help=\"email address for job reporting\")\nparser.add_option(\"-q\", \"--queue\", dest=\"qname\", default=\"gcc.q\", \n help=\"cluster queue name [default %default]\")\nparser.add_option(\"-o\", \"--options\", dest=\"qsubOptions\", default=\"\",\n help=\"additional options to pass to qsub, excluding -hold_jid, -N, -m e -M, -N, and -q\")\n(options, args) = parser.parse_args()\n\nif len(args) != 1:\n parser.error(\"incorrect number of arguments\")\n\nconfig = args[0]\nemail = options.email\nqname = options.qname\nqsubOptions = options.qsubOptions\n\npipeline = os.path.dirname(os.path.abspath(sys.argv[0]))\n\ndriver = os.path.join(pipeline, \"runRscript.sh\")\n\njobid = dict()\njob = \"subset\"\nrscript = os.path.join(pipeline, \"R\", job + \".R\")\njobid[job] = QCpipeline.submitJob(job, driver, [rscript, config], queue=qname, email=email, qsubOptions=qsubOptions)\n","repo_name":"UW-GAC/QCpipeline","sub_path":"geno_filt_subset.py","file_name":"geno_filt_subset.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"40451533331","text":"#!/usr/bin/env python3\n\nfrom buildaur import *\n\ndef branch(pkgs):\n alldeps=[]\n if len(pkgs) != 0:\n alldeps.append(deps(pkgs, do_install=False, quiet=True))\n if len(alldeps) != 0:\n alldeps+=branch(alldeps[0])\n return alldeps\n\ndef main(names):\n rescount, cutted=info(resolve(names))\n for i in range(rescount):\n pkg=Package(cutted, i)\n # print(names[i], end=\"\")\n ret=[arr for arr in branch([pkg]) if len(arr) != 0]\n ret.reverse()\n print(ret)\n for arr in ret:\n for pkg in arr:\n print(pkg.name)\n\nif __name__ == \"__main__\":\n main([\"gtkdialog\"])\n","repo_name":"lxgr-linux/buildaur","sub_path":"additions/deptree.py","file_name":"deptree.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"77"}
+{"seq_id":"25309055343","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ## Construct a dataframe with features\n# \n# **User ID**\n# \n# **Lexical**:\n# - sentence length (avg, std)\n# - word length (avg, std)\n# - Capitalize\n# - TF-IDF\n# \n# **Syntactic**\n# - number of exclamation mark\n# - number of question mark\n# \n# **User Behavior**\n# - cross-post (#URL# tag)\n# - retweet others (RT tag)\n# - mentioning others (#USER# tag)\n# - Amount of Hashtag\n\n# In[ ]:\n\n\n\n\n\n# In[66]:\n\n\nimport re\nfrom collections import Counter\nfrom xml.etree import ElementTree as ET\nimport os\nimport glob\nimport numpy as np\nimport pandas as pd\nfrom collections import OrderedDict\nimport matplotlib.pyplot as plt\n#import lightgbm as lgb\n\n\n# text = ['this', 'is', 'a', 'sentence', '.']\n# nonPunct = re.compile('.*[A-Za-z0-9].*') # must contain a letter or digit\n# filtered = [w for w in a if nonPunct.match(w)]\n\ndef clean(sentence):\n input_str = sentence\n output_str = re.sub('[^A-Za-z0-9]+', ' ', input_str) # remove punctiation\n output_str = re.sub('URL', ' ', output_str) # remove URL tag\n output_str = re.sub('RT', ' ', output_str) # remove RT tag\n output_str = re.sub('USER', ' ', output_str) # remove USER tag\n output_str = re.sub('HASHTAG', ' ', output_str) # remove HASHTAG tag\n output_str = re.sub(' s ', ' ', output_str) # remove 's\n\n return output_str\n\n\n# In[67]:\n\n\n# Path and construct a file list\nDIREC = \"/Users/Terry/Courses/language_processing/semester2/pan20-author-profiling-training-2020-02-23/\"\nLANG = \"en/\"\nfile_list = os.listdir(DIREC + LANG)\n\nfor i in file_list:\n if i[-3:] != \"xml\":\n file_list.remove(i)\n\nfile_list = sorted(file_list)\n\n\n# In[68]:\n\n\n# Get ground truth, append into the dataframe\nGT = DIREC + LANG + \"truth.txt\"\ntrue_values = OrderedDict()\nf = open(GT)\n\nfor line in f:\n linev = line.strip().split(\":::\")\n true_values[linev[0]] = linev[1]\n \nf.close()\n\ndf = pd.DataFrame(sorted(true_values.items()))\ndf = df.rename({0:\"ID\", 1:\"label\"}, axis = 1)\ndf[\"label\"] = df[\"label\"].astype(\"int\")\n\n\n# In[69]:\n\n\ndef get_representation_tweets(FILE):\n parsedtree = ET.parse(FILE)\n documents = parsedtree.iter(\"document\")\n \n texts = []\n for doc in documents:\n texts.append(doc.text)\n \n lengths = [len(text) for text in texts]\n \n# return (np.mean(lengths), np.std(lengths))\n return (texts)\n\n\n# In[70]:\n\n\n# append each content into DF\nx = []\nfor i in range(len(file_list)):\n ind = file_list[i]\n x.append(get_representation_tweets(DIREC + LANG + ind))\n \ndf[\"content\"] = pd.Series(x)\n\ndf.head()\n\n\n# Above code could generate a basic dataframe that contains IDs and the correspondent labels and contents. Make sure the **DIREC** variable should align to your local path. \n\n# ## Word Count\n\n# In[71]:\n\n\nword_true = []\nword_fake = []\ntrue = df[df[\"label\"] == 0]\nfake = df[df[\"label\"] == 1]\n\nfor i in range(len(true)):\n tweets = true.iloc[i][2]\n for j in range(len(tweets)):\n single_sentence = clean(tweets[j])\n word_true.append(len(single_sentence.split()))\n\nfor i in range(len(fake)):\n tweets = fake.iloc[i][2]\n for j in range(len(tweets)):\n single_sentence = clean(tweets[j])\n word_fake.append(len(single_sentence.split()))\n\nprint(np.mean(word_true), np.std(word_true))\nprint(np.mean(word_fake), np.std(word_fake))\n\n\n# In[72]:\n\n\n# add features\nword_count = []\n\nfor i in range(len(df)):\n tweets = df.iloc[i][2]\n s = []\n for j in range(len(tweets)):\n single_sentence = clean(tweets[j])\n s.append(len(single_sentence.split()))\n \n word_count.append(s)\n \nfor i in range(300):\n word_count[i] = np.sum(word_count[i])\ndf[\"word_count\"] = word_count\ndf.head()\n\n\n# ## Count stopwords\n\n# In[73]:\n\n\nfrom nltk.corpus import stopwords\nstopword = stopwords.words('english')\n\nfrom nltk.tokenize import word_tokenize\n\n\n# In[74]:\n\n\ndef stop_word_count(sentence):\n m = sentence.split()\n cnt = 0\n for word in m:\n if word in stopword:\n cnt+=1\n \n return cnt\n\n\n# In[75]:\n\n\n# add features\nstopword_count = []\n\nfor i in range(len(df)):\n tweets = df.iloc[i][2]\n s = []\n for j in range(len(tweets)):\n single_sentence = clean(tweets[j])\n #stop = len(set(stopword) & set(single_sentence.split()))\n stop = stop_word_count(single_sentence)\n\n s.append(stop)\n\n \n stopword_count.append(s)\n\nprint(len(stopword_count))\n \nfor i in range(300):\n stopword_count[i] = np.sum(stopword_count[i])\ndf[\"stopword\"] = stopword_count\ndf.head()\n\n\n# In[76]:\n\n\n# Statistics of stopwords\n\nprint (np.mean(df[df[\"label\"] == 0][\"stopword\"]))\nprint (np.mean(df[df[\"label\"] == 1][\"stopword\"]))\n\nprint (np.std(df[df[\"label\"] == 0][\"stopword\"]))\nprint (np.std(df[df[\"label\"] == 1][\"stopword\"]))\n\nmean_stop_true = np.mean(df[df[\"label\"] == 0][\"stopword\"])\nmean_stop_fake = np.mean(df[df[\"label\"] == 1][\"stopword\"])\nstd_stop_true = np.std(df[df[\"label\"] == 0][\"stopword\"])\nstd_stop_fake = np.std(df[df[\"label\"] == 1][\"stopword\"])\n\n\n# In[77]:\n\n\n# Plot\nplt.figure(figsize = (16, 6)) # figure size\nfs = 16 # fontsize \n\nplt.subplot(121)\nplt.bar([0, 3],[np.mean(word_true), np.std(word_true)], label = \"True\", color = \"#00589c\") # use HEX code to specify colors\nplt.bar([1, 4],[np.mean(word_fake), np.std(word_fake)], label = \"Fake\", color = \"#cd0000\")\nplt.yticks([0, 0.2, 0.4, 0.6, 0.8, 1], fontsize = fs);\n\nplt.ylabel(\"word numbers\", fontsize = fs) # specify label\nplt.xticks([0.5, 3.5], [\"Mean\", \"Std\"], fontsize = fs) # specify ticks\nplt.yticks(range(0, 13, 2), fontsize = fs) # specify ticks\n\nplt.legend(fontsize = fs)\nplt.title(\"Word Count\", fontsize = fs)\n#plt.savefig(\"word_count.png\", dpi = 300) # default resolution is low, so remember to set the resolution\n\n\n# plt.subplot(122)\n# plt.bar([0, 3],[mean_stop_true, std_stop_true], label = \"True\", color = \"#00589c\") # use HEX code to specify colors\n# plt.bar([1, 4],[mean_stop_fake, std_stop_fake], label = \"Fake\", color = \"#cd0000\")\n\n# plt.ylabel(\"word numbers\", fontsize = fs) # specify label\n# plt.xticks([0.5, 3.5], [\"Mean\", \"Std\"], fontsize = fs) # specify ticks\n# plt.yticks(range(0, 301, 50), fontsize = fs) # specify ticks\n\n# plt.legend(fontsize = fs)\n# plt.title(\"Stopword Count\", fontsize = fs)\n#plt.savefig(\"word_count.png\", dpi = 300) # default resolution is low, so remember to set the resolution\n\n\n# In[78]:\n\n\n# Combine features from other team member\nmen1 = pd.read_csv(\"dataframe2.csv\")\nmen2 = pd.read_csv(\"dataframe.csv\")\n\ndf[\"cross_post_duplicate\"] = men2[\"cross post\"]\ndf[\"cross_post\"] = men1[\"cross post\"]\n\ndf[\"retweet\"] = men1[\"retweet count\"]\ndf[\"user_mention\"] = men1[\"user mention counts\"]\ndf[\"hashtag\"] = men1[\"hashtag counts\"]\n\n\nmen3 = pd.read_csv(\"dataframe3.csv\")\n\nadd_features = [\"lexical_diversity\", \n \"exclamation_mark\",\n \"question_mark\",\n \"name_entites\",\n \"adjective_frequecy\",\n \"verb_frequency\",\n \"noun_frequency\",\n \"adverb_frequency\",\n \"pronoun_frequency\",]\nfor i in add_features:\n df[i] = men3[i]\n \n \nadd_features = [\"mean_sentiment\", \n \"std_of_sentiment\",\n \"mean_subjectivity\",\n \"std_of_subjectivity\"]\n\nmen4 = pd.read_csv(\"dataframe4.csv\")\n\n\nfor i in add_features:\n df[i] = men4[i]\n\n\n# In[174]:\n\n\ndef dist_plot(item, b, fs):\n sns.distplot(df[df[\"label\"] == 1][item], bins = b, norm_hist = True, kde = False, label = \"Fake\", color = \"#cd0000\")\n sns.distplot(df[df[\"label\"] == 0][item], bins = b, norm_hist = True, kde = False, label = \"True\", color = \"#00589c\")\n plt.title(item)\n plt.legend(fontsize = fs)\n plt.xlabel(\"\", fontsize = fs)\n\n\n# - sentence length (avg, std)\n# - Capitalize\n# - TF-IDF\n# - stopwords\n\n# trump\n# obama\n# us\n# U.S.\n# iran\n# rubio\n# islam\n# GOP\n\n# In[80]:\n\n\nkeywords = [\"trump\", \"obama\", \"biden\", \"clinton\", \"us\", \"iran\", \"rubio\", \"gop\", \"islam\", \"islamic\", \"u\", \"top\", \"kim\", \"bush\", \"visa\"]\nnumbers = [str(i) for i in range(100)]\n\n\n# In[81]:\n\n\nkey_cnt = []\nnumber_cnt = []\nfor i in range(300):\n kcnt = []\n ncnt = []\n\n for j in range(100):\n sen = clean(df[\"content\"][i][j]).lower().split()\n kcnt.append(len(set(keywords) & set(sen)))\n ncnt.append(len(set(numbers) & set(sen)))\n\n #print (\"key:\", kcnt, \"num:\", ncnt, sen)\n \n key_cnt.append(np.sum(kcnt))\n number_cnt.append(np.sum(ncnt))\n\n\n# In[82]:\n\n\ndf[\"keywords\"] = pd.Series(key_cnt)\ndf[\"numbers\"] = pd.Series(number_cnt)\n\n\n# In[83]:\n\n\nword_true = []\nword_fake = []\ntrue = df[df[\"label\"] == 0]\nfake = df[df[\"label\"] == 1]\n\nfor i in range(len(true)):\n tweets = true.iloc[i][2]\n for j in range(len(tweets)):\n single_sentence = clean(tweets[j])\n word_true.append(len(single_sentence.split()))\n\nfor i in range(len(fake)):\n tweets = fake.iloc[i][2]\n for j in range(len(tweets)):\n single_sentence = clean(tweets[j])\n word_fake.append(len(single_sentence.split()))\n\nprint(np.mean(word_true), np.std(word_true))\nprint(np.mean(word_fake), np.std(word_fake))\n\n\n# In[84]:\n\n\n\nlexical = ['word_count', 'stopword', 'exclamation_mark', 'question_mark', 'keywords', 'numbers', 'lexical_diversity', 'named_entites']\n \nuser_behavior = ['cross_post_duplicate', 'cross_post', 'retweet', 'user_mention', 'hashtag']\n \nsyntactic = ['adjective_frequecy', 'verb_frequency', 'noun_frequency', 'adverb_frequency', 'pronoun_frequency']\n \nsentiment = [\"mean_sentiment\", \"std_of_sentiment\", \"mean_subjectivity\", \"std_of_subjectivity\"]\n\n\n# In[85]:\n\n\ndf = df.rename({\"stopword_count\": \"stopword\"}, axis = 1)\ndf = df.rename({\"name_entites\": \"named_entities\"}, axis = 1)\n\n\n# ## Plot of features\n\n# In[86]:\n\n\ndf.head()\n\n\n# In[87]:\n\n\ndf[\"stopword\"]\n\n\n# In[175]:\n\n\nimport seaborn as sns\nb = 30\nfs = 16\nplt.figure(figsize = (15, 4))\n\n\nfin = [\"stopword\", \"lexical_diversity\", 'user_mention']\nplt.subplot(131)\ndist_plot(fin[0], b = b, fs = fs)\nplt.title(\"Stopword\", fontsize = fs)\nplt.ylabel(\"frequency\",fontsize = 14)\nplt.xlabel(\"count\",fontsize = 14)\n\n\nplt.subplot(132)\ndist_plot(fin[1], b = b, fs = fs)\nplt.title(\"Lexical diversity\", fontsize = fs)\nplt.xlabel(\"score\",fontsize = 14)\n\n\nplt.subplot(133)\ndist_plot(fin[2], b = b, fs = fs)\nplt.title(\"User Mention\", fontsize = fs)\nplt.xlabel(\"count\",fontsize = 14)\n\nplt.savefig(\"feats.png\", dpi = 300)\n\n\n# In[89]:\n\n\nimport seaborn as sns\nb = 30\nfs = 16\n\nplt.figure(figsize = (18, 9))\n\nlexical = ['word_count', 'stopword', 'exclamation_mark', 'question_mark', 'keywords', 'numbers', 'lexical_diversity', 'named_entities']\nplt.subplot(241)\ndist_plot(lexical[0], b = b, fs = fs)\n\nplt.subplot(242)\ndist_plot(lexical[1], b = b, fs = fs)\n\nplt.subplot(243)\ndist_plot(lexical[2], b = b, fs = fs)\n\nplt.subplot(244)\ndist_plot(lexical[3], b = b, fs = fs)\n\n\nplt.subplot(245)\ndist_plot(lexical[4], b = b, fs = fs)\n\nplt.subplot(246)\ndist_plot(lexical[5], b = b, fs = fs)\n\nplt.subplot(247)\ndist_plot(lexical[6], b = b, fs = fs)\n\nplt.subplot(248)\ndist_plot(lexical[7], b = b, fs = fs)\n\nplt.savefig(\"lexical.png\", dpi = 300)\n\n\n# In[90]:\n\n\nb = 30\nfs = 16\n\nplt.figure(figsize = (16, 9))\n\nuser_behavior = ['cross_post_duplicate', 'cross_post', 'retweet', 'user_mention', 'hashtag']\nplt.subplot(231)\ndist_plot(user_behavior[0], b = b, fs = fs)\n\nplt.subplot(232)\ndist_plot(user_behavior[1], b = b, fs = fs)\n\nplt.subplot(233)\ndist_plot(user_behavior[2], b = b, fs = fs)\n\nplt.subplot(234)\ndist_plot(user_behavior[3], b = b, fs = fs)\n\nplt.subplot(235)\ndist_plot(user_behavior[4], b = b, fs = fs)\n\n\n\nplt.savefig(\"user_behavior.png\", dpi = 300)\n\n\n# In[91]:\n\n\nb = 30\nfs = 16\n\nplt.figure(figsize = (16, 9))\n\nsyntactic = ['adjective_frequecy', 'verb_frequency', 'noun_frequency', 'adverb_frequency', 'pronoun_frequency']\nplt.subplot(231)\ndist_plot(syntactic[0], b = b, fs = fs)\n\nplt.subplot(232)\ndist_plot(syntactic[1], b = b, fs = fs)\n\nplt.subplot(233)\ndist_plot(syntactic[2], b = b, fs = fs)\n\nplt.subplot(234)\ndist_plot(syntactic[3], b = b, fs = fs)\n\nplt.subplot(235)\ndist_plot(syntactic[4], b = b, fs = fs)\n\n\n\nplt.savefig(\"syntactic.png\", dpi = 300)\n\n\n# In[92]:\n\n\nb = 30\nfs = 16\n\nplt.figure(figsize = (16, 9))\n\nsentiment = [\"mean_sentiment\", \"std_of_sentiment\", \"mean_subjectivity\", \"std_of_subjectivity\"]\nplt.subplot(221)\ndist_plot(sentiment[0], b = b, fs = fs)\n\nplt.subplot(222)\ndist_plot(sentiment[1], b = b, fs = fs)\n\nplt.subplot(223)\ndist_plot(sentiment[2], b = b, fs = fs)\n\nplt.subplot(224)\ndist_plot(sentiment[3], b = b, fs = fs)\n\n\nplt.savefig(\"sentiment.png\", dpi = 300)\n\n\n# In[93]:\n\n\nlstm = np.array([[ 0.42630056, -0.17814395],\n [-0.14523156, -0.2238305 ],\n [-0.17335439, -0.34844938],\n [ 0.25363263, -0.0485195 ],\n [-0.02997215, -0.3810338 ],\n [-0.30927843, -0.4811428 ],\n [-0.3034206 , 0.4003904 ],\n [-0.49077418, -0.32006943],\n [-0.35700735, 0.5064111 ],\n [-0.36409566, -0.08085655],\n [-0.16039595, -0.3579484 ],\n [-0.21042153, -0.13189687],\n [ 0.49798813, 0.19036944],\n [ 0.30867413, -0.286953 ],\n [-0.25924218, -0.04462197],\n [ 0.45879966, -0.16211168],\n [-0.2752164 , -0.10683901],\n [-0.28118694, -0.09712957],\n [ 0.5627344 , 0.42410606],\n [-0.47488025, 0.07553235]])\n\n\n# In[94]:\n\n\nneu = pd.DataFrame(index=range(300),columns=range(20))\nneu[\"label\"] = df[\"label\"]\nfor i in range(300):\n for j in range(20):\n if neu[\"label\"][i] == 0:\n neu.iat[i, j] = lstm[j, 0]\n \n if neu[\"label\"][i] == 1:\n neu.iat[i, j] = lstm[j, 1]\n\n\n# In[95]:\n\n\nneu = neu.drop(columns = \"label\", axis = 1)\ndf = pd.concat([df, neu[neu.keys()]], axis = 1)\nfor i in range(20):\n df = df.rename(columns = {i: \"neuron{}\".format(i)})\n\n\n# In[96]:\n\n\ndf.keys()\n\n\n# ## PCA\n\n# In[97]:\n\n\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\n\ndef pca(i):\n \n # Used Features:\n used_features = ['word_count', 'stopword',\n 'cross_post_duplicate', 'cross_post', 'retweet', 'user_mention',\n 'hashtag', 'keywords', 'numbers', 'lexical_diversity',\n 'exclamation_mark', 'question_mark', 'named_entities',\n 'adjective_frequecy', 'verb_frequency', 'noun_frequency',\n 'adverb_frequency', 'pronoun_frequency', \"mean_sentiment\", \"std_of_sentiment\",\n \"mean_subjectivity\", \"std_of_subjectivity\"]\n\n neurons = ['neuron0', 'neuron1', 'neuron2', 'neuron3', \n 'neuron4', 'neuron5', 'neuron6', 'neuron7', 'neuron8', \n 'neuron9', 'neuron10', 'neuron11','neuron12', \n 'neuron13', 'neuron14', 'neuron15', 'neuron16', 'neuron17',\n 'neuron18', 'neuron19']\n \n if i == 99:\n features = used_features\n else:\n neu = []\n for n in range(i):\n neu += [neurons[n]]\n features = used_features + neu\n\n\n # Separating out the features\n x = df[features].values\n # Separating out the target\n y = df['label'].values\n # Standardizing the features\n x = StandardScaler().fit_transform(x)\n\n pca = PCA(n_components=2)\n principalComponents = pca.fit_transform(x)\n principalDf = pd.DataFrame(data = principalComponents\n , columns = ['PC1', 'PC2'])\n\n principalDf[\"label\"] = df[\"label\"]\n\n plt.scatter(x = principalDf[principalDf[\"label\"] == 1][\"PC1\"], y = principalDf[principalDf[\"label\"] == 1][\"PC2\"], color = \"#cd0000\", label = \"Fake\", alpha = 0.7)\n plt.scatter(x = principalDf[principalDf[\"label\"] == 0][\"PC1\"], y = principalDf[principalDf[\"label\"] == 0][\"PC2\"], color = \"#00589c\", label = \"True\", alpha = 0.7)\n plt.legend(fontsize = fs)\n plt.xlabel(\"PC1\", fontsize = fs)\n plt.ylabel(\"PC2\",fontsize = fs)\n plt.title(\"Features + Neuron[0-{}]\".format(i), fontsize = fs)\n\n\n# In[98]:\n\n\nplt.figure(figsize = (20, 20))\nplt.subplot(331)\npca(99)\nplt.title(\"Features\", fontsize = 16)\n\nplt.subplot(332)\npca(0)\nplt.title(\"Features + Neuron0\", fontsize = 16)\n\n\nplt.subplot(333)\npca(1)\n\nplt.subplot(334)\npca(2)\n\nplt.subplot(335)\npca(3)\n\nplt.subplot(336)\npca(4)\n\nplt.subplot(337)\npca(5)\n\nplt.subplot(338)\npca(6)\n\nplt.subplot(339)\npca(7)\n\nplt.savefig(\"pca_neurons_en.png\", dpi = 150)\n\n\n# ## Model\n\n# In[99]:\n\n\n# Used Features:\nused_features = [\n 'word_count', 'stopword', 'cross_post_duplicate', 'cross_post', 'retweet', \n 'user_mention','hashtag', 'keywords', 'numbers', 'lexical_diversity',\n 'exclamation_mark', 'question_mark', 'named_entities', 'adjective_frequecy', \n 'verb_frequency', 'noun_frequency', 'adverb_frequency', 'pronoun_frequency', \n \"mean_sentiment\", \"std_of_sentiment\", \"mean_subjectivity\", \"std_of_subjectivity\"]\n\n\n# In[100]:\n\n\nneuron_list = []\nfor i in range(20):\n neuron_list.append(\"neuron{}\".format(i))\n\n\n# In[101]:\n\n\nneuron_list\n\n\n# In[152]:\n\n\nX = df.drop([\"ID\", \"label\", \"content\"], axis = 1)\ny = df[\"label\"]\n\n\n# In[153]:\n\n\nX.keys()\n\n\n# In[154]:\n\n\nprint (X.shape)\nprint (y.shape)\nX.head()\n\n\n# In[155]:\n\n\nfrom sklearn.model_selection import train_test_split as split\n\nX_train, X_test, y_train, y_test = split(X, y, test_size=0.33, random_state=42)\n\n\n# In[156]:\n\n\nscaler = StandardScaler()\nscaler.fit(X_train) \nX_scaled = pd.DataFrame(scaler.transform(X_train),columns = X_train.columns)\n\nscaler.fit(X_test) \nX_test_scaled = pd.DataFrame(scaler.transform(X_test),columns = X_test.columns)\n\n\n# In[157]:\n\n\nX_train.shape\n\n\n# In[158]:\n\n\ny_train.shape\n\n\n# In[159]:\n\n\n# AdaBoost\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score as acc\n\n# not scaled\nclf = AdaBoostClassifier(n_estimators=300, random_state=42)\nclf.fit(X_train, y_train)\npred = clf.predict(X_test)\nprint (\"not scaled\", acc(pred, y_test))\n\n# scaled\nclf = AdaBoostClassifier(n_estimators=300, random_state=42)\nclf.fit(X_scaled, y_train)\npred = clf.predict(X_test_scaled)\nprint (\"scaled\", acc(pred, y_test))\n\n\n# In[176]:\n\n\npred\n\n\n# In[160]:\n\n\ndef feature_importance():\n importances = clf.feature_importances_\n std = np.std([clf.feature_importances_ for tree in clf.estimators_],\n axis=0)\n indices = np.argsort(importances)[::-1]\n print (\"Ranking1\", X_train.keys()[indices[0]], \n \"Ranking2\", X_train.keys()[indices[1]],\n \"Ranking3\", X_train.keys()[indices[2]])\n\n # Print the feature ranking\n print(\"Feature ranking:\")\n\n for f in range(X.shape[1]):\n print(\"%d. feature %d (%f)\" % (f + 1, indices[f], importances[indices[f]]))\n\n # Plot the impurity-based feature importances of the forest\n plt.figure(figsize = (14, 8))\n plt.title(\"Feature importances\", fontsize = 16)\n plt.bar(range(X.shape[1]), importances[indices],\n color=\"r\", yerr=std[indices], align=\"center\")\n plt.xticks(range(X.shape[1]), indices)\n plt.xlim([-1, X.shape[1]])\n plt.xlabel(\"Features\", fontsize = 16)\n plt.show()\n\n\n# In[148]:\n\n\n# Random Forest\n# not scaled\nfrom sklearn.ensemble import RandomForestClassifier\nclf = RandomForestClassifier(n_estimators=100, random_state=42)\nclf.fit(X_train, y_train)\npred = clf.predict(X_test)\nprint (acc(pred, y_test))\nfeature_importance()\n\n\n# In[162]:\n\n\nprint (X_scaled.keys()[23])\nprint (X_scaled.keys()[38])\nprint (X_scaled.keys()[35])\n\n\n# In[161]:\n\n\n# scaled\nclf = RandomForestClassifier(n_estimators=15, random_state=42)\nclf.fit(X_scaled, y_train)\npred = clf.predict(X_test_scaled)\nprint (acc(pred, y_test))\nfeature_importance()\n\n\n# In[135]:\n\n\n# Logistic Regression (early stopping yields better acc)\nfrom sklearn.linear_model import LogisticRegression\nclf = LogisticRegression(random_state=42, max_iter=40)\nclf.fit(X_train, y_train)\npred = clf.predict(X_test)\nprint (acc(pred, y_test))\n\n# Logistic Regression (early stopping yields better acc)\nfrom sklearn.linear_model import LogisticRegression\nclf = LogisticRegression(random_state=42, max_iter=40)\nclf.fit(X_scaled, y_train)\npred = clf.predict(X_test_scaled)\nprint (acc(pred, y_test))\n\n\n# In[114]:\n\n\nfrom sklearn import svm\n\nfor i in [\"linear\", \"poly\", \"rbf\", \"sigmoid\"]:\n clf = svm.SVC(random_state = 42, kernel = i, C = 5)\n clf.fit(X_train, y_train)\n pred = clf.predict(X_test)\n print (i, acc(pred, y_test))\n \nfor i in [\"linear\", \"poly\", \"rbf\", \"sigmoid\"]:\n clf = svm.SVC(random_state = 42, kernel = i, C = 5)\n clf.fit(X_scaled, y_train)\n pred = clf.predict(X_test_scaled)\n print (i, acc(pred, y_test))\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[115]:\n\n\ndf.to_csv(\"all.csv\")\n\n\n# In[ ]:\n\n\n\n\n\n# In[116]:\n\n\nnew.to_csv(\"new.csv\")\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"laiaccc/Profiling_fake_news_spreader_on_Twitter","sub_path":"code/features_and_classification.py","file_name":"features_and_classification.py","file_ext":"py","file_size_in_byte":20494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"35805010323","text":"'''\nCreated on Nov 7, 2020\n\n@author: rluna\n'''\n\nimport os\nimport os.path\nimport pickle\nimport base64\n\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nfrom email.mime.text import MIMEText\nfrom googleapiclient.discovery import build\n\n\nclass Gmail(object):\n '''\n sends an email using gmail\n '''\n # If modifying these scopes, delete the file token.pickle.\n SCOPES = ['https://www.googleapis.com/auth/gmail.send']\n token_file = \"token.pickle\"\n credentials_file = \"credentials.json\"\n\n\n def __init__(self):\n pass\n \n\n def loadOrValidateCredentials( self ):\n self.creds = None\n # The file token.pickle stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time\n if os.path.exists(self.token_file) : \n with open(self.token_file, 'rb') as token : \n self.creds = pickle.load(token)\n # If there are no (valid) credentials available, let the user log in.\n if not self.creds or not self.creds.valid:\n if self.creds and self.creds.expired and self.creds.refresh_token:\n self.creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n self.credentials_file, self.SCOPES )\n self.creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open(self.token_file, 'wb') as token:\n pickle.dump(self.creds, token)\n self._createService()\n \n\n def _createService(self):\n self._gmail_service = build('gmail', 'v1', credentials=self.creds)\n \n def sendSimpleEmail(self,\n emailFrom, \n emailTo,\n emailSubject, \n emailBody ):\n if isinstance( emailTo, str ) : \n emailTo = [emailTo]\n \n for address in emailTo : \n message = MIMEText(emailBody)\n message['from'] = emailFrom\n message['to'] = address\n message['subject'] = emailSubject\n encoded_message = {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode('ascii')}\n self._gmail_service.users().messages().send(userId=emailFrom, body=encoded_message).execute() \n\n\n","repo_name":"rlunaro/changeMonitor","sub_path":"src/gmail.py","file_name":"gmail.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"7846869279","text":"class Solution(object):\n def smallerNumbersThanCurrent(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n l=[]\n for i in nums:\n smallerNums=0\n for j in nums:\n if i>j:\n smallerNums+=1\n l.append(smallerNums)\n return l\n \n","repo_name":"ahmedinB/A2SV-Progress-Sheet","sub_path":"smallerNumberThanCurrent.py","file_name":"smallerNumberThanCurrent.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"30119286370","text":"#!/usr/bin/python\nimport sys\n\n# cd python/src/p22_tf_idf_reducer_2/\n# python3 reducer.py < test_data_for_reducer.txt\n\nlastKey = None\ncnt = 0\ndoc_tf_buf = []\n\n\ndef do_print(key, count, arr):\n for el in arr:\n print(key + '#' + el[0] + '\\t' + el[1] + '\\t' + str(count))\n return\n\n\nfor line in sys.stdin:\n arr1 = line.strip().split(\"\\t\")\n key = arr1[0]\n arr2 = arr1[1].split(';')\n if lastKey and lastKey != key:\n do_print(lastKey, cnt, doc_tf_buf)\n cnt = 0\n doc_tf_buf = []\n lastKey = key\n cnt += 1\n doc_tf_buf.append((arr2[0], arr2[1]))\nif lastKey:\n do_print(lastKey, cnt, doc_tf_buf)\n","repo_name":"pasharik/hadoop","sub_path":"python/src/p22_tf_idf_reducer_2/reducer.py","file_name":"reducer.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"1240796820","text":"#Problem 5\n#\n#2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.\n#\n#What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?\n\ndef isDivisible(n):\n for i in range(1, 21):\n if n % i != 0:\n return False\n return True\n\nsorting = True\ncurrentnum = 1\nwhile sorting:\n if isDivisible(currentnum):\n sorting = False\n else:\n currentnum += 1\n print(currentnum)","repo_name":"micfun123/projecteuler","sub_path":"5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"74151048249","text":"\"\"\"\nMake two functions that receive a list of integers as input and return the largest and lowest number in that list, respectively.\n\"\"\"\n\ndef minimum(list):\n # Fisrt solution\n minimum = list[0]\n\n for number in list:\n if number < minimum: minimum = number\n\n return minimum\n\n # Second solution\n # return min(list)\n\ndef maximum(list):\n # First solution\n maximum = list[0]\n\n for number in list:\n if number > maximum: maximum = number\n\n return maximum\n\n # Second solution\n # return max(list)\n\nlist = [-52, 56, 30, 29, -54, 0, -110]\n\nprint(minimum(list))\nprint(maximum(list))\n","repo_name":"EmilianoRivasMX/code-challenges","sub_path":"codewars/python/max_and_min.py","file_name":"max_and_min.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"24809753723","text":"\"\"\"\nThis code can be run to load a fitting pair of\n.pyenc and .pykey files, which will then be \"decrypted\" with\nXOR One Time Pad, so the contained code can be compiled and run.\nThe .pyenc and .pykey files can be created with \"CodePacker\".\nBoth, CodeLoader and CodePacker are supposed to be run as a \ncompiled PyInstaller .exe file for Windows.\n\"\"\"\n\n__version__ = '0.1.0'\n\nimport os\n\n\n# Encrypt / Decrypt using XOR\ndef decrypt_code(codefile, keyfile, debug=False):\n # decrypt helper function\n def decrypt(bytestring, key, debug=False):\n if debug:\n print(\"Original:\")\n for ib in range(len(bytestring)):\n print(format(bytestring[ib], \"02x\"), end=\" \")\n print(\"\\nKey:\")\n for ib in range(len(bytestring)):\n print(format(key[ib%len(key)], \"02x\"), end=\" \")\n print(\"\\nResult:\")\n res = b\"\"\n for ib in range(len(bytestring)):\n newbyte = bytes((bytestring[ib] ^ key[ib%len(key)],))\n res += newbyte\n if debug:\n print(format(newbyte[0], \"02x\"), end=\" \")\n return res\n enc_code = open(codefile, 'rb').read()\n cryptokey = open(keyfile, 'rb').read()\n return decrypt(enc_code, cryptokey)\n\n\n# Load every file with a .pyenc-ending, then decrypt and run it.\nif __name__ == '__main__':\n for filename in os.listdir(os.getcwd()):\n if filename[-6:] == \".pyenc\":\n print(\"Opening\", filename)\n code = decrypt_code(filename, filename[:-6]+'.pykey', debug=False)\n print()\n print(code.decode('utf-8'))\n print()\n comp_code = compile(code, '', 'exec')\n retval = exec(comp_code)\n else:\n print(\"Skipping\", filename)\n print(\"END\")\n input()\n","repo_name":"darkAco/lw_ftsrv","sub_path":"Code/CodeLoader.py","file_name":"CodeLoader.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"24629539820","text":"\nfrom django.conf.urls import url\n\nfrom .views import InvokerView, ResultView, ResultSocketView\n# from django.views.generic.base import TemplateView\n\n\n\nurlpatterns = [\n url(r'^$', InvokerView.as_view(), name='invoker'),\n url(r'^result/(?P\\w+)$', ResultView.as_view(), name='result'),\n # url(r'^result_socket/$', TemplateView.as_view(template_name=\"scraper_invoker/result_socket.html\")),\n # url(r'^result_socket/(?P\\w+)/(?P[\\w,&]+)/(?P\\w+)/(?P.*)$', ResultSocketView.as_view(), name='socket_result'),\n url(r'^result_socket/(?P[0-9a-z-]+)$', ResultSocketView.as_view(), name='socket_result'),\n]\n","repo_name":"didoogan/image_parser","sub_path":"django_app/scraper_invoker/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"28221884111","text":"import time\ndef writeLog(type,text):\n\tlog = open(\"logs/log_\"+time.strftime(\"%Y-%m-%d\",time.localtime())+\".txt\",\"a\")\n\tif type == \"warn\":\n\t\tsign = \"WARNING: \"\n\telif type == \"err\":\n\t\tsign = \"ERROR: \"\n\telse:\n\t\tsign = \"INFO: \"\n\tlog.write(time.strftime(\"%H:%M:%S\",time.localtime())+\" \"+sign+\"\t\"+text+\"\\n\")\nwriteLog(\"inf\",\"Starting...\\nCurrent time: \"+time.strftime(\"%Y/%m/%d %H:%M:%S\"))\nglobal ispi\nfrom init_vars import *\ntry:\n\timport RPi.GPIO as gpio\n\tgpio.setmode(gpio.BOARD)\n\tgpio.setup(tvpin, gpio.OUT)\n\tgpio.setup(isrunningledpin, gpio.OUT)\n\tgpio.setup(timerledpin, gpio.OUT)\n\tgpio.output(isrunningledpin, gpio.HIGH)\n\tispi = True\nexcept ImportError:\n\tispi = False\n\tprint(\"WARNING: Couldn't load the RPi.GPIO module, GPIO functions won't work\")\n\twriteLog(\"warn\",\"Couldn't load the RPi.GPIO module, GPIO functions won't work\")\nimport os\nimport datetime\nfrom threading import Thread\ndef stopBell():\n\tif ispi:\n\t\tgpio.output(isrunningledpin, gpio.LOW)\n\t\tgpio.output(timerledpin, gpio.LOW)\n\t\tgpio.output(tvpin, gpio.LOW)\n\t\tgpio.cleanup()\n\texit()\ndef ringBell(startend):\n\tif ispi:\n\t\tgpio.output(tvpin, gpio.HIGH)\n\ttime.sleep(5)\n\tif startend == \"start\":\n\t\tos.system(termcommand+\" sound/start.wav\")\n\t\twriteLog(\"inf\",\"Sending command to play end.wav\")\n\telif startend == \"end\":\n\t\twriteLog(\"inf\",\"Sending command to play start.wav\" )\n\t\tos.system(termcommand+\" sound/end.wav\")\n\ttime.sleep(10)\n\tif ispi:\n\t\tgpio.output(tvpin, gpio.HIGH)\ndef importSchoolDays():\n\tdayfile = open(\"data/schooldays.txt\",\"r\")\n\tdayraw = dayfile.readlines()\n\tdayfile.close()\n\ttry:\n\t\tdays = dayraw[0].split(\" \")\n\texcept IndexError:\n\t\tdays = [\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\",\"Sun\"]\n\ti = 0\n\twhile i Stopping\")\n\t\t\t\tstopBell()\n\t\t\tif asd[0] == True:\n\t\t\t\twriteLog(\"inf\",\"Ringing bell\")\n\t\t\t\tif asd[1] == 0:\n\t\t\t\t\tprint(\"INFO: Ringing bell (start) at \"+time.strftime(\"%H:%M\",time.localtime()))\n\t\t\t\t\tringBell(\"start\")\n\t\t\t\t\ttime.sleep(60)\n\t\t\t\telif asd[1] == 1:\n\t\t\t\t\tprint(\"INFO: Ringing bell (end) at \"+time.strftime(\"%H:%M\",time.localtime()))\n\t\t\t\t\tringBell(\"end\")\n\t\t\t\t\ttime.sleep(60)\n\t\t\telif isPreBellTime(schedule):\n\t\t\t\twriteLog(\"inf\",\"Ringing warning bell\")\n\t\t\t\tprint(\"INFO: Ringing warning bell at \"+time.strftime(\"%H:%M\",time.localtime()))\n\t\t\t\tringBell(\"start\")\n\t\t\t\ttime.sleep(60)\n\t\t\telse:\n\t\t\t\ttime.sleep(10)\n\texcept KeyboardInterrupt:\n\t\tprint(\"INFO: Stopped manually\")\n\t\twriteLog(\"inf\",\"Stopped manually\")\n\t\tstopBell()\ntry:\n\tbreaks = importBreaks()\n\tschedule = importSchedule()\n\tsatschool = importSatSchoolDays()\n\tfreedays = importWDaysWOutSchool()\n\tschooldays = importSchoolDays()\nexcept IOError:\n\tprint(\"ERROR:Couldn't import every file from the data folder, file may be deleted, or may be renamed to a wrong name\")\n\tprint(\"Stopping...\")\n\twriteLog(\"err\",\"Couldn't import every file --> Stopping\")\n\tstopBell()\nprint(\"INFO: All data has been read succesfully!\")\nwriteLog(\"inf\",\"All data has been read succesfully\")\nprint(\"Ring schedule:\")\nprint(schedule)\nprint(\"Breaks:\")\nprint(breaks)\nprint(\"Saturday schooldays:\")\nprint(satschool)\nprint(\"Weekdays without school:\")\nprint(freedays)\nprint(\"Days of the week with school:\")\nprint(schooldays)\nstopped = True\nif isSchoolDay(schooldays):\n\tif isBreak(breaks) == False:\n\t\tif isDay(freedays) == False:\n\t\t\tprint(\"INFO: Starting timer functions\")\n\t\t\twriteLog(\"inf\",\"Today is a schoolday\")\n\t\t\twriteLog(\"inf\",\"Starting timer functions\")\n\t\t\tstartTimer(schedule)\n\t\t\tstopped = False\n\t\telse:\n\t\t\tprint(\"INFO: Today is a weekday without school\")\n\t\t\twriteLog(\"inf\",\"Today is a weekday without school\")\n\telse:\n\t\tprint(\"INFO: Today there is a break going on\")\n\t\twriteLog(\"inf\",\"Today is included in a break\")\nelse:\n\tprint(\"INFO: Today is not a weekday with school\")\n\twriteLog(\"inf\",\"Today is not a weekday with school\")\nif isDay(satschool) and stopped:\n\tprint(\"INFO: Today is a saturday with school\")\n\twriteLog(\"inf\", \"Today is a saturday with school\")\n\tprint(\"Starting timer functions\")\n\twriteLog(\"inf\",\"Starting timer functions\")\n\tstartTimer(schedule)\nprint(\"INFO: Exiting\")\nwriteLog(\"inf\",\"Exiting\")\nstopBell()\n","repo_name":"hixio-mh/school_bell","sub_path":"bell.py","file_name":"bell.py","file_ext":"py","file_size_in_byte":7289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"70336276410","text":"from flask import Flask, render_template, request\r\nfrom flask_sqlalchemy import SQLAlchemy\r\n\r\nimport config as config\r\n\r\n# инициализация и подключение к бд\r\napp = Flask(__name__)\r\napp.config.from_object(config)\r\n\r\ndb = SQLAlchemy(app)\r\n\r\n\r\n# роут на главную, выводит все сборки\r\n@app.route('/', methods=['GET', 'POST'])\r\ndef index():\r\n # импортируем модель сборки, потому что в ней импортируется bd => выше поднять не можем\r\n from models import Musicset, Track\r\n # получаем то что у нас в select и search\r\n search = request.args.get('search')\r\n select = request.args.get('select')\r\n # создаем сессию / подключение к можели Track\r\n track_session = db.session.query(Track)\r\n # если существует переменная search\r\n if search:\r\n # если выбран артист\r\n if select == 'artist':\r\n # фильтруем артиста по введенному значению, возвращаем треки\r\n result = track_session.filter(Track.artist.ilike('%{0}%'.format(search)))\r\n # если выбрано название трека\r\n elif select == 'track_title':\r\n # фильтруем треки по введенному названию, возвращаем треки\r\n result = track_session.filter(Track.title.ilike('%{0}%'.format(search)))\r\n # если выбрано название сборки\r\n elif select == 'set_title':\r\n # фильтруем по названию сборки, возвращаем сборки\r\n mst = Musicset.query.filter(Musicset.set_title.ilike('%{0}%'.format(search)))\r\n # инициализируем массив для треков\r\n result = []\r\n # проходим по выбранным сборкам\r\n for item in mst:\r\n # приводим id борки в str\r\n id = str(item.id)\r\n # фильтруем нужные нам треки и добавляем их в массив\r\n result.extend(Track.query.filter_by(set_id=id))\r\n # если выбран minus\r\n elif select == 'minus':\r\n # фильтруем треки по артисту и названию\r\n d = track_session.filter(Track.artist.ilike('%{0}%'.format(search)) | Track.title.ilike('%{0}%'.format(search)))\r\n # удаляем найденные\r\n d.delete(synchronize_session=False)\r\n # комитим\r\n db.session.commit()\r\n # возвращаем оставшиеся треки\r\n result = Track.query.all()\r\n # если выбран plus\r\n elif select == 'plus':\r\n # если искомое значение не найдено в поле артиста или названия трека, то удаляем трек\r\n track_session.filter(~(Track.artist.ilike('%{0}%'.format(search))\r\n | Track.title.ilike('%{0}%'.format(search))\r\n ))\\\r\n .delete(synchronize_session=False)\r\n # комитим\r\n db.session.commit()\r\n # возвращаем оставшиеся треки\r\n result = Track.query.all()\r\n # если переменная не существует\r\n else:\r\n # достаем ве записи\r\n result = Track.query.all()\r\n\r\n # возвращаем темплейт чтобы вывести заиси\r\n return render_template('start.html', mst=result)\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run()\r\n","repo_name":"P0s7el2/Small-parser-zaycev-top-python","sub_path":"parser_flask_api.py","file_name":"parser_flask_api.py","file_ext":"py","file_size_in_byte":3868,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"24170337993","text":"\n# Angel Higueros\n# 20460\n# Laboratorio A\n\nEPSILON = 'ε'\nfrom graphviz import Digraph\n\nclass Estado:\n\n def __init__(self, id):\n self.id = id\n self.transiciones = []\n\n\nclass AFN:\n def __init__(self, inicial, final, estados):\n self.inicial = inicial\n self.final = final\n self.estados = estados\n\n\n\ndef crear_afn(expresion_regular): # sourcery skip: simplify-len-comparison\n\n if expresion_regular is None:\n return None\n\n num_estado = 1\n stack_afns = []\n\n for i in range(len(expresion_regular)):\n char = expresion_regular[i]\n\n # Crear nuevos estados, inicio - final\n nuevo_inicio = Estado(f\"{num_estado}\")\n num_estado += 1\n nuevo_final = Estado(f\"{num_estado}\")\n\n if char == '|': #union\n # Obtener los dos ultimos estados\n afn2 = stack_afns.pop()\n afn1 = stack_afns.pop()\n\n # Conectar el nuevo estado incial a los dos estados que tenemos\n nuevo_inicio.transiciones.append((afn1.inicial, EPSILON))\n nuevo_inicio.transiciones.append((afn2.inicial, EPSILON))\n\n # Conectar los dos estados que tenemos al nuevo estado final\n afn1.final.transiciones.append((nuevo_final, EPSILON))\n afn2.final.transiciones.append((nuevo_final, EPSILON))\n\n # Crear un nuevo AFN y agregarlo a nuestra lista\n estados = afn1.estados + afn2.estados + [nuevo_inicio, nuevo_final]\n stack_afns.append(AFN(nuevo_inicio, nuevo_final, estados))\n\n elif char == '*': # estrella\n\n # Obtener el utlimo estado\n afn = stack_afns.pop()\n\n # Crear las transiciones, entrada - salida\n nuevo_inicio.transiciones.append((afn.inicial, EPSILON))\n afn.final.transiciones.append((nuevo_final, EPSILON))\n\n\n # Crear las transiciones, arco - incio, final\n afn.final.transiciones.append((afn.inicial, EPSILON))\n nuevo_inicio.transiciones.append((nuevo_final, EPSILON))\n\n # Crear un nuevo AFN y agregarlo a nuestra lista\n estados = afn.estados + [nuevo_inicio, nuevo_final]\n stack_afns.append(AFN(nuevo_inicio, nuevo_final, estados))\n else: # agregar\n \n nuevo_inicio.transiciones.append((nuevo_final, char))\n stack_afns.append(AFN(nuevo_inicio, nuevo_final, [nuevo_inicio, nuevo_final]))\n\n\n num_estado += 1\n\n \n if len(stack_afns) > 1: # concatenacion\n while len(stack_afns) < 1:\n\n afn2 = stack_afns.pop()\n afn1 = stack_afns.pop()\n\n\n afn2.final.transiciones.append((afn1.inicial, EPSILON))\n afn1.inicial.transiciones.append((afn2.final, EPSILON))\n\n \n estados = afn1.estados + afn2.estados\n stack_afns.append(AFN(afn1, afn2, estados))\n\n\n\n return stack_afns.pop()\n\ndef mostrar_afn(afn, r):\n if afn is None:\n return\n\n dot = Digraph(name='AFN')\n for estado in afn.estados:\n if estado == afn.inicial:\n dot.node(str(estado.id), shape='circle', style='bold')\n elif estado == afn.final:\n dot.node(str(estado.id), shape='doublecircle', style='bold')\n else:\n dot.node(str(estado.id))\n\n for transicion in estado.transiciones:\n if transicion[1] is not None:\n dot.edge(str(estado.id), str(transicion[0].id), label=transicion[1])\n else:\n dot.edge(str(estado.id), str(transicion[0].id), label='ε')\n\n dot.attr(rankdir='LR')\n dot.attr(label=f'AFN generado de r={r}')\n dot.render('afn', format='png')\n\n\ndef mostrar_resumen(r, postfix):\n print(\"\\n:: AFN ::\")\n print(\"[] r = \", r)\n print(\"[] postfix = \", postfix)","repo_name":"angelhigueros11/dl-labA","sub_path":"implementacion.py","file_name":"implementacion.py","file_ext":"py","file_size_in_byte":3761,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"623145965","text":"\"\"\"\nExplanation -\nThe problem requires us to find the difference between the highest and lowest amongst a certain number of\nstudents from a list.\nReturn the least difference after calculation.\n\nnums[int] - scores of all students\nk - the number students to compare at a time.\n\nSo, a sliding window makes this easier. But the list has to be sorted first.\nThis way the first student will have the lowest score and the last student will have the highest score.\n(sort is ascending by default)\n\"\"\"\n\n\ndef minimum_difference(nums: list[int], k: int) -> int:\n start = 0\n stop = k - 1\n nums.sort(reverse=True)\n least_difference = max(nums) # this way the least difference can never be bigger than this.\n while stop < len(nums):\n least_difference = min(least_difference, nums[start] - nums[stop])\n start += 1\n stop += 1\n\n return least_difference\n\n\nprint(minimum_difference(nums=[90], k=1))\nprint(minimum_difference(nums=[9, 4, 1, 7], k=2))\nprint(minimum_difference(nums=[87063, 61094, 44530, 21297, 95857, 93551, 9918], k=6))\n","repo_name":"Asif-GD/neetcode_problems","sub_path":"easy/two_pointers/p1984_minimum_difference/p1984_minimum_difference.py","file_name":"p1984_minimum_difference.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"35476367636","text":"import pdb\nimport random\nimport statistics\nfrom itertools import chain\n\nimport math\nimport torch.nn.functional as F\nfrom torch import nn\nfrom masked_cross_entropy import *\nfrom utils import Categorical\nfrom modules.BinaryTreeBasedModule import BinaryTreeBasedModule\nfrom utils import clamp_grad\nimport time\nimport copy\nimport re\nimport pdb\nimport os\n\nUSE_CUDA = torch.cuda.is_available()\n\nPAD_token = 0\nSOS_token = 1\nEOS_token = 2\nx1_token = 3\nx2_token = 4\nx3_token = 5\nx4_token = 6\n\nall_entities = [\"m0\", \"m1\", \"m2\", \"m3\", \"m4\", \"m5\", \"m6\", \"m7\", \"m8\", \"m9\"]\navailable_src_vars = ['x1', 'x2', 'x3', 'x4']\n\n\nclass E: # Entities (M0~M9)\n # 0: in\n # 1: on\n # 2: beside\n # 3: recipient theme (E E)\n # 4: theme recipient (E to E)\n # 5: theme agent (E by E)\n # 6: recipient agent (to E by E)\n def __init__(self, entity):\n # [in_word/on_word/beside_word, agent_word/theme_word/recipient_word, entity]\n self.entity_chain = [[None, None, entity]]\n # entity_class\n self.entity_para = None\n\n def add_E_in(self, E0):\n left_E = copy.deepcopy(E0)\n left_E.entity_chain[0][0] = 'in'\n self.entity_chain = self.entity_chain + left_E.entity_chain\n self.entity_para = None\n\n def add_E_on(self, E0):\n left_E = copy.deepcopy(E0)\n left_E.entity_chain[0][0] = 'on'\n self.entity_chain = self.entity_chain + left_E.entity_chain\n self.entity_para = None\n\n def add_E_beside(self, E0):\n left_E = copy.deepcopy(E0)\n left_E.entity_chain[0][0] = 'beside'\n self.entity_chain = self.entity_chain + left_E.entity_chain\n self.entity_para = None\n\n def add_E_recipient_theme(self, E0):\n self.entity_chain[0][1] = 'recipient'\n para_E = copy.deepcopy(E0)\n para_E.entity_chain[0][1] = 'theme'\n self.entity_para = para_E\n\n def add_E_theme_recipient(self, E0):\n self.entity_chain[0][1] = 'theme'\n para_E = copy.deepcopy(E0)\n para_E.entity_chain[0][1] = 'recipient'\n self.entity_para = para_E\n\n def add_E_theme_agent(self, E0):\n self.entity_chain[0][1] = 'theme'\n para_E = copy.deepcopy(E0)\n para_E.entity_chain[0][1] = 'agent'\n self.entity_para = para_E\n\n def add_E_recipient_agent(self, E0):\n self.entity_chain[0][1] = 'recipient'\n para_E = copy.deepcopy(E0)\n para_E.entity_chain[0][1] = 'agent'\n self.entity_para = para_E\n\n\nclass P:\n def __init__(self, action):\n # [ccomp_word/xcomp_word, agent_entity_class, theme_entity_class, recipient_entity_class, action_word]\n self.action_chain = [[None, None, None, None, action]]\n\n self.has_agent = False\n self.has_theme = False\n self.has_recipient = False\n\n self.is_full = False\n\n def add_E_agent(self, E0):\n assert E0.entity_para is None\n\n E_add = copy.deepcopy(E0)\n E_add.entity_chain[0][1] = 'agent'\n self.action_chain[0][1] = E_add\n\n def add_E_theme(self, E0):\n assert E0.entity_para is None\n\n E_add = copy.deepcopy(E0)\n E_add.entity_chain[0][1] = 'theme'\n self.action_chain[0][2] = E_add\n\n def add_E_recipient(self, E0):\n assert E0.entity_para is None\n\n E_add = copy.deepcopy(E0)\n E_add.entity_chain[0][1] = 'recipient'\n self.action_chain[0][3] = E_add\n\n def add_E_recipient_theme(self, E0):\n assert E0.entity_chain[0][1] == 'recipient'\n assert E0.entity_para.entity_chain[0][1] == 'theme'\n\n E_add_0 = copy.deepcopy(E0)\n E_add_1 = copy.deepcopy(E0.entity_para)\n\n E_add_0.entity_para = None\n E_add_1.entity_para = None\n\n self.action_chain[0][3] = E_add_0\n self.action_chain[0][2] = E_add_1\n\n def add_E_theme_recipient(self, E0):\n assert E0.entity_chain[0][1] == 'theme'\n assert E0.entity_para.entity_chain[0][1] == 'recipient'\n\n E_add_0 = copy.deepcopy(E0)\n E_add_1 = copy.deepcopy(E0.entity_para)\n\n E_add_0.entity_para = None\n E_add_1.entity_para = None\n\n self.action_chain[0][2] = E_add_0\n self.action_chain[0][3] = E_add_1\n\n def add_E_theme_agent(self, E0):\n assert E0.entity_chain[0][1] == 'theme'\n assert E0.entity_para.entity_chain[0][1] == 'agent'\n\n E_add_0 = copy.deepcopy(E0)\n E_add_1 = copy.deepcopy(E0.entity_para)\n\n E_add_0.entity_para = None\n E_add_1.entity_para = None\n\n self.action_chain[0][2] = E_add_0\n self.action_chain[0][1] = E_add_1\n\n def add_E_recipient_agent(self, E0):\n assert E0.entity_chain[0][1] == 'recipient'\n assert E0.entity_para.entity_chain[0][1] == 'agent'\n\n E_add_0 = copy.deepcopy(E0)\n E_add_1 = copy.deepcopy(E0.entity_para)\n\n E_add_0.entity_para = None\n E_add_1.entity_para = None\n\n self.action_chain[0][3] = E_add_0\n self.action_chain[0][1] = E_add_1\n\n def add_P_ccomp(self, P0):\n P_add = copy.deepcopy(P0)\n P_add.action_chain[0][0] = 'ccomp'\n\n self.action_chain = self.action_chain + P_add.action_chain\n\n def add_P_xcomp(self, P0):\n P_add = copy.deepcopy(P0)\n P_add.action_chain[0][0] = 'xcomp'\n\n self.action_chain = self.action_chain + P_add.action_chain\n\n\nclass BottomAbstrator(nn.Module):\n # To make bottom abstractions such as 'M0' and 'executive produce'\n def __init__(self, alignment_idx):\n super().__init__()\n self.alignment_idx = alignment_idx\n\n def forward(self, x):\n bottom_span = []\n for position, token in enumerate(x[0]):\n if token.item() in self.alignment_idx:\n bottom_span.append([position, position])\n else:\n continue\n\n return bottom_span\n\n\nclass BottomClassifier(nn.Module):\n # To classify bottom abstractions\n def __init__(self, output_lang, alignments_idx):\n super().__init__()\n self.output_lang = output_lang\n self.alignments_idx = alignments_idx\n\n def forward(self, x, bottom_span):\n span2output_token = []\n for span in bottom_span:\n position = span[0]\n input_idx = x[0, position].item()\n output_idx = self.alignments_idx[input_idx]\n assert len(output_idx) == 1\n output_idx = output_idx[0]\n output_token = self.output_lang.index2word[output_idx]\n span2output_token.append([span, output_token])\n\n return span2output_token\n\n\nclass BottomUpTreeComposer(BinaryTreeBasedModule):\n # To generate a binary tree structure based on bottom abstractions\n def __init__(self, input_dim, hidden_dim, vocab_size, leaf_transformation, trans_hidden_dim, input_lang,\n output_lang,\n alignments_idx={}, entity_list=[], caus_predicate_list=[], unac_predicate_list=[],\n dropout_prob=None):\n super().__init__(input_dim, hidden_dim, leaf_transformation, trans_hidden_dim, dropout_prob)\n self.embd_parser = nn.Embedding(vocab_size, input_dim)\n self.q = nn.Parameter(torch.empty(size=(hidden_dim,), dtype=torch.float32))\n self.var_linear = nn.Linear(in_features=hidden_dim, out_features=2)\n self.hidden_dim = hidden_dim\n self.input_lang = input_lang\n self.output_lang = output_lang\n\n self.alignments_idx = alignments_idx\n self.entity_list = entity_list\n self.predicate_list = caus_predicate_list + unac_predicate_list\n\n self.reset_parameters()\n\n def reset_parameters(self):\n super().reset_parameters()\n nn.init.normal_(self.q, mean=0, std=0.01)\n\n def forward(self, pair, x, bottom_span_batch, span2output_token_batch,\n relaxed=False, tau_weights=None, straight_through=False, noise=None,\n eval_actions=None, eval_sr_actions=None, eval_swr_actions=None, debug_info=None):\n\n batch_size = len(bottom_span_batch)\n\n span2variable_batch = [{} for _ in range(batch_size)]\n\n length_ori = len(x[0])\n\n span2output_token_dict_batch = []\n for span2output_token in span2output_token_batch:\n span2output_token_dict = {}\n for span_token in span2output_token:\n span2output_token_dict[str(span_token[0])] = span_token[1]\n span2output_token_dict_batch.append(span2output_token_dict)\n\n if USE_CUDA:\n single_mask = torch.tensor([[1.]]).cuda()\n h_x1, c_x1 = self._transform_leafs(self.embd_parser(torch.tensor([[x1_token]]).cuda()), mask=single_mask)\n h_x2, c_x2 = self._transform_leafs(self.embd_parser(torch.tensor([[x2_token]]).cuda()), mask=single_mask)\n else:\n single_mask = torch.tensor([[1.]])\n h_x1, c_x1 = self._transform_leafs(self.embd_parser(torch.tensor([[x1_token]])), mask=single_mask)\n h_x2, c_x2 = self._transform_leafs(self.embd_parser(torch.tensor([[x2_token]])), mask=single_mask)\n\n span_start_end = [[i, i] for i in range(length_ori)]\n span_start_end_batch = [span_start_end for _ in range(batch_size)]\n\n for in_batch_idx in range(batch_size):\n bottom_span_batch[in_batch_idx].sort(key=lambda span: span[0], reverse=True)\n\n var_normalized_entropy = []\n var_log_prob = []\n\n x_embedding = self.embd_parser(x)\n x_embedding = x_embedding.expand(batch_size, x_embedding.shape[1], x_embedding.shape[2])\n mask = torch.ones((x_embedding.shape[0], x_embedding.shape[1]), dtype=torch.float32)\n if USE_CUDA:\n mask = mask.cuda()\n hidden_1, cell_1 = self._transform_leafs(x_embedding, mask)\n\n for in_batch_idx in range(batch_size):\n bottom_span = bottom_span_batch[in_batch_idx]\n bottom_span.sort(key=lambda span: span[0], reverse=True)\n span_start_end = span_start_end_batch[in_batch_idx]\n for span in bottom_span:\n span_start_end = span_start_end[:span[0]] + [span] + span_start_end[span[1] + 1:]\n span_start_end_batch[in_batch_idx] = span_start_end\n assert span[1] - span[0] == 0\n\n span2output_token_dict = span2output_token_dict_batch[in_batch_idx]\n token = span2output_token_dict[str(span)]\n assert token in self.entity_list + self.predicate_list\n\n if token in self.entity_list:\n h_x, c_x = h_x1, c_x1\n else:\n h_x, c_x = h_x2, c_x2\n\n hidden_1_one_batch = torch.cat(\n [hidden_1[in_batch_idx:in_batch_idx + 1, :span[0], :],\n h_x,\n hidden_1[in_batch_idx:in_batch_idx + 1, span[1] + 1:, :]], dim=1)\n cell_1_one_batch = torch.cat(\n [cell_1[in_batch_idx:in_batch_idx + 1, :span[0], :],\n c_x,\n cell_1[in_batch_idx:in_batch_idx + 1, span[1] + 1:, :]], dim=1)\n\n hidden_1 = torch.cat([hidden_1[:in_batch_idx], hidden_1_one_batch, hidden_1[in_batch_idx + 1:]], dim=0)\n cell_1 = torch.cat([cell_1[:in_batch_idx], cell_1_one_batch, cell_1[in_batch_idx + 1:]], dim=0)\n\n hidden, cell = hidden_1, cell_1\n\n reduce_span_in_all_span_batch = [[] for _ in range(batch_size)]\n for in_batch_idx in range(batch_size):\n bottom_span = bottom_span_batch[in_batch_idx]\n span_start_end = span_start_end_batch[in_batch_idx]\n for span in span_start_end:\n if span in bottom_span:\n reduce_span_in_all_span_batch[in_batch_idx].append([span])\n else:\n reduce_span_in_all_span_batch[in_batch_idx].append([])\n\n parent_child_spans_batch = [[] for _ in range(batch_size)]\n span2repre_batch = [{} for _ in range(batch_size)]\n\n normalized_entropy = []\n log_prob = []\n\n mask = torch.ones((batch_size, length_ori), dtype=torch.float32)\n if USE_CUDA:\n mask = mask.cuda()\n\n for i in range(1, x_embedding.shape[1]):\n # pdb.set_trace()\n noise = None\n ev_actions = None\n\n cat_distr, _, actions, hidden, cell = self._make_step(hidden, cell, mask[:, i:],\n relaxed, tau_weights,\n straight_through, noise,\n ev_actions)\n\n actions_idx = actions.argmax(dim=1)\n hidden_parent = hidden[torch.arange(hidden.shape[0]), actions_idx] # batch_size * hidden_size\n var_cat_distr, _, var_actions = self._var_make_step(hidden_parent, relaxed,\n tau_weights,\n straight_through, noise,\n ev_actions)\n\n reduce_list = []\n for in_batch_idx in range(batch_size):\n\n action_idx = actions[in_batch_idx].argmax().item()\n span_start_end = span_start_end_batch[in_batch_idx]\n merged_span = [span_start_end[action_idx][0], span_start_end[action_idx + 1][1]]\n # update original span_start_end_batch\n span_start_end_batch[in_batch_idx] = \\\n span_start_end[:action_idx] + [merged_span] + span_start_end[action_idx + 2:]\n\n reduce_span_in_all_span = reduce_span_in_all_span_batch[in_batch_idx]\n reduce_span = reduce_span_in_all_span[action_idx] + reduce_span_in_all_span[action_idx + 1]\n # update original reduce_span_in_all_span_batch\n reduce_span_in_all_span_batch[in_batch_idx] = \\\n reduce_span_in_all_span[:action_idx] + [reduce_span] + reduce_span_in_all_span[action_idx + 2:]\n\n # If a span contains 2 reduced spans, this span will be reduced\n if len(reduce_span) >= 2:\n assert len(reduce_span) == 2\n reduce_list.append(in_batch_idx)\n reduce_span_in_all_span_batch[in_batch_idx][action_idx] = [merged_span]\n span2repre_batch[in_batch_idx][str(merged_span)] = \\\n hidden[in_batch_idx:in_batch_idx + 1, action_idx]\n\n if var_actions[in_batch_idx, 0] == 1:\n h_x, c_x = h_x1, c_x1\n span2variable_batch[in_batch_idx][str(merged_span)] = 'entity'\n else:\n assert var_actions[in_batch_idx, 1] == 1\n h_x, c_x = h_x2, c_x2\n span2variable_batch[in_batch_idx][str(merged_span)] = 'predicate'\n # pdb.set_trace()\n hidden, cell = self.abst_embed(hidden, cell, h_x, c_x, in_batch_idx, action_idx)\n\n parent_child_span = [merged_span, reduce_span]\n parent_child_spans_batch[in_batch_idx].append(parent_child_span)\n\n reduce_mask = [1 if i in reduce_list else 0 for i in range(batch_size)]\n reduce_mask = torch.tensor(reduce_mask, dtype=torch.float32)\n if USE_CUDA:\n reduce_mask = reduce_mask.cuda()\n\n normalized_entropy.append(cat_distr.normalized_entropy)\n log_prob.append(-cat_distr.log_prob(actions))\n\n var_normalized_entropy.append(var_cat_distr.normalized_entropy * reduce_mask)\n var_log_prob.append(-var_cat_distr.log_prob(var_actions) * reduce_mask)\n\n log_prob = sum(log_prob) + sum(var_log_prob)\n\n normalized_entropy = (sum(normalized_entropy) + sum(var_normalized_entropy)) / (\n len(normalized_entropy) + len(var_normalized_entropy))\n\n assert relaxed is False\n\n tree_rl_infos = [normalized_entropy, log_prob, parent_child_spans_batch, span2repre_batch]\n\n return tree_rl_infos, span2variable_batch\n\n def abst_embed(self, hidden, cell, h_x, c_x, in_batch_idx, action_idx):\n # replace the abstrat with certain variable (x1 or x2)\n h_p_new = torch.cat([hidden[in_batch_idx:in_batch_idx + 1, :action_idx],\n h_x,\n hidden[in_batch_idx:in_batch_idx + 1, action_idx + 1:]], dim=1)\n c_p_new = torch.cat([cell[in_batch_idx:in_batch_idx + 1, :action_idx],\n c_x,\n cell[in_batch_idx:in_batch_idx + 1, action_idx + 1:]], dim=1)\n h_batch_new = torch.cat([hidden[:in_batch_idx],\n h_p_new,\n hidden[in_batch_idx + 1:]], dim=0)\n c_batch_new = torch.cat([cell[:in_batch_idx],\n c_p_new,\n cell[in_batch_idx + 1:]], dim=0)\n\n return h_batch_new, c_batch_new\n\n def _var_make_step(self, span_repr, relaxed, tau_weights, straight_through, gumbel_noise, ev_sr_actions):\n # make step on choice of x1 or x2\n var_score = self.var_linear(span_repr)\n var_mask = torch.ones_like(var_score)\n\n var_cat_distr = Categorical(var_score, var_mask)\n if ev_sr_actions is None:\n var_actions, gumbel_noise = self._sample_action(var_cat_distr, var_mask, relaxed, tau_weights,\n straight_through,\n gumbel_noise)\n else:\n var_actions = ev_sr_actions\n\n return var_cat_distr, gumbel_noise, var_actions\n\n def _make_step(self, hidden, cell, mask_ori, relaxed, tau_weights, straight_through, gumbel_noise, ev_actions):\n # make step on generating binary tree\n mask = copy.deepcopy(mask_ori)\n\n h_l, c_l = hidden[:, :-1], cell[:, :-1]\n h_r, c_r = hidden[:, 1:], cell[:, 1:]\n h_p, c_p = self.tree_lstm_cell(h_l, c_l, h_r, c_r)\n\n q_mul_vector = h_p\n\n score = torch.matmul(q_mul_vector, self.q) # (N x L x d, d) -> (N x L)\n cat_distr = Categorical(score, mask)\n if ev_actions is None:\n actions, gumbel_noise = self._sample_action(cat_distr, mask, relaxed, tau_weights, straight_through,\n gumbel_noise)\n else:\n\n actions = ev_actions\n # ==== incorporate sampled action into the agent's representation of the environment state ====\n h_p, c_p = BinaryTreeBasedModule._merge(actions, h_l, c_l, h_r, c_r, h_p, c_p, mask)\n\n return cat_distr, gumbel_noise, actions, h_p, c_p\n\n def _make_step_tree(self, hidden, cell):\n # ==== calculate the prob distribution over the merge actions and sample one ====\n\n h_l, c_l = hidden[:, :-1], cell[:, :-1]\n h_r, c_r = hidden[:, 1:], cell[:, 1:]\n h_p, c_p = self.tree_lstm_cell(h_l, c_l, h_r, c_r)\n\n return h_p, c_p\n\n def _sample_action(self, cat_distr, mask, relaxed, tau_weights, straight_through, gumbel_noise):\n if self.training:\n if relaxed:\n N = mask.sum(dim=-1, keepdim=True)\n tau = tau_weights[0] + tau_weights[1].exp() * torch.log(N + 1) + tau_weights[2].exp() * N\n actions, gumbel_noise = cat_distr.rsample(temperature=tau, gumbel_noise=gumbel_noise)\n if straight_through:\n actions_hard = torch.zeros_like(actions)\n actions_hard.scatter_(-1, actions.argmax(dim=-1, keepdim=True), 1.0)\n actions = (actions_hard - actions).detach() + actions\n actions = clamp_grad(actions, -0.5, 0.5)\n else:\n actions, gumbel_noise = cat_distr.rsample(gumbel_noise=gumbel_noise)\n else:\n actions = torch.zeros_like(cat_distr.probs)\n actions.scatter_(-1, torch.argmax(cat_distr.probs, dim=-1, keepdim=True), 1.0)\n gumbel_noise = None\n return actions, gumbel_noise\n\n\nclass Solver(nn.Module):\n # To compose bottom abstractions with rules\n def __init__(self, hidden_dim, output_lang,\n entity_list=[], caus_predicate_list=[], unac_predicate_list=[]):\n super().__init__()\n\n # 0: in\n # 1: on\n # 2: beside\n # 3: recipient theme (E E)\n # 4: theme recipient (E to E)\n # 5: theme agent (E by E)\n # 6: recipient agent (to E by E)\n self.semantic_E_E = nn.Linear(in_features=hidden_dim, out_features=7)\n\n # 0: agent\n # 1: theme\n # 2: recipient\n self.semantic_P_E = nn.Linear(in_features=hidden_dim, out_features=3)\n\n # 0: ccomp\n # 1: xcomp\n self.semantic_P_P = nn.Linear(in_features=hidden_dim, out_features=2)\n\n self.hidden_dim = hidden_dim\n self.output_lang = output_lang\n\n self.entity_list = entity_list\n self.caus_predicate_list = caus_predicate_list\n self.unac_predicate_list = unac_predicate_list\n self.predicate_list = caus_predicate_list + unac_predicate_list\n\n def forward(self, pair, span2output_token, parent_child_spans, span2repre,\n relaxed=False, tau_weights=None, straight_through=False, noise=None,\n eval_actions=None, eval_sr_actions=None, eval_swr_actions=None, debug_info=None):\n\n # TODO: maybe have bugs when reduce_span is empty\n # pdb.set_trace()\n span2semantic = self.init_semantic_class(span2output_token)\n # pdb.set_trace()\n\n semantic_normalized_entropy = []\n semantic_log_prob = []\n\n noise_i = None\n eval_swr_actions_i = None\n\n for parent_child_span in parent_child_spans:\n parent_span = parent_child_span[0]\n child0_span = parent_child_span[1][0]\n child1_span = parent_child_span[1][1]\n assert child0_span[1] < child1_span[0]\n child0_semantic = span2semantic[str(child0_span)]\n child1_semantic = span2semantic[str(child1_span)]\n # pdb.set_trace()\n cat_distr, _, actions_i, parent_semantic = self.semantic_merge(child0_semantic, child1_semantic,\n span2repre[str(parent_span)],\n relaxed, tau_weights,\n straight_through, noise_i,\n eval_swr_actions_i)\n span2semantic[str(parent_span)] = parent_semantic\n\n if cat_distr is not None:\n semantic_normalized_entropy.append(cat_distr.normalized_entropy)\n semantic_log_prob.append(-cat_distr.log_prob(actions_i))\n\n # pdb.set_trace()\n\n # pdb.set_trace()\n\n normalized_entropy = sum(semantic_normalized_entropy) / len(semantic_normalized_entropy)\n semantic_log_prob = sum(semantic_log_prob)\n\n assert relaxed is False\n\n final_semantic = copy.deepcopy(span2semantic[str(parent_span)])\n for action_idx in range(len(final_semantic.action_chain)):\n action_info = final_semantic.action_chain[action_idx]\n if action_info[1] is not None and action_info[2] is None and action_info[3] is None:\n agent_class = copy.deepcopy(action_info[1])\n assert agent_class.entity_chain[0][1] == 'agent'\n action = action_info[4]\n\n # in gen\n # A donut on the bed rolled .\n # * bed ( x _ 4 ) ; donut ( x _ 1 ) AND donut . nmod . on ( x _ 1 , x _ 4 ) AND roll . theme ( x _ 5 , x _ 1 )\n # The girl beside a table rolled .\n # * girl ( x _ 1 ) ; girl . nmod . beside ( x _ 1 , x _ 4 ) AND table ( x _ 4 ) AND roll . agent ( x _ 5 , x _ 1 )\n\n # in train\n # Victoria hoped that a girl rolled .\n # hope . agent ( x _ 1 , Victoria ) AND hope . ccomp ( x _ 1 , x _ 5 ) AND girl ( x _ 4 ) AND roll . theme ( x _ 5 , x _ 4 )\n\n if action in self.unac_predicate_list and len(agent_class.entity_chain) == 1:\n # if action in self.unac_predicate_list:\n agent_class.entity_chain[0][1] = 'theme'\n final_semantic.action_chain[action_idx][1] = None\n final_semantic.action_chain[action_idx][2] = agent_class\n final_semantic.has_agent = False\n final_semantic.has_theme = True\n\n span2semantic[str(parent_span)] = final_semantic\n\n semantic_rl_infos = [normalized_entropy, semantic_log_prob, span2semantic, parent_span]\n\n return semantic_rl_infos\n\n def init_semantic_class(self, span2output_token):\n span2semantic = {}\n for span in span2output_token:\n span_position = span[0]\n output_token = span[1]\n\n assert output_token in self.entity_list + self.predicate_list\n\n if output_token in self.entity_list:\n span_semantic = E(output_token)\n else:\n span_semantic = P(output_token)\n\n span2semantic[str(span_position)] = span_semantic\n\n return span2semantic\n\n def semantic_merge(self, child0_semantic, child1_semantic, parent_repre,\n relaxed, tau_weights, straight_through, gumbel_noise, ev_swr_actions):\n if isinstance(child0_semantic, E) and isinstance(child1_semantic, E):\n semantic_score = self.semantic_E_E(parent_repre)\n semantic_mask = torch.ones_like(semantic_score)\n\n cat_distr = Categorical(semantic_score, semantic_mask)\n actions, gumbel_noise = self._sample_action(cat_distr, semantic_mask, relaxed, tau_weights,\n straight_through,\n gumbel_noise)\n if actions[0, 0] == 1:\n parent_semantic = copy.deepcopy(child0_semantic)\n parent_semantic.add_E_in(child1_semantic)\n elif actions[0, 1] == 1:\n parent_semantic = copy.deepcopy(child0_semantic)\n parent_semantic.add_E_on(child1_semantic)\n elif actions[0, 2] == 1:\n parent_semantic = copy.deepcopy(child0_semantic)\n parent_semantic.add_E_beside(child1_semantic)\n elif actions[0, 3] == 1:\n parent_semantic = copy.deepcopy(child0_semantic)\n parent_semantic.add_E_recipient_theme(child1_semantic)\n elif actions[0, 4] == 1:\n parent_semantic = copy.deepcopy(child0_semantic)\n parent_semantic.add_E_theme_recipient(child1_semantic)\n elif actions[0, 5] == 1:\n parent_semantic = copy.deepcopy(child0_semantic)\n parent_semantic.add_E_theme_agent(child1_semantic)\n else:\n assert actions[0, 6] == 1\n parent_semantic = copy.deepcopy(child0_semantic)\n parent_semantic.add_E_recipient_agent(child1_semantic)\n\n elif isinstance(child0_semantic, P) and isinstance(child1_semantic, P):\n semantic_score = self.semantic_P_P(parent_repre)\n semantic_mask = torch.ones_like(semantic_score)\n\n cat_distr = Categorical(semantic_score, semantic_mask)\n actions, gumbel_noise = self._sample_action(cat_distr, semantic_mask, relaxed, tau_weights,\n straight_through,\n gumbel_noise)\n\n if actions[0, 0] == 1:\n parent_semantic = copy.deepcopy(child0_semantic)\n parent_semantic.add_P_ccomp(child1_semantic)\n else:\n assert actions[0, 1] == 1\n parent_semantic = copy.deepcopy(child0_semantic)\n parent_semantic.add_P_xcomp(child1_semantic)\n\n else:\n semantic_score = self.semantic_P_E(parent_repre)\n semantic_mask = torch.ones_like(semantic_score)\n\n if isinstance(child0_semantic, P) and isinstance(child1_semantic, E):\n parent_semantic = copy.deepcopy(child0_semantic)\n E_semantic = copy.deepcopy(child1_semantic)\n else:\n assert isinstance(child1_semantic, P) and isinstance(child0_semantic, E)\n parent_semantic = copy.deepcopy(child1_semantic)\n E_semantic = copy.deepcopy(child0_semantic)\n\n if E_semantic.entity_para is not None:\n if E_semantic.entity_chain[0][1] == 'recipient' and \\\n E_semantic.entity_para.entity_chain[0][1] == 'theme':\n parent_semantic.add_E_recipient_theme(E_semantic)\n parent_semantic.has_recipient = True\n parent_semantic.has_theme = True\n elif E_semantic.entity_chain[0][1] == 'theme' and \\\n E_semantic.entity_para.entity_chain[0][1] == 'recipient':\n parent_semantic.add_E_theme_recipient(E_semantic)\n parent_semantic.has_theme = True\n parent_semantic.has_recipient = True\n elif E_semantic.entity_chain[0][1] == 'theme' and \\\n E_semantic.entity_para.entity_chain[0][1] == 'agent':\n parent_semantic.add_E_theme_agent(E_semantic)\n parent_semantic.has_theme = True\n parent_semantic.has_agent = True\n else:\n assert E_semantic.entity_chain[0][1] == 'recipient' and \\\n E_semantic.entity_para.entity_chain[0][1] == 'agent'\n parent_semantic.add_E_recipient_agent(E_semantic)\n parent_semantic.has_recipient = True\n parent_semantic.has_agent = True\n\n cat_distr, actions, gumbel_noise = None, None, None\n\n else:\n if not parent_semantic.is_full:\n assert parent_semantic.has_agent is False or \\\n parent_semantic.has_theme is False or \\\n parent_semantic.has_recipient is False\n if parent_semantic.has_agent is True:\n semantic_mask[0, 0] = 0\n if parent_semantic.has_theme is True:\n semantic_mask[0, 1] = 0\n if parent_semantic.has_recipient is True:\n semantic_mask[0, 2] = 0\n\n cat_distr = Categorical(semantic_score, semantic_mask)\n actions, gumbel_noise = self._sample_action(cat_distr, semantic_mask, relaxed, tau_weights,\n straight_through,\n gumbel_noise)\n if actions[0, 0] == 1:\n parent_semantic.add_E_agent(E_semantic)\n parent_semantic.has_agent = True\n elif actions[0, 1] == 1:\n parent_semantic.add_E_theme(E_semantic)\n parent_semantic.has_theme = True\n else:\n assert actions[0, 2] == 1\n parent_semantic.add_E_recipient(E_semantic)\n parent_semantic.has_recipient = True\n\n if parent_semantic.has_agent is True and \\\n parent_semantic.has_theme is True and \\\n parent_semantic.has_recipient is True:\n parent_semantic.is_full = True\n\n return cat_distr, gumbel_noise, actions, parent_semantic\n\n def _sample_action(self, cat_distr, mask, relaxed, tau_weights, straight_through, gumbel_noise):\n if self.training:\n if relaxed:\n N = mask.sum(dim=-1, keepdim=True)\n tau = tau_weights[0] + tau_weights[1].exp() * torch.log(N + 1) + tau_weights[2].exp() * N\n actions, gumbel_noise = cat_distr.rsample(temperature=tau, gumbel_noise=gumbel_noise)\n if straight_through:\n actions_hard = torch.zeros_like(actions)\n actions_hard.scatter_(-1, actions.argmax(dim=-1, keepdim=True), 1.0)\n actions = (actions_hard - actions).detach() + actions\n actions = clamp_grad(actions, -0.5, 0.5)\n else:\n actions, gumbel_noise = cat_distr.rsample(gumbel_noise=gumbel_noise)\n else:\n actions = torch.zeros_like(cat_distr.probs)\n actions.scatter_(-1, torch.argmax(cat_distr.probs, dim=-1, keepdim=True), 1.0)\n gumbel_noise = None\n return actions, gumbel_noise\n\n\nclass HRLModel(nn.Module):\n def __init__(self, vocab_size, word_dim, hidden_dim, label_dim,\n composer_trans_hidden=None,\n var_normalization=False,\n input_lang=None, output_lang=None,\n alignments_idx={}, entity_list=[], caus_predicate_list=[], unac_predicate_list=[]):\n super().__init__()\n self.input_lang = input_lang\n self.output_lang = output_lang\n self.label_dim = label_dim\n self.alignments_idx = alignments_idx\n self.entity_list = entity_list\n self.caus_predicate_list = caus_predicate_list\n self.unac_predicate_list = unac_predicate_list\n self.abstractor = BottomAbstrator(alignments_idx)\n self.classifier = BottomClassifier(output_lang, alignments_idx)\n self.composer = BottomUpTreeComposer(word_dim, hidden_dim, vocab_size, \"no_transformation\",\n composer_trans_hidden, input_lang, output_lang,\n alignments_idx=alignments_idx,\n entity_list=entity_list,\n caus_predicate_list=caus_predicate_list,\n unac_predicate_list=unac_predicate_list)\n self.solver = Solver(hidden_dim, output_lang,\n entity_list=entity_list,\n caus_predicate_list=caus_predicate_list,\n unac_predicate_list=unac_predicate_list)\n self.var_norm_params = {\"var_normalization\": var_normalization, \"var\": 1.0, \"alpha\": 0.9}\n self.criterion = nn.CrossEntropyLoss(reduction='none')\n # self.reset_parameters()\n self.is_test = False\n\n self.case = None\n\n # TODO: change the paremeters\n def get_high_parameters(self):\n return list(chain(self.composer.parameters()))\n\n def get_low_parameters(self):\n return list(chain(self.solver.parameters()))\n\n def case_study(self, reduced_output, token_list):\n token_list = token_list[0].split()\n sentence_len = len(token_list)\n sentences_num = len(reduced_output)\n res = []\n for i in range(sentences_num):\n sentence = reduced_output[i]\n dic = {}\n min_num, max_num = sentence_len + 1, 0\n for x in sentence:\n parent = x[0]\n children = x[1]\n dic[tuple(parent)] = children\n max_num = max(max_num, parent[1])\n min_num = min(min_num, parent[0])\n\n def dfs(parent):\n if not parent in dic:\n return \"(\" + \" \".join([token_list[i] for i in range(parent[0], parent[1] + 1)]) + \")\"\n children = dic[parent]\n child0 = dfs(tuple(children[0]))\n child1 = dfs(tuple(children[1]))\n\n def fill_gap(begin, end):\n string = \"\"\n for i in range(begin, end):\n string += token_list[i] + \" \"\n return string[:-1]\n\n case_string = \"(\" + fill_gap(parent[0], children[0][0]) + child0 \\\n + fill_gap(children[0][1] + 1, children[1][0]) + child1 \\\n + fill_gap(children[1][1] + 1, parent[1] + 1) + \")\"\n return case_string\n\n res.append(dfs((min_num, max_num)))\n return res\n\n def forward(self, pair, x, sample_num, is_test=False, epoch=None, debug_info=None):\n self.is_test = is_test\n\n batch_forward_info, pred_chain, label_chain = self._forward(\n pair, x, sample_num, epoch, is_test, debug_info=debug_info)\n return batch_forward_info, pred_chain, label_chain\n\n def _forward(self, pair, x, sample_num, epoch, is_test, debug_info):\n assert x.size(1) > 1\n\n bottom_span = self.abstractor(x)\n\n span2output_token = self.classifier(x, bottom_span)\n\n bottom_span_batch = [bottom_span for _ in range(sample_num)]\n span2output_token_batch = [span2output_token for _ in range(sample_num)]\n\n tree_rl_info, span2variable_batch = self.composer(pair, x, bottom_span_batch, span2output_token_batch)\n tree_normalized_entropy, tree_log_prob, parent_child_spans_batch, span2repre_batch = tree_rl_info\n\n batch_forward_info = []\n\n for in_batch_idx in range(sample_num):\n parent_child_spans = parent_child_spans_batch[in_batch_idx]\n span2repre = span2repre_batch[in_batch_idx]\n span2output_token = span2output_token_batch[in_batch_idx]\n\n semantic_rl_infos = self.solver(pair, span2output_token, parent_child_spans, span2repre)\n\n semantic_normalized_entropy, semantic_log_prob, span2semantic, end_span = semantic_rl_infos\n\n pred_chain = self.translate(span2semantic[str(end_span)])\n # pdb.set_trace()\n label_chain = self.process_output(pair[1])\n reward = self.get_reward(pred_chain, label_chain)\n\n # pdb.set_trace()\n\n normalized_entropy = tree_normalized_entropy[in_batch_idx] + \\\n semantic_normalized_entropy\n\n log_prob = tree_log_prob[in_batch_idx] + \\\n semantic_log_prob\n\n batch_forward_info.append([normalized_entropy, log_prob, reward])\n\n # pdb.set_trace()\n\n return batch_forward_info, pred_chain, label_chain\n\n def get_reward(self, pred_chain, label_chain):\n pred_len = len(pred_chain)\n label_len = len(label_chain)\n max_com_len = 0\n for pred_idx in range(pred_len):\n for label_idx in range(label_len):\n com_len = 0\n if pred_chain[pred_idx] != label_chain[label_idx]:\n continue\n else:\n com_len += 1\n right_hand_length = min(pred_len - pred_idx - 1, label_len - label_idx - 1)\n for right_hand_idx in range(right_hand_length):\n if pred_chain[pred_idx + right_hand_idx + 1] == label_chain[label_idx + right_hand_idx + 1]:\n com_len += 1\n continue\n else:\n break\n if com_len > max_com_len:\n max_com_len = com_len\n\n reward = max_com_len / (pred_len + label_len - max_com_len)\n\n assert reward <= 1.\n if reward == 1.:\n assert pred_chain == label_chain\n\n return reward\n\n def get_entity_chain(self, semantic):\n if semantic is None:\n return ['None']\n\n assert isinstance(semantic, E)\n flat_chain = []\n # [in_word / on_word / beside_word, agent_word / theme_word / recipient_word, entity]\n for entity_idx, entity_info in enumerate(semantic.entity_chain):\n if entity_idx == 0:\n flat_entity_chain = [entity_info[2]]\n else:\n assert entity_info[0] is not None\n flat_entity_chain = [entity_info[0], entity_info[2]]\n flat_chain = flat_chain + flat_entity_chain\n\n return flat_chain\n\n # Translate a nest class into a list\n def translate(self, semantic):\n assert isinstance(semantic, P)\n flat_chain = []\n\n for action_idx, action_info in enumerate(semantic.action_chain):\n # [ccomp_word / xcomp_word, agent_entity_class, theme_entity_class, recipient_entity_class, action_word]\n if action_idx == 0:\n flat_action_chain = [action_info[4]]\n else:\n assert action_info[0] is not None\n flat_action_chain = [action_info[0], action_info[4]]\n\n if action_info[0] == 'xcomp':\n agent_chain = reserve_agent_chain\n else:\n agent_chain = self.get_entity_chain(action_info[1])\n theme_chain = self.get_entity_chain(action_info[2])\n recipient_chain = self.get_entity_chain(action_info[3])\n flat_action_chain = flat_action_chain + agent_chain + theme_chain + recipient_chain\n reserve_agent_chain = copy.deepcopy(agent_chain)\n\n flat_chain = flat_chain + flat_action_chain\n\n return flat_chain\n\n def process_output(self, output):\n output_process = output.replace(\" and \", \" AND \")\n output_process = output_process.replace(\" ccomp \", \" CCOMP \")\n output_process = output_process.replace(\" xcomp \", \" XCOMP \")\n output_process = output_process.replace(\" nmod \", \" NMOD \")\n output_process = output_process.replace(\" agent \", \" AGENT \")\n output_process = output_process.replace(\" theme \", \" THEME \")\n output_process = output_process.replace(\" recipient \", \" RECIPIENT \")\n output_process = output_process.replace(\" x \", \" X \")\n output_process = output_process.replace(\" \", \"\")\n output_process = output_process.replace(\"*\", \"\")\n output_process = re.split(\";|AND\", output_process)\n\n object_stack = {}\n output_process_no_obj = copy.deepcopy(output_process)\n for function in output_process:\n if '.' not in function: # entity\n function_para = re.split(\"\\(|\\)\", function)[:-1]\n assert len(function_para) == 2\n object, object_index = function_para\n assert object_index not in object_stack\n object_stack[object_index] = object\n output_process_no_obj.remove(function)\n else:\n continue\n\n output_process_no_obj_no_pr = copy.deepcopy(output_process_no_obj)\n output_process_no_obj.reverse()\n for function in output_process_no_obj:\n if 'NMOD' in function: # pr\n function_para = re.split(\"\\(|\\)|\\.|,\", function)[:-1]\n assert len(function_para) == 5\n pr_word = function_para[2]\n pr_subject_index = function_para[3]\n pr_subject = object_stack[pr_subject_index]\n # assert for 2 things:\n # first, re-ensure subject\n # second, ensure subject in object_stack has no other pr\n # the second means that the composition process is from right to left\n # (implemented by output_process_no_obj.reverse())\n # this is to ensure the left subject has all corresponding objects\n assert pr_subject == function_para[0]\n pr_object_index = function_para[4]\n # ensure pr_object_index is an index but not like Emma\n assert 'X' in pr_object_index\n # this can also ensure the left subject has all corresponding objects\n # (as the object is popped, it cannot occur as subject again)\n pr_object = object_stack.pop(pr_object_index)\n new_subject = pr_subject + \" \" + pr_word + \" \" + pr_object\n object_stack[pr_subject_index] = new_subject\n output_process_no_obj_no_pr.remove(function)\n else:\n continue\n\n output_process_only_comp = copy.deepcopy(output_process_no_obj_no_pr)\n predicate_stack = {}\n predicate_object_stack = {}\n for function in output_process_no_obj_no_pr:\n if 'COMP' not in function:\n function_para = re.split(\"\\(|\\)|\\.|,\", function)[:-1]\n assert len(function_para) == 4\n predicate, object_type, predicate_index, object_index = function_para\n if 'X' not in object_index:\n object = object_index\n else:\n object = object_stack[object_index]\n if predicate_index not in predicate_stack:\n predicate_stack[predicate_index] = predicate\n predicate_object_stack[predicate_index] = {\"AGENT\": \"None\",\n \"THEME\": \"None\",\n \"RECIPIENT\": \"None\",\n }\n predicate_object_stack[predicate_index][object_type] = object\n output_process_only_comp.remove(function)\n else:\n continue\n\n for predicate_key in predicate_object_stack:\n if predicate_object_stack[predicate_key][\"RECIPIENT\"] != \"None\" \\\n and predicate_object_stack[predicate_key][\"THEME\"] == \"None\":\n pdb.set_trace()\n\n final_chain = []\n if output_process_only_comp:\n output_process_only_comp.reverse()\n for function in output_process_only_comp:\n function_para = re.split(\"\\(|\\)|\\.|,\", function)[:-1]\n assert len(function_para) == 4\n compose_type = function_para[1]\n assert compose_type in [\"CCOMP\", \"XCOMP\"]\n subject_index = function_para[2]\n object_index = function_para[3]\n subject = predicate_stack[subject_index]\n subject_contain = predicate_object_stack[subject_index]\n try:\n assert subject == function_para[0]\n except:\n pdb.set_trace()\n # ensure object will not occur as subject\n object = predicate_stack.pop(object_index)\n object_contain = predicate_object_stack.pop(object_index)\n if compose_type == 'XCOMP':\n assert subject_contain[\"AGENT\"] == object_contain[\"AGENT\"]\n if final_chain == []:\n final_chain = [[subject, subject_contain], compose_type, [object, object_contain]]\n else:\n final_chain = [[subject, subject_contain], compose_type] + final_chain\n\n else:\n assert len(predicate_stack) == 1\n for predicate_index in predicate_stack:\n subject = predicate_stack[predicate_index]\n subject_contain = predicate_object_stack[predicate_index]\n final_chain = [[subject, subject_contain]]\n\n flat_chain = []\n\n for pred_info in final_chain:\n if isinstance(pred_info, list):\n action = pred_info[0]\n flat_chain.append(action)\n\n action_info = pred_info[1]\n agent = action_info['AGENT']\n agent = agent.split()\n flat_chain = flat_chain + agent\n\n theme = action_info['THEME']\n theme = theme.split()\n flat_chain = flat_chain + theme\n\n recipient = action_info['RECIPIENT']\n recipient = recipient.split()\n flat_chain = flat_chain + recipient\n\n else:\n assert pred_info in [\"CCOMP\", \"XCOMP\"]\n flat_chain.append(pred_info.lower())\n\n return flat_chain\n","repo_name":"thousfeet/LEAR","sub_path":"COGS_experiment/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":48129,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"77"}
+{"seq_id":"28516934137","text":"import pickle\n\nimport pandas as pd\nfrom catboost import CatBoostClassifier\nfrom flask import Flask, request, render_template\n\napp = Flask(__name__)\nwith open('prep.pkl', \"rb\") as f:\n prep = pickle.load(f)\n\ncat_model = CatBoostClassifier()\ncat_model.load_model('cat_model.bin')\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/predict', methods=['POST', 'GET'])\ndef predict():\n data = []\n columns = ['internet_service', 'online_security', 'online_backup', 'device_protection', 'tech_support',\n 'streaming_tv', 'streaming_movies', 'multiple_lines', 'gender', 'senior_citizen', 'partner',\n 'dependents', 'begin_date', 'end_date', 'type', 'paperless_billing', 'payment_method',\n 'monthly_charges', 'total_charges']\n\n for i in range(1, 20):\n data.append(request.form[str(i)])\n try:\n data = pd.DataFrame([data], columns=columns)\n data[['monthly_charges', 'total_charges']] = data[['monthly_charges', 'total_charges']].astype('float')\n data = prep.transform(data)\n\n result = round(cat_model.predict_proba(data)[0, 1], 3)\n except:\n result = 'неверный ввод даты'\n return render_template('predict.html', result=result)\n\n\n\n\n","repo_name":"estochka/yandex","sub_path":"final/Flask/ind.py","file_name":"ind.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"73578186167","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('login/', views.login_page, name='login_page'),\n path('signup/', views.create_user_page, name='signup_page'),\n path('home/', views.home_page, name='home_page'),\n path('module//', views.module_page, name='module_page'),\n path('logout/', views.logout_page, name='logout'),\n]","repo_name":"jweir136/Enactus-Colgate-Project","sub_path":"Colgate/occ/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"1177993387","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 13 23:15:36 2018\n\n@author: apatti\n\"\"\"\nimport hashlib\nfrom time import time\nimport json\n\nclass Lahar:\n def __init__(self):\n self.chain=[]\n self.transactions = []\n #initial block (also called as genesis block)\n self.new_lahar(proof=100,prev_hash=1)\n \n #similar to block\n def new_lahar(self,proof,prev_hash=None):\n lahar = {'index':len(self.chain)+1,\n 'timestamp':time,\n 'transactions':self.transactions,\n 'proof':proof,\n 'previous_hash':prev_hash}\n self.transactions.clear()\n self.chain.append(lahar)\n return lahar\n \n def new_transaction(self,sender,receiver,amount):\n self.transactions.append({'sender':sender,\n 'receiver':receiver,\n 'amount':amount})\n return\n \n def last_lahar(self):\n return self.chain[-1]\n \n @staticmethod\n def Hash(lahar):\n return hashlib.sha256(json.dumps(lahar,sort_keys=True).encode()).digest()\n \n \n def proof_of_work(self):\n '''\n '' find a nonce such that hash(lastBlock.hash|transaction|nonce) has 4 leading zeroes\n '' in real implementation they use Merkle Tree for hashing transactions\n '' in our implementation, we shall hash all transactions together\n '''\n proof = 0\n while True:\n prev_hash=self.last_lahar['previous_hash']\n \n if Lahar.validate_pow(prev_hash,self.transactions,proof) == True:\n break\n \n proof += 1\n \n return proof\n \n @staticmethod\n def validate_pow(prev_hash,current_transactions,proof):\n tran_hash=''\n for transaction in current_transactions:\n tran_hash += hashlib.sha256(json.dumps(transaction,sort_keys=True).encode()).digest()\n \n tran_hash=hashlib.sha256(tran_hash)\n hash = hashlib.sha256(prev_hash+tran_hash+str(proof)).digest()\n return hash[:4]=='0000'","repo_name":"apatti/dukescoin","sub_path":"blockchain/lahar.py","file_name":"lahar.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"28073207924","text":"__author__ = 'atrament'\n__all__ = ['is_iso_date', 'mkdatetime', \"is_iso_time\", \"mktimedelta\"]\n\nimport re as _re\nimport datetime as _datetime\nfrom config import DATETIME_PATTERN as _DATETIME_PATTERN\n\n\ndef is_iso_date(d):\n \"\"\":returns True if d is a string representing an iso date or datetime, False otherwise\"\"\"\n if not isinstance(d, str): # can't regex on non-string elements\n return False\n return bool(_re.match(_DATETIME_PATTERN, d))\n\n\ndef is_iso_time(d, fetch=False):\n if not isinstance(d, str): # can't regex on non-string elements\n return False\n match = _re.findall(\"\\d{1,2}:\\d{2}(?::\\d{2})*(?:.\\d{1,6})*\", d)\n if fetch and bool(match):\n return match[0]\n return bool(match)\n\n\ndef mkdatetime(iso):\n \"\"\"makes a datetime object from given string\n :returns datetime.datetime object\"\"\"\n if not isinstance(iso, str):\n raise TypeError(\"Argument for mkdatetime must be a string.\")\n if not is_iso_date(iso):\n raise ValueError(\"Argument for mkdatetime must be iso datetime format\")\n return _datetime.datetime(*map(int, _re.findall(\"\\d+\", iso)))\n\n\ndef mktimedelta(iso):\n if not isinstance(iso, str):\n raise TypeError(\"Argument for mktimedelta must be a string.\")\n if not is_iso_time(iso):\n raise ValueError(\"Argument for mktimedelta must be iso datetime or time format\")\n time = is_iso_time(iso, fetch=True)\n time = list(map(int, _re.findall(\"\\d+\", time)))\n args = dict(zip(\"hours minutes seconds microseconds\".split(),\n time))\n return _datetime.timedelta(**args)\n","repo_name":"AlbericC/PyledTasks","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"11272573401","text":"from django.urls import re_path\nfrom users.views import UserInfoView, UploadImageView, ChangePwdView\nfrom users.views import SendChangeEmailView, ChangeEmailView, MyCourseView\nfrom users.views import MyOrgCollectionView, MyTeacherCollectionView, MyCourseCollectionView, MyMessageView\n\nurlpatterns = [\n re_path(r'^center_info/$', UserInfoView.as_view(), name='center_info'),\n re_path(r'^my_course/$', MyCourseView.as_view(), name='my_course'),\n\n # 我的收藏\n re_path(r'^my_collection/orgs/$', MyOrgCollectionView.as_view(), name='collections_orgs'),\n re_path(r'^my_collection/teachers/$', MyTeacherCollectionView.as_view(), name='collections_teachers'),\n re_path(r'^my_collection/courses/$', MyCourseCollectionView.as_view(), name='collections_courses'),\n # 我的消息\n re_path(r'^my_message/$', MyMessageView.as_view(), name='my_message'),\n # 上传头像\n re_path(r'^image_upload/$', UploadImageView.as_view(), name='image_upload'),\n\n # 修改密码\n re_path(r'^change_pwd/$', ChangePwdView.as_view(), name='change_pwd'),\n\n # 发送修改邮箱验证码\n re_path(r'^send_email/$', SendChangeEmailView.as_view(), name='send_email'),\n # 修改邮箱验证码\n re_path(r'^change_email/$', ChangeEmailView.as_view(), name='change_email'),\n\n]\n","repo_name":"KevinPei777/Yun_Class","sub_path":"Munet1/apps/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"28396360315","text":"import re\nfrom collections import Counter \nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen\n\n\ndef getSyns(word):\n url=\"https://www.thesaurus.com/browse/\"+word+\"?s=t\"\n page = urlopen(url)\n html = page.read().decode(\"utf-8\")\n soup = BeautifulSoup(html, \"html.parser\")\n\n\n finalList=[]\n\n for a in soup.find_all('a', class_=\"css-1m14xsh eh475bn1\", href=True):\n finalList.append(a['href'])\n\n outList=[]\n for x in finalList:\n x=x[8:]\n outList.append(x)\n return outList\n\nwith open('commonWords.txt', 'r') as file:\n commonWords=file.read().replace('\\n', ' ')\n\n\n\n\ncommonWords=commonWords.lower()\ncommonList=commonWords.split(\" \")\n\ncheck=True\nextra=input(\"Any words you want added to the common words list? y/n \")\nif (extra==\"n\"):\n check=False\nwhile check==True:\n extraCommon=input(\"Enter Word (lowercase pls): \")\n commonList.append(extraCommon)\n checker=input(\"Any more? y/n \" )\n if(checker==\"n\"):\n check=False\n\n\n\n\n#print(commonList[1])\nfileName=input(\"enter name of txt file, with .txt included: \")\nwith open(fileName, 'r') as file:\n data = file.read().replace('\\n', ' ')\ndata=data.lower()\n # split() returns list of all the words in the string \nsplit_it = data.split()\n\nl3 = [x for x in split_it if x not in commonList]\n \n # Pass the split_it list to instance of Counter class. \nCounter = Counter(l3) \n \n # most_common() produces k frequently encountered \n # input values and their respective counts. \nval=int(input(\"How many words do you want Synonyms of? \"))\nmost_occur = Counter.most_common(val)\nx=0\n#print(getSyns(\"test\"))\nwhile x< val:\n w1=most_occur[x][0]\n print(most_occur[x])\n print(\"Synonyms: \")\n print(getSyns(w1))\n print(\"\")\n #+str(most_occur[x][1])+\"occurences\")\n \n x=x+1\n\n","repo_name":"rcrenny/essaySyns","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"20083582435","text":"\"\"\"Local executor\"\"\"\n\nimport asyncio\nimport logging\n\nlogger = logging.getLogger(__name__)\n\nclass LocalExecutor:\n def __init__(self):\n pass\n\n async def execute(self, cmd):\n proc = await asyncio.create_subprocess_shell(\n cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=None\n )\n\n stdout, _ = await proc.communicate()\n return (proc.returncode, stdout.decode('utf-8'))\n \n async def execute_no_output(self, cmd):\n proc = await asyncio.create_subprocess_shell(\n cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=None\n )\n\n await proc.wait()\n return proc.returncode","repo_name":"libreliu/presto-pipeline","sub_path":"pipeline-optim/LocalExecutor.py","file_name":"LocalExecutor.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"22518790897","text":"#!/usr/bin/env python\nfrom typing import List\n\nclass Solution:\n def singleNumber(self, nums: List[int]) -> List[int]:\n s = 0\n for num in nums:\n s = s ^ num\n mask = 1\n while s & mask == 0: # 寻找一个是1的位置\n mask = mask << 1\n g0, g1 = 0, 0\n for num in nums:\n if num & mask == 0:\n g0 = g0 ^ num\n else:\n g1 = g1 ^ num\n return [g0, g1]","repo_name":"ftakanashi/JobProjects","sub_path":"LeetCode/260.只出现一次的数字III/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"36771209828","text":"import Hardware\nimport time\nfrom firebase import firebase\n\nfirebase = firebase.FirebaseApplication('https://green-future-cc3e6-default-rtdb.firebaseio.com/', None)\n\n#RELAY = Hardware.Relay(18, False)\n#SECONDS_TO_WATER = 10\n\n#def water_plant(relay, seconds):\ndef water_plant(relay, percent):\n\n\tdata3 = []\n\tif percent > 25:\n\t\trelay.on()\n\telse:\n\t\trelay.off()\n\t\tplant_time = int(time.time())\n\t\tdata3.append(plant_time)\n\t\tdata3 = {\"plantTime\": plant_time}\n\t\tfirebase.patch('Set_Time', data3)\n\n#def main():\n# \twater_plant(RELAY, SECONDS_TO_WATER)\n#\tprint(\"\\nPlant was last watered at {}\".format(time_keeper.time_last_watered))\n\n#while True:\n#\ttime.sleep(SECONDS_TO_WATER)\n#\tmain()\n","repo_name":"tristan-hanna/GreenFuture","sub_path":"Raspberrypi Code/test_relay.py","file_name":"test_relay.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"53229118","text":"'''\nCommand: uninstall\n'''\n\nfrom thetool.helpers.log import LOGGER\nfrom thetool.helpers.database import get_database_tool\nfrom thetool.helpers.tool import remove_tool\n\ndef init_parser(subparsers):\n '''\n Initialize parser.\n '''\n\n parser = subparsers.add_parser('uninstall', help='uninstall tool')\n parser.add_argument('tool', help='tool name')\n parser.add_argument('-v', '--version', help='tool version to uninstall')\n\ndef run(args):\n '''\n Run command.\n '''\n\n LOGGER.info('uninstall tool %s', args.tool)\n tool_metadata = get_database_tool(args.tool)\n remove_tool(tool_metadata, version=args.version)\n","repo_name":"Lunik/thetool","sub_path":"src/thetool/commands/uninstall.py","file_name":"uninstall.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"7718276402","text":"\"\"\"A neuron to use in a neural network.\"\"\"\n\nimport numpy as np\n\nfrom functions import sigmoid, derivative\n\n\nclass Neuron:\n \"\"\"\n A simple neuron class.\n \"\"\"\n\n def __init__(self, inputs, weights, bias, is_output=False):\n self.delta = 0\n self.inputs = inputs\n self.weights = weights\n self.inproduct = None # Before sigmoid\n self.bias = bias\n self.is_output = is_output\n\n def activation(self):\n \"\"\"\n Returns the sigmoid of the inproduct of the weights and the inputs.\n \"\"\"\n self.inproduct = np.dot(self.inputs, self.weights) + self.bias\n return sigmoid(self.inproduct)\n\n def calculate_delta(self, change):\n \"\"\"\n Calculate and set the new neuron delta.\n \"\"\"\n self.delta = change * derivative(self.activation())\n","repo_name":"BasvRossem/2020_HU_AI","sub_path":"Programming_NNs/neuron.py","file_name":"neuron.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"36336328289","text":"import singer\nfrom singer import utils\nfrom singer.catalog import Catalog\nfrom tap_ga4.client import Client\nfrom tap_ga4.discover import discover\nfrom tap_ga4.sync import sync\n\nLOGGER = singer.get_logger()\n\nREQUIRED_CONFIG_KEYS = [\n \"start_date\",\n \"oauth_client_id\",\n \"oauth_client_secret\",\n \"refresh_token\",\n \"property_id\",\n \"account_id\",\n \"report_definitions\",\n]\n\n\ndef main_impl():\n args = utils.parse_args(REQUIRED_CONFIG_KEYS)\n config = args.config\n catalog = args.catalog or Catalog([])\n state = {}\n\n client = Client(config)\n\n if args.state:\n state.update(args.state)\n if args.discover:\n discover(client, config[\"report_definitions\"], config[\"property_id\"])\n LOGGER.info(\"Discovery complete\")\n elif args.catalog:\n sync(client, config, catalog, state)\n LOGGER.info(\"Sync Completed\")\n else:\n LOGGER.info(\"No properties were selected\")\n\n\ndef main():\n try:\n main_impl()\n except Exception as e:\n for line in str(e).splitlines():\n LOGGER.critical(line)\n raise e\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"singer-io/tap-ga4","sub_path":"tap_ga4/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"77"}
+{"seq_id":"31801494083","text":"#! /usr/bin/python\n\n\"\"\"\nUnit tests for pubsub module\n\"\"\"\n\nimport logging\nimport unittest\n\nimport pubsub\n\n\nclass SingleSubscriber(object):\n def __init__(self, test, bus, exp_topic, exp_data, create_topic=True):\n self.bus = bus\n self.test = test\n self.exp_topic = exp_topic\n self.exp_data = exp_data\n self.num_cb = 0 # Number of times the data callback was invoked\n\n if create_topic:\n self.bus.create_topic(exp_topic)\n\n def subscribe_good(self):\n self.bus.subscribe(self.exp_topic, self.sub_cb_good)\n\n def subscribe_not_callable(self):\n self.bus.subscribe(self.exp_topic, 'not a callback')\n\n def subscribe_incorrect_sig(self):\n self.bus.subscribe(self.exp_topic, self.sub_cb_invalid)\n\n def sub_cb_good(self, topic, data):\n # Verify expected topic name and data were given\n self.test.assertEquals(topic, self.exp_topic)\n self.test.assertEquals(data, self.exp_data)\n self.num_cb += 1\n\n def sub_cb_invalid(self, topic):\n self.test.fail('Invalid callback should never be called')\n\n\nclass MultiSubscriber(object):\n def __init__(self, test, bus, topic_data_dict):\n self.bus = bus\n self.test = test\n self.topic_data_dict = topic_data_dict\n self.num_cb = 0 # Number of times the data callback was invoked\n\n for topic in self.topic_data_dict:\n self.bus.create_topic(topic)\n\n def subscribe_topics(self):\n for topic in self.topic_data_dict:\n self.bus.subscribe(topic, self.common_sub_cb)\n\n def common_sub_cb(self, topic, data):\n # Verify the topic was one of the expected and the data matches what is\n # expected for that topic\n self.test.assertIn(topic, self.topic_data_dict)\n self.test.assertEquals(data, self.topic_data_dict[topic])\n self.num_cb += 1\n\nclass PubSubTest(unittest.TestCase):\n \"\"\"Unit tests for pubsub module\"\"\"\n def test_normal_pub_sub(self):\n \"\"\"Tests normal usage with topic created before sub\"\"\"\n # Create bus and foo topic\n bus = pubsub.PubSubBus()\n bus.create_topic('foo')\n\n # Create two initial subscribers not subscribed to any topics yet\n exp_data = {'payload': 'test'}\n foo_sub = SingleSubscriber(self, bus, 'foo', exp_data)\n bar_sub = SingleSubscriber(self, bus, 'bar', 5)\n self.assertEquals(foo_sub.num_cb, 0)\n self.assertEquals(bar_sub.num_cb, 0)\n\n # Publish on topic foo and ensure that no subscribers see it (since\n # nothing is subscribed yet)\n bus.publish('foo', exp_data)\n self.assertEquals(foo_sub.num_cb, 0)\n self.assertEquals(bar_sub.num_cb, 0)\n\n # Have both subscribers subscribe to topics foo and bar, respectively\n foo_sub.subscribe_good()\n bar_sub.subscribe_good()\n\n # Publish on topic foo again and ensure that only the foo subscriber\n # saw it\n bus.publish('foo', exp_data)\n self.assertEquals(foo_sub.num_cb, 1)\n self.assertEquals(bar_sub.num_cb, 0)\n\n # Create a new foo subscriber and immediately subscribe\n foo_sub2 = SingleSubscriber(self, bus, 'foo', exp_data)\n foo_sub2.subscribe_good()\n self.assertEquals(foo_sub2.num_cb, 0)\n\n # Publish on topic foo again and make sure that the first foo sub got\n # both messages (this and last) and the second subscriber only received\n # the message just published\n bus.publish('foo', exp_data)\n self.assertEquals(foo_sub.num_cb, 2)\n self.assertEquals(bar_sub.num_cb, 0)\n self.assertEquals(foo_sub2.num_cb, 1)\n\n # Publish on topic bar and make sure that only the bar subscriber\n # received it\n bus.publish('bar', 5)\n self.assertEquals(foo_sub.num_cb, 2)\n self.assertEquals(bar_sub.num_cb, 1)\n self.assertEquals(foo_sub2.num_cb, 1)\n\n def test_normal_sub_pub(self):\n \"\"\"Tests normal usage with subs created before topic\"\"\"\n # Create bus\n bus = pubsub.PubSubBus()\n\n # Create two initial subscribers not subscribed to any topics yet\n exp_data = {'payload': 'test'}\n foo_sub = SingleSubscriber(self, bus, 'foo', exp_data)\n bar_sub = SingleSubscriber(self, bus, 'bar', 5)\n self.assertEquals(foo_sub.num_cb, 0)\n self.assertEquals(bar_sub.num_cb, 0)\n\n foo_sub.subscribe_good()\n bar_sub.subscribe_good()\n\n bus.publish('foo', exp_data)\n self.assertEquals(foo_sub.num_cb, 1)\n self.assertEquals(bar_sub.num_cb, 0)\n\n def test_topic_check(self):\n \"\"\"\n Tests check that one cannot publish or subscribe before the topic is\n created\n \"\"\"\n # Create bus\n bus = pubsub.PubSubBus()\n\n # Try to publish with non-existent topic\n self.assertRaises(ValueError, bus.publish, 'foo', 'data')\n\n foo_sub = SingleSubscriber(\n self, bus, 'foo', 'data', create_topic=False)\n\n # Try to subscribe to non-existent topic\n self.assertRaises(ValueError, foo_sub.subscribe_good)\n\n # Create topic\n bus.create_topic('foo')\n\n # Everything should work normally now\n foo_sub.subscribe_good()\n bus.publish('foo', 'data')\n self.assertEquals(foo_sub.num_cb, 1)\n\n def test_invalid_callbacks(self):\n \"\"\"\n Tests errors cases when subscriber data callbacks are not callback or\n have incorrect signature\n \"\"\"\n # Create bus\n bus = pubsub.PubSubBus()\n\n # Try to subscribe with a non-callable callback\n foo_sub = SingleSubscriber(self, bus, 'foo', 'data')\n self.assertRaises(TypeError, foo_sub.sub_cb_invalid)\n\n # Create second sub to check bus will not be broken\n foo_sub2 = SingleSubscriber(self, bus, 'foo', 'data')\n foo_sub2.subscribe_good()\n\n # Ensure that invalid callbacks (invalid signatures) do not get called\n # and do not break the bus for other subscribers\n foo_sub.subscribe_incorrect_sig()\n bus.publish('foo', 'data')\n self.assertEquals(foo_sub2.num_cb, 1)\n\n def test_multi_sub(self):\n \"\"\"Tests one subscriber that subscribes to multiple topics\"\"\"\n # Create bus\n bus = pubsub.PubSubBus()\n\n topic_data_dict = {\n 'foo': 'data',\n 'bar': 589,\n 'baz': {'a': 1, 'b': 2}}\n\n # Create multi-subscriber and publish to all topics before subscribing.\n multi_sub = MultiSubscriber(self, bus, topic_data_dict)\n\n for (topic, data) in topic_data_dict.iteritems():\n bus.publish(topic, data)\n\n self.assertEquals(multi_sub.num_cb, 0)\n\n # Subscribe to all topics\n multi_sub.subscribe_topics()\n\n # Publish several times in various combos of topics and then verify\n # counts\n\n for (topic, data) in topic_data_dict.iteritems():\n bus.publish(topic, data)\n\n self.assertEquals(multi_sub.num_cb, len(topic_data_dict))\n\n for (topic, data) in topic_data_dict.iteritems():\n bus.publish(topic, data)\n bus.publish(topic, data)\n\n self.assertEquals(multi_sub.num_cb, 3 * len(topic_data_dict))\n\n bus.publish('foo', topic_data_dict['foo'])\n self.assertEquals(multi_sub.num_cb, 3 * len(topic_data_dict) + 1)\n\n\nif __name__ == '__main__':\n logging.basicConfig()\n unittest.main()\n","repo_name":"tanadeau/pubsub","sub_path":"test_pubsub.py","file_name":"test_pubsub.py","file_ext":"py","file_size_in_byte":7459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"19494055437","text":"import io\nfrom platform import node\nimport time\nimport pycurl\nimport stem.control\nfrom stem.util import term\nfrom random import randrange, sample\n\n# EXIT_FINGERPRINT_IN = 'E34C28D652520D7C8D386EA3958EA924910E647B'\n# EXIT_FINGERPRINT_IN_2 = '059208418A85DAEA537027F54AF9DB8A01AFF381'\n\n# EXIT_FINGERPRINT_SG = '5E762A58B1F7FF92E791A1EA4F18695CAC6677CE'\n# EXIT_FINGERPRINT_XOR = '00089AB30F240C64687576C3EE8FC93002D9ACA0'\n\n# paths = [EXIT_FINGERPRINT_IN,EXIT_FINGERPRINT_SG]\n\nSOCKS_PORT = 9050\nCONNECTION_TIMEOUT = 10 # timeout before we give up on a circuit\n\ndef query(url):\n# Uses pycurl to fetch a site using the proxy on the SOCKS_PORT.\n\n output = io.BytesIO()\n\n query = pycurl.Curl()\n query.setopt(pycurl.URL, url)\n query.setopt(pycurl.PROXY, 'localhost')\n query.setopt(pycurl.PROXYPORT, SOCKS_PORT)\n query.setopt(pycurl.CONNECTTIMEOUT, CONNECTION_TIMEOUT)\n query.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS5_HOSTNAME)\n query.setopt(pycurl.WRITEFUNCTION, output.write)\n\n try:\n query.perform()\n return output.getvalue()\n except pycurl.error as exc:\n return \"Unable to reach %s (%s)\" % (url, exc)\n\n\ndef scan(controller, path):\n\n# Fetch ipinfo.io/ip through the given path of relays, providing back the IP & time it took.\n\n print(\"Trying to build a circuit on this Path...\")\n\n circuit_id = controller.new_circuit(path, await_build = True)\n\n def attach_stream(stream):\n if stream.status == 'NEW':\n controller.attach_stream(stream.id, circuit_id)\n\n controller.add_event_listener(attach_stream, stem.control.EventType.STREAM)\n\n try:\n controller.set_conf('__LeaveStreamsUnattached', '1') # leave stream management to us\n start_time = time.time()\n\n print(\"\\nCONNECTED SUCCESSFULLY!\")\n print(\"\\nOutput from IPinfo:\")\n print(term.format(query(\"http://ipinfo.io/ip\"), term.Color.CYAN))\n\n return time.time() - start_time\n finally:\n controller.remove_event_listener(attach_stream)\n controller.reset_conf('__LeaveStreamsUnattached')\n\n###############\n\nnodes = []\nrelay_fingerprints = []\n\nwith stem.control.Controller.from_port() as controller:\n controller.authenticate()\n\n\n num = int(input(\"Enter the number of relays to be used in tor circuit: \"))\n x = input(\"Do you want random relays: [y/n] \")\n\n if x.lower() == 'y':\n print(\"\\nDownloading Tor Relay information...\")\n\n for desc in controller.get_network_statuses():\n relay_fingerprints.append([desc.nickname, desc.fingerprint, desc.address])\n\n print(\"Done!\")\n print(\"\\nNow selecting\" ,num, \"relays randomly from the Tor Relay list...\")\n\n nodes = sample(relay_fingerprints, num)\n\n print(\"\\nThe following path has been selected:\\n\")\n \n for i in nodes:\n print(i)\n\n path = [x[1] for x in nodes]\n\n elif x.lower() == 'n':\n print(\"\\nEnter the fingerprints of the\", num ,\" Relays manually -\\n\")\n\n for i in range(num):\n nodes.append(input(\"Enter fingerprint: \"))\n\n path = nodes\n\n else:\n print(\"Invalid choice!\\n\")\n\n try:\n \n print(\"\\nTesting the above path...\")\n\n time_taken = scan(controller, path)\n print('Total time taken => %0.2f seconds' % (time_taken))\n except Exception as exc:\n print('ERROR => %s' % (exc))\n\n\n\n\n\n\n","repo_name":"ritik-malik/torpedo","sub_path":"torpedo.py","file_name":"torpedo.py","file_ext":"py","file_size_in_byte":3192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"30867066085","text":"\"\"\"协程的小练习,利用协程实现同时进行一个抽象的复杂任务(这里用time.sleep()代替)和一个不断旋转的指示器\"\"\"\n\nimport time\nimport sys\n\n\ndef draw():\n while True:\n for icon in ['/ ', '| ', '\\\\ ', '—— ']:\n sys.stdout.write('\\r')\n sys.stdout.write(icon)\n sys.stdout.flush()\n x = yield\n\n\ndef time_waste():\n current_time = 0\n while True:\n time.sleep(0.2)\n current_time += 0.2\n x = yield current_time\n\n\ndef main():\n total_time = 10\n draw_machine = draw()\n time_waste_machine = time_waste()\n next(draw_machine)\n next(time_waste_machine)\n is_finished = False\n while not is_finished:\n draw_machine.send(1)\n current_time = time_waste_machine.send(1)\n if current_time >= total_time:\n is_finished = True\n\n\nif __name__ == '__main__':\n main()","repo_name":"cao93821/creeper","sub_path":"coroutines00.py","file_name":"coroutines00.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"71718107130","text":"from cosmo_forecast.likelihoods import baoLikelihood\nfrom cosmo_forecast.sampler_interface import Sampler\nimport numpy as np\nfrom configparser import ConfigParser\n\n\ndef main(ini_file):\n\n # Read ini file and initialize likelihood object\n config = ConfigParser()\n config.read(ini_file)\n\n limits = {}\n for param, lims in config.items('Likelihood'):\n if param != 'data':\n limits[param] = np.array(lims.split(',')).astype(float)\n assert len(limits[param]) == 2\n\n lik_obj = baoLikelihood(config)\n sampler = Sampler(config['Polychord'], limits, lik_obj.log_lik)\n sampler.run()\n\n\nif __name__ == \"__main__\":\n import sys\n\n if len(sys.argv) != 2:\n print(\"Usage: \", __file__, \" \")\n else:\n main(sys.argv[1])","repo_name":"andreicuceu/cosmo_forecast","sub_path":"bin/run_polychord.py","file_name":"run_polychord.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"21374618301","text":"import importlib\nimport os\nfrom collections import OrderedDict\nfrom lib.test.evaluation.environment import env_settings\nimport time\nimport cv2 as cv\n\nfrom lib.utils.lmdb_utils import decode_img\nfrom pathlib import Path\nimport numpy as np\n\n\ndef trackerlist(name: str, parameter_name: str, dataset_name: str, run_ids = None, display_name: str = None,\n result_only=False):\n \"\"\"Generate list of trackers.\n args:\n name: Name of tracking method.\n parameter_name: Name of parameter file.\n run_ids: A single or list of run_ids.\n display_name: Name to be displayed in the result plots.\n \"\"\"\n if run_ids is None or isinstance(run_ids, int):\n run_ids = [run_ids]\n return [Tracker(name, parameter_name, dataset_name, run_id, display_name, result_only) for run_id in run_ids]\n\n\nclass Tracker:\n \"\"\"Wraps the tracker for evaluation and running purposes.\n args:\n name: Name of tracking method.\n parameter_name: Name of parameter file.\n run_id: The run id.\n display_name: Name to be displayed in the result plots.\n \"\"\"\n\n def __init__(self, name: str, parameter_name: str, dataset_name: str, run_id: int = None, display_name: str = None,\n result_only=False):\n assert run_id is None or isinstance(run_id, int)\n\n self.name = name\n self.parameter_name = parameter_name\n self.dataset_name = dataset_name\n self.run_id = run_id\n self.display_name = display_name\n\n env = env_settings()\n if self.run_id is None:\n self.results_dir = '{}/{}/{}'.format(env.results_path, self.name, self.parameter_name)\n else:\n self.results_dir = '{}/{}/{}_{:03d}'.format(env.results_path, self.name, self.parameter_name, self.run_id)\n if result_only:\n self.results_dir = '{}/{}'.format(env.results_path, self.name)\n\n tracker_module_abspath = os.path.abspath(os.path.join(os.path.dirname(__file__),\n '..', 'tracker', '%s.py' % self.name))\n if os.path.isfile(tracker_module_abspath):\n tracker_module = importlib.import_module('lib.test.tracker.{}'.format(self.name))\n self.tracker_class = tracker_module.get_tracker_class()\n else:\n self.tracker_class = None\n\n def create_tracker(self, params):\n tracker = self.tracker_class(params, self.dataset_name)\n return tracker\n\n def run_sequence(self, seq, debug=None):\n \"\"\"Run tracker on sequence.\n args:\n seq: Sequence to run the tracker on.\n visualization: Set visualization flag (None means default value specified in the parameters).\n debug: Set debug level (None means default value specified in the parameters).\n multiobj_mode: Which mode to use for multiple objects.\n \"\"\"\n params = self.get_parameters()\n\n debug_ = debug\n if debug is None:\n debug_ = getattr(params, 'debug', 0)\n\n params.debug = debug_\n\n # Get init information\n init_info = seq.init_info()\n\n tracker = self.create_tracker(params)\n\n output = self._track_sequence(tracker, seq, init_info)\n return output\n\n def _track_sequence(self, tracker, seq, init_info):\n # Define outputs\n # Each field in output is a list containing tracker prediction for each frame.\n\n # In case of single object tracking mode:\n # target_bbox[i] is the predicted bounding box for frame i\n # time[i] is the processing time for frame i\n\n # In case of multi object tracking mode:\n # target_bbox[i] is an OrderedDict, where target_bbox[i][obj_id] is the predicted box for target obj_id in\n # frame i\n # time[i] is either the processing time for frame i, or an OrderedDict containing processing times for each\n # object in frame i\n\n output = {'target_bbox': [],\n 'time': []}\n if tracker.params.save_all_boxes:\n output['all_boxes'] = []\n output['all_scores'] = []\n\n def _store_outputs(tracker_out: dict, defaults=None):\n defaults = {} if defaults is None else defaults\n for key in output.keys():\n val = tracker_out.get(key, defaults.get(key, None))\n if key in tracker_out or val is not None:\n output[key].append(val)\n\n # Initialize\n image = self._read_image(seq.frames[0])\n\n start_time = time.time()\n out = tracker.initialize(image, init_info)\n if out is None:\n out = {}\n\n prev_output = OrderedDict(out)\n init_default = {'target_bbox': init_info.get('init_bbox'),\n 'time': time.time() - start_time}\n if tracker.params.save_all_boxes:\n init_default['all_boxes'] = out['all_boxes']\n init_default['all_scores'] = out['all_scores']\n\n _store_outputs(out, init_default)\n\n for frame_num, frame_path in enumerate(seq.frames[1:], start=1):\n image = self._read_image(frame_path)\n\n start_time = time.time()\n\n info = seq.frame_info(frame_num)\n info['previous_output'] = prev_output\n\n if len(seq.ground_truth_rect) > 1:\n info['gt_bbox'] = seq.ground_truth_rect[frame_num]\n out = tracker.track(image, info)\n prev_output = OrderedDict(out)\n _store_outputs(out, {'time': time.time() - start_time})\n\n for key in ['target_bbox', 'all_boxes', 'all_scores']:\n if key in output and len(output[key]) <= 1:\n output.pop(key)\n\n return output\n\n def run_video(self, frames, optional_box=None, debug=None, visdom_info=None, save_results=False):\n \"\"\"Run the tracker with the vieofile.\n args:\n debug: Debug level.\n \"\"\"\n\n params = self.get_parameters()\n\n debug_ = debug\n if debug is None:\n debug_ = getattr(params, 'debug', 0)\n params.debug = debug_\n\n params.tracker_name = self.name\n params.param_name = self.parameter_name\n # self._init_visdom(visdom_info, debug_)\n\n multiobj_mode = getattr(params, 'multiobj_mode', getattr(self.tracker_class, 'multiobj_mode', 'default'))\n\n if multiobj_mode == 'default':\n tracker = self.create_tracker(params)\n if hasattr(tracker, 'initialize_features'):\n tracker.initialize_features()\n\n elif multiobj_mode == 'parallel':\n tracker = MultiObjectWrapper(self.tracker_class, params, self.visdom, fast_load=True)\n else:\n raise ValueError('Unknown multi object mode {}'.format(multiobj_mode))\n\n output_boxes, output_confidence, output_heatmaps = [], [], []\n\n # cap = cv.VideoCapture(videofilepath)\n # cap = cv.VideoCapture(videofilepath)\n # success, frame = cap.read()\n frame = frames[0]\n\n # display_name = 'Display: ' + tracker.params.tracker_name\n # cv.namedWindow(display_name, cv.WINDOW_NORMAL | cv.WINDOW_KEEPRATIO)\n # cv.resizeWindow(display_name, 960, 720)\n # # success, frame = cap.read()\n # cv.imshow(display_name, frame)\n\n # def _build_init_info(box):\n # return {'init_bbox': OrderedDict({1: box}), 'init_object_ids': [1, ], 'object_ids': [1, ],\n # 'sequence_object_ids': [1, ]}\n def _build_init_info(box):\n return {'init_bbox': box}\n\n assert optional_box is not None\n assert isinstance(optional_box, (list, tuple))\n assert len(optional_box) == 4, \"valid box's foramt is [x,y,w,h]\"\n tracker.initialize(frame, _build_init_info(optional_box))\n\n for frame in frames:\n\n if frame is None:\n break\n\n # Draw box\n out = tracker.track(frame)\n state = [int(s) for s in out[\"target_bbox\"]]\n conf = out[\"bbox_score\"]\n heatmap = out[\"heatmap\"] # .squeeze().cpu().detach()\n # If the tracker box confidence is < threshold, kill the tracker\n # if conf < 0.1:\n # return output_boxes, output_confidence, output_heatmaps\n # print({k: max(v) for k, v in out[\"max_score\"].items()}, state)\n output_boxes.append(state)\n output_confidence.append(conf)\n output_heatmaps.append(heatmap)\n\n tracker.initialize(frame, _build_init_info(state)) # Reinit the template\n\n return output_boxes, output_confidence, output_heatmaps\n\n def extract_encodings(self, frames, states, debug=False, visdom_info=None, save_results=False):\n \"\"\"Run the tracker with the vieofile.\n args:\n debug: Debug level.\n \"\"\"\n\n params = self.get_parameters()\n\n debug_ = debug\n if debug is None:\n debug_ = getattr(params, 'debug', 0)\n params.debug = debug_\n\n params.tracker_name = self.name\n params.param_name = self.parameter_name\n # self._init_visdom(visdom_info, debug_)\n\n multiobj_mode = getattr(params, 'multiobj_mode', getattr(self.tracker_class, 'multiobj_mode', 'default'))\n\n tracker = self.create_tracker(params)\n if hasattr(tracker, 'initialize_features'):\n tracker.initialize_features()\n\n def _build_init_info(box):\n return {'init_bbox': box}\n\n tracker.initialize(frames[0], _build_init_info(states[0]))\n output_heatmaps, output_boxes = [], []\n for frame, state in zip(frames, states):\n self.state = state # Not tracking, so overwrite with existing tracks\n\n if frame is None:\n break\n\n # Draw box\n out = tracker.track(frame)\n encoding = out[\"encodings\"]\n state = [int(s) for s in out[\"target_bbox\"]]\n\n # Figure out how to summarize encodings\n encoding = encoding.squeeze(0).mean(0).detach().cpu().numpy().reshape(1, -1)\n output_heatmaps.append(encoding)\n output_boxes.append(state)\n\n return output_heatmaps, output_boxes\n\n def gradient_of_distance(self, framesa, framesb, statesa, statesb, smooth_iters=0, debug=False, visdom_info=None, save_results=False):\n \"\"\"Run the tracker with the vieofile.\n args:\n debug: Debug level.\n \"\"\"\n\n params = self.get_parameters()\n\n debug_ = debug\n if debug is None:\n debug_ = getattr(params, 'debug', 0)\n params.debug = debug_\n\n params.tracker_name = self.name\n params.param_name = self.parameter_name\n # self._init_visdom(visdom_info, debug_)\n\n multiobj_mode = getattr(params, 'multiobj_mode', getattr(self.tracker_class, 'multiobj_mode', 'default'))\n\n tracker = self.create_tracker(params)\n if hasattr(tracker, 'initialize_features'):\n tracker.initialize_features()\n\n def _build_init_info(box):\n return {'init_bbox': box}\n\n\n # First track framesa\n tracker.initialize(framesa[0], _build_init_info(statesa[0]))\n encs_a = []\n for frame, state in zip(framesa, statesa):\n self.state = state # Not tracking, so overwrite with existing tracks\n\n # Get encodings\n out = tracker.track(frame)\n encoding = out[\"encodings\"]\n encoding = encoding.squeeze(0).mean(0).reshape(1, -1)\n encs_a.append(encoding)\n\n # Next track framesb, compute distance of ||encodingb|| - encodinga_t||, and store gradient of difference wrt framesb\n tracker.initialize(framesb[0], _build_init_info(statesb[0]))\n gradients, patches = [], []\n for frame, state, enc_a in zip(framesb, statesb, encs_a):\n self.state = state # Not tracking, so overwrite with existing tracks\n\n # Get encodings\n if smooth_iters:\n smoothed = []\n for _ in range(smooth_iters):\n noise_frame = frame + np.random.normal(scale=1e-3, size=frame.shape)\n out = tracker.track(noise_frame, store_grad=True)\n encoding = out[\"encodings\"]\n input_patch = out[\"input_patch\"] # Has a gradient\n enc_b = encoding.squeeze(0).mean(0).reshape(1, -1)\n\n # Get difference and gradient\n dist = ((enc_a - enc_b) ** 2).mean()\n tracker.network.zero_grad()\n dist.backward()\n gradient = input_patch.grad.data.cpu().numpy()\n smoothed.append(gradient)\n gradient = np.stack(smoothed, 0).mean(0)\n else:\n out = tracker.track(frame, store_grad=True)\n encoding = out[\"encodings\"]\n input_patch = out[\"input_patch\"] # Has a gradient\n enc_b = encoding.squeeze(0).mean(0).reshape(1, -1)\n\n # Get difference and gradient\n dist = ((enc_a - enc_b) ** 2).mean()\n tracker.network.zero_grad()\n dist.backward()\n gradient = input_patch.grad.data.cpu().numpy()\n gradients.append(gradient)\n patches.append(input_patch.detach().cpu().numpy())\n return gradients, patches\n\n def get_parameters(self):\n \"\"\"Get parameters.\"\"\"\n param_module = importlib.import_module('lib.test.parameter.{}'.format(self.name))\n params = param_module.parameters(self.parameter_name)\n return params\n\n def _read_image(self, image_file: str):\n if isinstance(image_file, str):\n im = cv.imread(image_file)\n return cv.cvtColor(im, cv.COLOR_BGR2RGB)\n elif isinstance(image_file, list) and len(image_file) == 2:\n return decode_img(image_file[0], image_file[1])\n else:\n raise ValueError(\"type of image_file should be str or list\")\n\n\n\n","repo_name":"drewlinsley/ost_cells","sub_path":"lib/test/evaluation/tracker.py","file_name":"tracker.py","file_ext":"py","file_size_in_byte":14034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"28899699552","text":"\"\"\"Type mapping between Python and PySpark types.\"\"\"\n\nimport inspect\nfrom types import UnionType\nfrom typing import (\n Any,\n Callable,\n List,\n Tuple,\n Type,\n Union,\n get_args,\n get_origin,\n no_type_check,\n)\n\nfrom pyspark.sql.types import (\n ArrayType,\n BooleanType,\n DataType,\n FloatType,\n IntegerType,\n MapType,\n NullType,\n StringType,\n StructField,\n StructType,\n)\n\nimport numpy as np\nimport warnings\n\nIntArray = np.ndarray[1, int]\nBooleanArray = np.ndarray[1, bool]\nFloatArray = np.ndarray[1, float]\nNullableFloatArray = np.ndarray[1, float | None]\n\n\ndef convert_annotation_to_spark(name: str, t: type) -> StructField:\n \"\"\"Converts a Python type annotation to PySpark DataType.\"\"\"\n # TODO: Check for numpy.typing.NDArray and others... they're a bit raw for now\n\n # Scalar types\n if get_origin(t) is None:\n if t is None:\n return StructField(name, NullType(), nullable=True) # FIXME: allowed?\n if t is Any:\n return StructField(name, NullType()) # FIXME: is this allowed?\n if issubclass(t, str):\n return StructField(name, StringType(), nullable=False)\n if issubclass(t, bool):\n return StructField(name, BooleanType(), nullable=False)\n if issubclass(t, float):\n return StructField(name, FloatType(), nullable=False)\n if issubclass(t, int):\n return StructField(name, IntegerType(), nullable=False)\n # Other things are disallowed\n if isinstance(t, np.ndarray):\n raise TypeError(\n \"Cannot specify ndarray without sizes. Use `np.ndarray[1, float]`\"\n \" or `IntArray`/`BooleanArray`/`[Nullable]FloatArray` instead.\"\n )\n raise TypeError(f\"Unknown type annotation: {t!r}\")\n # More complex case\n origin = get_origin(t)\n args = get_args(t)\n # Optional\n if origin in [Union, UnionType]:\n # Check for nullables\n has_none = bool((None in args) or (type(None) in args))\n clean_args = tuple(x for x in args if x not in [None, type(None)])\n # Make sure it's a union with only 1 other value\n if len(clean_args) == 1:\n base = convert_annotation_to_spark(name, clean_args[0])\n return StructField(name, base.dataType, nullable=has_none)\n raise TypeError(f\"Unions of multiple types (besides None) not allowed: {t!r}\")\n\n # lists as arrays\n if origin in [List, list]:\n # This can do arrays of arrays\n base = convert_annotation_to_spark(name, args[0])\n at = ArrayType(base.dataType, containsNull=base.nullable)\n return StructField(name, at, nullable=False)\n\n # numpy array\n if origin is np.ndarray:\n n = args[0]\n if n is Any:\n n = 1 # FIXME: This always assumes ndarray[Any, dtype] is 1D for now\n if not isinstance(n, int):\n raise TypeError(f\"Unknown ndarray annotation (n = {n!r}): {t!r}\")\n # Make n-dimensional list as array-of-arrays\n new_t = args[1:]\n for _ in range(n):\n new_t = list[new_t]\n return convert_annotation_to_spark(name, new_t)\n\n # tuples as lists or structs\n if origin in [Tuple, tuple]:\n if ... in args:\n # treat it as a list\n clean_args = tuple(x for x in args if x is not ...)\n return convert_annotation_to_spark(name, list[clean_args])\n else:\n # treat it as a struct\n warnings.warn(f\"Unknown names for fields, setting as '{name}_i'.\")\n fields = []\n for i, arg in enumerate(args):\n fld = convert_annotation_to_spark(f\"{name}_{i}\", arg)\n fields.append(fld)\n return StructField(name, StructType(fields), nullable=False)\n\n raise TypeError(f\"Unknown annotation origin {origin!r} for: {t!r}\")\n\n\n@no_type_check\ndef eval_type(t, globalns=None, localns=None, recursive_guard=frozenset()):\n \"\"\"Wrapper for typing._eval_type() function.\"\"\"\n from typing import _eval_type # noqa\n\n if localns is None:\n localns = {}\n if globalns is None:\n globalns = globals()\n\n return _eval_type(t, globalns, localns, recursive_guard=recursive_guard)\n\n\ndef get_param_type(p: inspect.Parameter) -> type:\n \"\"\"Tries to get the type from a parameter.\"\"\"\n if p.annotation == p.empty:\n raise TypeError(f\"Missing annotation for {p!r}\")\n t = eval_type(p.annotation)\n return t\n","repo_name":"NowanIlfideme/pyspark-mc","sub_path":"pyspark_mc/internals/type_mapping.py","file_name":"type_mapping.py","file_ext":"py","file_size_in_byte":4479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"73656053690","text":"from web3 import Web3, Account\nimport json\n\n\nw3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))\n\nPRIVATE_KEY = \"0x2a871d0798f97d79848a013d4936a73bf4cc922c825d33c1cf7073dff6d409c6\"\n\nERC20_ABI = json.load(open('abi/ERC20.json', 'r'))\nPOOL_ABI = json.load(open('abi/Pool.json', 'r'))\nMANAGER_ABI = json.load(open('abi/Manager.json', 'r'))\nQUOTER_ABI = json.load(open('abi/Quoter.json', 'r'))\n\nWETH_ADDRESS = \"0x0E4B6314D9756D40EE0b3D68cF3999D29eEFb147\"\nUSDC_ADDRESS = \"0x3C4249f1cDf4C5Ee12D480a543a6A42362baAAFf\"\nPOOL_ADDRESS = \"0x3Be63776630ac9f282109352C804E650d515C604\"\nMANAGER_ADDRESS = \"0x43992F5f575c28A1dE03b1F337974b94e44FAb8c\"\nQUOTER_ADDRESS = \"0x5f474bC674b6Ad4d7b6A5c6429d586D53053DA33\"\n\nweth = w3.eth.contract(address=WETH_ADDRESS, abi=ERC20_ABI)\nusdc = w3.eth.contract(address=USDC_ADDRESS, abi=ERC20_ABI)\npool = w3.eth.contract(address=POOL_ADDRESS, abi=POOL_ABI)\nmanager = w3.eth.contract(address=MANAGER_ADDRESS, abi=MANAGER_ABI)\nquoter = w3.eth.contract(address=QUOTER_ADDRESS, abi=QUOTER_ABI)\n\naccount = Account.from_key(PRIVATE_KEY)\nw3.eth.defaultAccount = account.address\n\nprint(f\"Set default account to {account.address}\")\n\n","repo_name":"brandonshiyay/uniswapv3-clone","sub_path":"client/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"32288601897","text":"import logging\r\nimport datetime\r\nimport os\r\nfrom pathlib import Path\r\n\r\n\r\ndef getDate():\r\n return str(datetime.date.today().strftime(\"%d_%m_%Y\"))\r\n\r\n\r\ndef Log(LogName):\r\n cwd = os.getcwd()\r\n filePath = rf'{Path(cwd)}\\Log'\r\n\r\n LogPath = CreateNewLogFile(date=getDate(),\r\n filename=LogName, file_path=filePath)\r\n\r\n logger = logging.getLogger(LogName)\r\n logger.setLevel(logging.DEBUG) # the level should be the lowest level set in handlers\r\n log_format = logging.Formatter('%(asctime)s: \\t --> [%(levelname)s] \\t %(message)s')\r\n\r\n streamLog = logging.StreamHandler()\r\n streamLog.setFormatter(log_format)\r\n streamLog.setLevel(logging.DEBUG)\r\n logger.addHandler(streamLog)\r\n\r\n MainLog = logging.FileHandler(LogPath)\r\n MainLog.setFormatter(log_format)\r\n MainLog.setLevel(logging.DEBUG)\r\n logger.addHandler(MainLog)\r\n\r\n return logger\r\n\r\n\r\ndef CreateNewLogFile(date, filename, file_path):\r\n ToDay = date\r\n fullPath = os.path.join(file_path, f'{filename} {ToDay}.log')\r\n try:\r\n if not os.path.exists(fullPath):\r\n open(fullPath, 'w+').close()\r\n else:\r\n raise FileExistsError\r\n\r\n except FileExistsError:\r\n print(f\"{filename} {ToDay}.log already exists\")\r\n except OSError as oerr:\r\n print(f\"Creation of the {filename} {ToDay}.log failed \\n got this error: {oerr}\")\r\n except TypeError as terr:\r\n print(f\"Creation of the file {filename} {ToDay}.log failed \\n got this error: {terr}\")\r\n else:\r\n print(f\"Successfully created the {filename} {ToDay}.log \")\r\n\r\n return fullPath\r\n","repo_name":"lirankris/Fuel_Vs._Food_ML-Project","sub_path":"DataFrames/CreateTools/CreateLogger.py","file_name":"CreateLogger.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"43735181475","text":"import re\nimport sys\nfrom urllib.parse import urlparse\n\nMODULE_REGEX = r'^[a-z][a-z0-9\\-]+[a-z0-9]$'\nMODULE_NAME = '{{ cookiecutter.project_name }}'\n\nDOMAIN_NAME = '{{ cookiecutter.project_domain }}'\n\n\ndef validate_project_name():\n \"\"\"\n This validator is used to ensure that `project_name` is valid.\n\n Valid inputs starts with the lowercase letter.\n Followed by any lowercase letters, numbers or underscores.\n\n Valid example: `school_project3`.\n \"\"\"\n if not re.match(MODULE_REGEX, MODULE_NAME):\n # Validates project's module name:\n message = [\n 'ERROR: The project slug {0} is not a valid name.',\n 'Start with a lowercase letter.',\n 'Followed by any lowercase letters, numbers, or dashes (-).',\n ]\n raise ValueError(' '.join(message).format(MODULE_NAME))\n\n\ndef validate_domain():\n \"\"\"\n This validator is used to enforce correct `project_domain` inputs.\n\n What is considered valid:\n 1. myapp.com\n 2. google.co.uk\n 3. wemake.services\n\n What is considered invalid:\n 1. https://wemake.services\n 2. http://mysite.ru/hello\n 3. http://myshop.com?query=django\n\n \"\"\"\n parsed_url = urlparse(DOMAIN_NAME)\n if not parsed_url.path:\n # When entering just a domain everything inside goes to `path`.\n # So, it should be set. If not, that's an error.\n raise ValueError(\n 'ERROR: `project_domain` is invalid. Remove `http(s)://` part.',\n )\n\n parts = [\n parsed_url.scheme,\n parsed_url.netloc,\n parsed_url.params,\n parsed_url.query,\n parsed_url.fragment,\n ]\n\n if any(bool(part) for part in parts):\n raise ValueError(\n 'ERROR: `project_domain` should be a domain name only. ',\n )\n\n\nvalidators = (\n validate_project_name,\n validate_domain,\n)\n\nfor validator in validators:\n try:\n validator()\n except ValueError as ex:\n print(ex) # noqa: WPS421\n sys.exit(1)\n","repo_name":"wemake-services/wemake-django-template","sub_path":"hooks/pre_gen_project.py","file_name":"pre_gen_project.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","stars":1846,"dataset":"github-code","pt":"77"}
+{"seq_id":"10848998001","text":"# Get Sentence from Sentence\n\noriginal = input(\"Type the sentence\").strip().lower()\n\n# Split the sentence into words\n\nwords = original.split()\n\n# Loop through the words and convert to Pig Latin\nnew_words = []\n# if it starts with vowel, just add \"yay\"\n# otherwise, move the first consonent to the end and add \"aY\"\nfor word in words:\n if word[0] in \"aeiou\":\n new_word = word + \"yay\"\n new_words.append(new_word)\n else:\n vowel_pos = 0\n for letter in word:\n if letter not in \"aeiou\":\n vowel_pos += 1\n else:\n break\n new_word = word[vowel_pos:] + word[:vowel_pos].upper() + \"aY\"\n new_words.append(new_word)\n\nprint (\" \".join(new_words))\n\n\n# Stick those words together into Sentence\n\n# Output the final String","repo_name":"sumitkjm/python-learning","sub_path":"Pig.py","file_name":"Pig.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"42888971987","text":"#Finding COS sightlines that pass within 2 Mpc in projected separation wrt to BCGs in Abell Clusters \nfrom nedcalc1 import *\nfrom numpy import *\nf0 = open('modspec','r')\nlines0 = f0.readlines()\nf = open('abell_new','r')\nlines = f.readlines()\nf1 = open('qsoradec','r')\nlines1 = f1.readlines()\nf2 = open('clustercover','w')\ncf = pi/180.0\nf2.write('BCG z N(<1Mpc) N_sight Distance [Mpc] Sightline\\n')\nn1 = 0\nn2 = 0\nn3 = 0\nfor i in range(28,len(lines)):\n print('Cluster '+str(i-27)+' ...')\n line = lines[i].split()\n z = float(line[4])\n zsp = float(line[5])\n nmem = int(line[7])\n zsel = zsp\n if zsel ==-1:\n zsel = z - 0.03\n ra1 = float(line[2])*cf\n dec1 = float(line[3])*cf\n sf = cosmcalc(69.6,0.286,0.714,zsel)#scale factor in kpc/\"\n count=0\n sname = array([],dtype=str)\n ds=array([])\n for j in range(len(lines1)):\n line1 = lines1[j].split()\n line0 = lines0[j].split('\\n')[0]\n zqso = float(line0.split(',')[1])\n if zqso>zsel:\n ra2 = float(line1[1])*cf\n dec2 = float(line1[2])*cf\n theta = 180/pi*arccos(sin(dec1)*sin(dec2)+cos(dec1)*cos(dec2)*cos(ra1-ra2))*3600\n d = sf*theta*1e-3#projected distance in Mpc\n if d<=2:#if the sightline is within 2 Mpc of the BCG\n count+=1\n sname = append(sname,line1[0])\n print('yes!: '+sname[-1]+','+str(round(d,1))+' Mpc')\n #if d1 and d<1.5:\n n2+=1\n if d>1.5 and d<2:\n n3+=1 \n f2.write('\\n'+line[1]+' '+str(zsel)+' '+str(nmem)+' '+str(count)+' '+str(ds)+' '+str(sname))\nf2.close()\n \nprint('Sightlines at d <1 Mpc:',n1)\nprint('Sightlines at 1 int:\n if not root:\n return 0\n q = deque([(1,root)])\n ans = 1\n while q:\n layer, node = q.popleft()\n ans = max(layer,ans)\n if node.left:\n q.append((layer+1, node.left))\n if node.right:\n q.append((layer+1, node.right))\n return ans\n\nfrom collections import deque\nclass Solution:\n def maxDepth(self, root: Optional[TreeNode]) -> int:\n if not root:\n return 0\n q = deque([root])\n depth = 0\n while q:\n depth += 1\n for _ in range(len(q)): # L번쨰 layer들의 모든 Node들이 담김\n node = q.popleft()\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n return depth\n\n'''\n첫번째 풀이가 내 풀이이고, 두번째 풀이가 책에 적힌 풀이이다. \n시간대는 내가 더 빠르게 풀이가 되었다. 그러나 특정 layer의 모든 node들을 for문에서 모두 popleft시키고 child node들을 다시 q에 채워나가는 방식에서 흥미롭다고 생각했다.\n더불어서, if not root와 같은 형태로 exception을 잡아주는 노력을 시도했어야 했다.\n'''\n\n#https://leetcode.com/problems/diameter-of-binary-tree/submissions/\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nfrom collections import deque\nclass Solution:\n def __init__(self):\n self.longest = 0\n\n def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n def dfs(node: TreeNode) -> int:\n if not node:\n return -1\n left = dfs(node.left)\n right = dfs(node.right)\n\n self.longest = max(self.longest, left + right + 2) # 거리\n return max(left, right) + 1 #상태값\n\n dfs(root)\n return self.longest\n\n'''\n위 문제는 dfs를 이용해서 leaf node까지 도달한 다음, 거리와 상태값을 업데이트 한다.\n이때 거리는 left와 right에 +2 (한 node를 기준으로 left에 대한 edge 1개 + right에 대한 edge가 1개) 이기 때문이다.\n그리고 상태값은 해당 Node가 가질 수 있는 최대 깊이(?)라고 생각이 가능하다. \n이때 하나의 전역변수인 self.longest를 이용해서 binary tree에 존재하는 모든 거리에 대해서 max로 비교하였다.\n\n아직까지 코딩이 너무 부족하다고 많이 느낀다 ㅠㅠ\n'''","repo_name":"Gyu-Seok0/Coding-Test","sub_path":"Binary Search/0621_BinaryTree.py","file_name":"0621_BinaryTree.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"23800081005","text":"import os\n\nfrom qtpy.QtCore import Qt, QRectF\nfrom qtpy.QtGui import QImage\nfrom qtpy.QtWidgets import QLabel, QSlider, QVBoxLayout\nimport FreeCAD as App\n\nfrom nodeeditor.node_node import Node\nfrom nodeeditor.node_socket import LEFT_CENTER, RIGHT_CENTER\nfrom nodeeditor.node_graphics_node import QDMGraphicsNode\nfrom nodeeditor.node_content_widget import QDMNodeContentWidget\nfrom examples.example_freecad.calc_conf import register_node, OP_NODE_NUM_SLID\nfrom nodeeditor.utils import dumpException\n\n\nclass NumberSliderContent(QDMNodeContentWidget):\n def initUI(self):\n self.layout = QVBoxLayout()\n self.layout.setContentsMargins(0,0,0,0)\n self.setLayout(self.layout)\n\n self.slider = QSlider(Qt.Horizontal, parent=self)\n self.slider.setTickPosition(QSlider.TicksAbove)\n self.slider.setMinimum(0)\n self.slider.setMaximum(100)\n self.slider.setValue(50)\n self.layout.addWidget(self.slider)\n\n self.lbl = QLabel(str(self.slider.value()/100), self)\n self.lbl.setObjectName(self.node.content_label_objname)\n self.lbl.setAlignment(Qt.AlignCenter)\n self.layout.addWidget(self.lbl)\n\n def serialize(self):\n res = super().serialize()\n res['number'] = self.slider.value()\n return res\n\n def deserialize(self, data, hashmap={}):\n res = super().deserialize(data, hashmap)\n try:\n value = data['number']\n self.slider.setValue(value)\n return True & res\n except Exception as e:\n dumpException(e)\n return res\n\n\nclass NumberSliderGraphicsNode(QDMGraphicsNode):\n def initSizes(self):\n super().initSizes()\n self.width = 160\n self.height = 52\n self.edge_roundness = 6\n self.edge_padding = 0\n self.title_horizontal_padding = 8\n self.title_vertical_padding = 10\n\n def initAssets(self):\n super().initAssets()\n status_icon = os.path.join(App.getUserAppDataDir(), \"Macro\", \"pyqt-node-editor\", \"examples\",\n \"example_freecad\", \"icons\", \"status_icons.png\")\n self.icons = QImage(status_icon)\n\n def paint(self, painter, QStyleOptionGraphicsItem, widget=None):\n super().paint(painter, QStyleOptionGraphicsItem, widget)\n\n offset = 24.0\n if self.node.isDirty(): offset = 0.0\n if self.node.isInvalid(): offset = 48.0\n\n painter.drawImage(\n QRectF(-10, -10, 24.0, 24.0),\n self.icons,\n QRectF(offset, 0, 24.0, 24.0)\n )\n\n\n@register_node(OP_NODE_NUM_SLID)\nclass NumberSliderNode(Node):\n icon = os.path.join(App.getUserAppDataDir(), \"Macro\", \"pyqt-node-editor\", \"examples\",\n \"example_freecad\", \"icons\", \"freecad_default_icon.png\")\n op_code = OP_NODE_NUM_SLID\n op_title = \"Number Slider\"\n content_label_objname = \"number_slider_node\"\n\n GraphicsNode_class = NumberSliderGraphicsNode\n NodeContent_class = NumberSliderContent\n\n def __init__(self, scene):\n super().__init__(scene, self.__class__.op_title, inputs=[], outputs=[(0, \"\")])\n self.value = None\n self.markDirty()\n self.eval()\n\n def initSettings(self):\n super().initSettings()\n self.input_socket_position = LEFT_CENTER\n self.output_socket_position = RIGHT_CENTER\n\n def initInnerClasses(self):\n self.content = NumberSliderContent(self)\n self.grNode = NumberSliderGraphicsNode(self)\n self.content.slider.valueChanged.connect(self.onInputChanged)\n\n def eval(self):\n if not self.isDirty() and not self.isInvalid():\n print(\" _> returning cached %s value:\" % self.__class__.__name__, self.value)\n return self.value\n try:\n val = self.evalImplementation()\n return val\n except ValueError as e:\n self.markInvalid()\n self.grNode.setToolTip(str(e))\n self.markDescendantsDirty()\n except Exception as e:\n self.markInvalid()\n self.grNode.setToolTip(str(e))\n dumpException(e)\n\n def evalImplementation(self):\n slider_value = self.content.slider.value()\n self.value = slider_value/100\n self.content.lbl.setText(str(self.value))\n self.markDirty(False)\n self.markInvalid(False)\n self.markDescendantsInvalid(False)\n self.markDescendantsDirty()\n self.grNode.setToolTip(\"\")\n self.evalChildren()\n print(\"%s::__eval()\" % self.__class__.__name__, \"self.value = \", self.value)\n return self.value\n\n def evalOperation(self):\n pass\n\n def onInputChanged(self, socket=None):\n self.markDirty()\n self.eval()\n print(\"%s::__onInputChanged\" % self.__class__.__name__, \"self.value = \", self.value)\n\n def serialize(self):\n res = super().serialize()\n res['op_code'] = self.__class__.op_code\n return res\n\n def deserialize(self, data, hashmap={}, restore_id=True):\n res = super().deserialize(data, hashmap, restore_id)\n #print(\"Deserialized Node '%s'\" % self.__class__.__name__, \"res:\", res)\n return res","repo_name":"LorainePan/pyqt-node-editor","sub_path":"examples/example_freecad/nodes/number_slider.py","file_name":"number_slider.py","file_ext":"py","file_size_in_byte":5173,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"4311593148","text":"import json\nimport sys\n\nclass Config:\n def __init__(self, filepath: str):\n self.filepath = filepath\n\n try:\n with open(filepath, \"r\") as f:\n self.__dict__.update(json.load(f))\n except:\n print(\"Unable to open config file! {path}\".format(path=self.filepath))\n sys.exit(1)\n","repo_name":"ballofcthulu/rudy","sub_path":"rudy/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"6207489075","text":"#!/usr/bin/evn python3\n\nimport argparse\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('action', type=str)\nparser.add_argument('-n', '--name', type=str, default='first')\nparser.add_argument('-c', '--count', type=int, default=5)\n\n\nargs = parser.parse_args()\n\nstudent = {'first': 1,\n 'second': 2,\n 'third': 3\n }\n\n\ndef find(name):\n \"\"\"function for finding a number by name\n Args:\n name (str): student name\n Returns:\n print number the student and new list\n \"\"\"\n print(student[name],'- with 100')\n\n\ndef set(name, count):\n \"\"\"function to set any number by name\n Args:\n name (str): student name\n count (int): student number\n Returns:\n print action and new list\n \"\"\"\n count = int(count)\n print(student[name], '=>', count)\n student[name] = count\n\n\ndef add(name, count):\n \"\"\"function to adds any number to number by name\n Args:\n name (str): student name\n count (int): student number\n Returns:\n print action and new list\n \"\"\"\n count = int(count)\n print(student[name], '+', count,'=', student[name]+count)\n student[name] += count\n\n\nif args.action == 'find':\n find(args.name)\nelif args.action == 'set':\n set(args.name, args.count)\nelif args.action == 'add':\n add(args.name, args.count)\nelif args.action != 'print':\n print('Not corect action')\n\nprint('list:', student)\n","repo_name":"kpi-keoa/kpi-python-course","sub_path":"dk91_tusiac/lab1/lab1.py","file_name":"lab1.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"70246255610","text":"import numpy as np\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data import Dataset\nfrom torch.utils.data.dataset import T_co\nfrom torchvision import transforms\nfrom torchvision.io import read_image\n\n\nclass SingleImageDataset(Dataset):\n def __init__(self, image_path, alpha=False):\n super().__init__()\n\n to_pil = transforms.ToPILImage()\n to_tensor = transforms.ToTensor()\n\n self.image = read_image(image_path)\n self.image = to_pil(self.image)\n self.image = to_tensor(self.image)\n self.alpha = alpha\n\n def __len__(self):\n return self.image.shape[1] * self.image.shape[2]\n\n def __getitem__(self, index) -> T_co:\n height = self.image.shape[1]\n width = self.image.shape[2]\n\n x = index // width\n y = index % width\n\n r = self.image[0, y, x]\n g = self.image[1, y, x]\n b = self.image[2, y, x]\n a = self.image[3, y, x] if self.alpha else 1.0\n\n return np.array([float(x / width), float(y / height)]), np.array([r, g, b, a] if self.alpha else [r, g, b])\n\n\nif __name__ == '__main__':\n test_dataset = SingleImageDataset('/Users/allanpichardo/sites/cppn-generator/test_image.png')\n test_dataloader = DataLoader(test_dataset, batch_size=64, shuffle=True)\n\n train_features, train_labels = next(iter(test_dataloader))\n print(f\"Feature batch shape: {train_features.shape}\")\n print(f\"Labels batch shape: {train_labels.shape}\")\n\n for x, y in zip(train_features, train_labels):\n print(\"Pixel {},{} | Color {},{},{}\".format(x[0], x[1], y[0], y[1], y[2]))","repo_name":"allanpichardo/cppn-generator","sub_path":"datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"25958198112","text":"#!/var/www/flask-apps/bin/python3\n\nimport sys, os, time\nimport requests\nimport json\nimport urllib3\nimport yaml, base64\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n\nimport PyU4V\n\n\nwith open('/usr/local/StorageOps/etc/endpoints.yaml') as info:\n endpoints = yaml.load(info)\n\ndef get_credentials(token):\n p = endpoints[token]['password']\n u = endpoints[token]['username']\n udecoded = base64.b64decode(u.encode('utf-8')).decode('utf-8')\n pdecoded = base64.b64decode(p.encode('utf-8')).decode('utf-8')\n return [udecoded,pdecoded]\n\nend_date = int(round(time.time() * 1000))\nstart_date = end_date - 3600000\n\n\ndef GetFEPerf(unisphere,port,symid,username,password):\n conn = PyU4V.U4VConn(username=username,password=password,server_ip=unisphere,\n port=port,verify=False,array_id=symid)\n array_list = conn.common.get_array_list()\n FEutilization = dict()\n for array in array_list:\n conn.set_array_id(array)\n if array not in FEutilization:\n FEutilization[array] = dict()\n print(\"Begin collection for: \" + array)\n #\n # 1492 gives me a key error???\n #\n try:\n port_list = conn.performance.get_fe_port_list()\n except:\n port_list = dict()\n directors = dict()\n for port in port_list:\n for feport,director in port.items():\n if director not in directors:\n directors[director] = list() \n directors[director].append(feport)\n for director in sorted(directors.keys()):\n #print(\"\\t\" + director)\n if director not in FEutilization[array]:\n FEutilization[array][director] = dict() \n for port in directors[director]:\n #print(\"\\t\\t\" + port)\n if port not in FEutilization[array][director]:\n FEutilization[array][director][port] = list()\n port_metrics = conn.performance.get_fe_port_util_last4hrs(director,port)\n results = port_metrics[0]['resultList']['result']\n for result in results:\n FEutilization[array][director][port].append(result)\n\n \n feperf_json = '/usr/local/StorageOps/data/symmperf/FE_Perf.json'\n with open(feperf_json, \"w\") as write_file:\n json.dump(FEutilization, write_file)\n\n\n\n\n\ndef main():\n unispheres = dict()\n symid = dict()\n unispheres['IP_Addr'] = 'PORT#'\n # Have to provide a valid symid when connecting to unisphere\n symid['IP_Addr'] = 'SID'\n cred = get_credentials('unisphere')\n for unisphere,port in unispheres.items():\n GetFEPerf(unisphere,port,symid[unisphere],cred[0],cred[1])\n\n\n\n# Boiler plate call to main()\nif __name__ == '__main__':\n main()\n\nsys.exit()\n\n","repo_name":"NuisanceLevel7/Storage-Scripts","sub_path":"vmax_fe_utilization.py","file_name":"vmax_fe_utilization.py","file_ext":"py","file_size_in_byte":2819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"2020181210","text":"import os\nimport sys\nimport time\nimport argparse\nimport json\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport nvdiffrast.torch as dr\n\nimport src.renderutils as ru\nfrom src import obj\nfrom src import util\nfrom src import mesh\nfrom src import texture\nfrom src import render\nfrom src import regularizer\nfrom src.mesh import Mesh\n\nRADIUS = 3.5\n\n# Enable to debug back-prop anomalies\n# torch.autograd.set_detect_anomaly(True)\n\n###############################################################################\n# Utility mesh loader\n###############################################################################\n\ndef load_mesh(filename, mtl_override=None):\n name, ext = os.path.splitext(filename)\n if ext == \".obj\":\n return obj.load_obj(filename, clear_ks=True, mtl_override=mtl_override)\n assert False, \"Invalid mesh file extension\"\n\n###############################################################################\n# Loss setup\n###############################################################################\n\ndef createLoss(FLAGS):\n if FLAGS.loss == \"smape\":\n return lambda img, ref: ru.image_loss(img, ref, loss='smape', tonemapper='none')\n elif FLAGS.loss == \"mse\":\n return lambda img, ref: ru.image_loss(img, ref, loss='mse', tonemapper='none')\n elif FLAGS.loss == \"logl1\":\n return lambda img, ref: ru.image_loss(img, ref, loss='l1', tonemapper='log_srgb')\n elif FLAGS.loss == \"logl2\":\n return lambda img, ref: ru.image_loss(img, ref, loss='mse', tonemapper='log_srgb')\n elif FLAGS.loss == \"relativel2\":\n return lambda img, ref: ru.image_loss(img, ref, loss='relmse', tonemapper='none')\n else:\n assert False\n\n###############################################################################\n# Main shape fitter function / optimization loop\n###############################################################################\n\ndef optimize_mesh(\n FLAGS,\n out_dir, \n log_interval=10,\n mesh_scale=2.0\n ):\n\n os.makedirs(out_dir, exist_ok=True)\n os.makedirs(os.path.join(out_dir, \"mesh\"), exist_ok=True)\n\n # Projection matrix\n proj_mtx = util.projection(x=0.4, f=1000.0)\n\n # Guess learning rate if not specified\n if FLAGS.learning_rate is None:\n FLAGS.learning_rate = 0.01\n\n # Reference mesh\n ref_mesh = load_mesh(FLAGS.ref_mesh, FLAGS.mtl_override)\n print(\"Ref mesh has %d triangles and %d vertices.\" % (ref_mesh.t_pos_idx.shape[0], ref_mesh.v_pos.shape[0]))\n\n # Check if the training texture resolution is acceptable\n ref_texture_res = np.maximum(ref_mesh.material['kd'].getRes(), ref_mesh.material['ks'].getRes())\n if 'normal' in ref_mesh.material:\n ref_texture_res = np.maximum(ref_texture_res, ref_mesh.material['normal'].getRes())\n if FLAGS.texture_res[0] < ref_texture_res[0] or FLAGS.texture_res[1] < ref_texture_res[1]:\n print(\"---> WARNING: Picked a texture resolution lower than the reference mesh [%d, %d] < [%d, %d]\" % (FLAGS.texture_res[0], FLAGS.texture_res[1], ref_texture_res[0], ref_texture_res[1]))\n\n # Base mesh\n base_mesh = load_mesh(FLAGS.base_mesh)\n print(\"Base mesh has %d triangles and %d vertices.\" % (base_mesh.t_pos_idx.shape[0], base_mesh.v_pos.shape[0]))\n print(\"Avg edge length: %f\" % regularizer.avg_edge_length(base_mesh))\n\n # Create normalized size versions of the base and reference meshes. Normalized base_mesh is important as it makes it easier to configure learning rate.\n normalized_base_mesh = mesh.unit_size(base_mesh)\n normalized_ref_mesh = mesh.unit_size(ref_mesh)\n\n assert not FLAGS.random_train_res or FLAGS.custom_mip, \"Random training resolution requires custom mip.\"\n\n # ==============================================================================================\n # Initialize weights / variables for trainable mesh\n # ==============================================================================================\n trainable_list = [] \n\n v_pos_opt = normalized_base_mesh.v_pos.clone().detach().requires_grad_(True)\n\n # Trainable normal map, initialize to (0,0,1) & make sure normals are always in positive hemisphere\n if FLAGS.random_textures:\n normal_map_opt = texture.create_trainable(np.array([0, 0, 1]), FLAGS.texture_res, not FLAGS.custom_mip)\n else:\n if 'normal' not in ref_mesh.material:\n normal_map_opt = texture.create_trainable(np.array([0, 0, 1]), FLAGS.texture_res, not FLAGS.custom_mip)\n else:\n normal_map_opt = texture.create_trainable(ref_mesh.material['normal'], FLAGS.texture_res, not FLAGS.custom_mip)\n\n # Setup Kd, Ks albedo and specular textures\n if FLAGS.random_textures:\n if FLAGS.layers > 1:\n kd_map_opt = texture.create_trainable(np.random.uniform(size=FLAGS.texture_res + [4], low=0.0, high=1.0), FLAGS.texture_res, not FLAGS.custom_mip)\n else:\n kd_map_opt = texture.create_trainable(np.random.uniform(size=FLAGS.texture_res + [3], low=0.0, high=1.0), FLAGS.texture_res, not FLAGS.custom_mip)\n\n ksR = np.random.uniform(size=FLAGS.texture_res + [1], low=0.0, high=0.01)\n ksG = np.random.uniform(size=FLAGS.texture_res + [1], low=FLAGS.min_roughness, high=1.0)\n ksB = np.random.uniform(size=FLAGS.texture_res + [1], low=0.0, high=1.0)\n ks_map_opt = texture.create_trainable(np.concatenate((ksR, ksG, ksB), axis=2), FLAGS.texture_res, not FLAGS.custom_mip)\n else:\n kd_map_opt = texture.create_trainable(ref_mesh.material['kd'], FLAGS.texture_res, not FLAGS.custom_mip)\n ks_map_opt = texture.create_trainable(ref_mesh.material['ks'], FLAGS.texture_res, not FLAGS.custom_mip)\n\n # Trainable displacement map\n displacement_map_var = None\n if FLAGS.subdivision > 0:\n displacement_map_var = torch.tensor(np.zeros(FLAGS.texture_res + [1], dtype=np.float32), dtype=torch.float32, device='cuda', requires_grad=True)\n\n # Add trainable arguments according to config\n if not 'position' in FLAGS.skip_train:\n trainable_list += [v_pos_opt] \n if not 'normal' in FLAGS.skip_train:\n trainable_list += normal_map_opt.getMips()\n if not 'kd' in FLAGS.skip_train:\n trainable_list += kd_map_opt.getMips()\n if not 'ks' in FLAGS.skip_train:\n trainable_list += ks_map_opt.getMips()\n if not 'displacement' in FLAGS.skip_train and displacement_map_var is not None:\n trainable_list += [displacement_map_var]\n\n # ==============================================================================================\n # Setup material for optimized mesh\n # ==============================================================================================\n\n opt_material = {\n 'bsdf' : ref_mesh.material['bsdf'],\n 'kd' : kd_map_opt,\n 'ks' : ks_map_opt,\n 'normal' : normal_map_opt\n }\n\n # ==============================================================================================\n # Setup reference mesh. Compute tangentspace and animate with skinning\n # ==============================================================================================\n\n render_ref_mesh = mesh.compute_tangents(ref_mesh)\n \n # Compute AABB of reference mesh. Used for centering during rendering TODO: Use pre frame AABB?\n ref_mesh_aabb = mesh.aabb(render_ref_mesh.eval())\n\n # ==============================================================================================\n # Setup base mesh operation graph, precomputes topology etc.\n # ==============================================================================================\n\n # Create optimized mesh with trainable positions \n opt_base_mesh = Mesh(v_pos_opt, normalized_base_mesh.t_pos_idx, material=opt_material, base=normalized_base_mesh)\n\n # Scale from [-1, 1] local coordinate space to match extents of the reference mesh\n opt_base_mesh = mesh.align_with_reference(opt_base_mesh, ref_mesh)\n\n # Compute smooth vertex normals\n opt_base_mesh = mesh.auto_normals(opt_base_mesh)\n\n # Set up tangent space\n opt_base_mesh = mesh.compute_tangents(opt_base_mesh)\n\n # Subdivide if we're doing displacement mapping\n if FLAGS.subdivision > 0:\n # Subdivide & displace optimized mesh\n subdiv_opt_mesh = mesh.subdivide(opt_base_mesh, steps=FLAGS.subdivision)\n opt_detail_mesh = mesh.displace(subdiv_opt_mesh, displacement_map_var, FLAGS.displacement, keep_connectivity=True)\n else:\n opt_detail_mesh = opt_base_mesh\n\n # Laplace regularizer\n if FLAGS.relative_laplacian:\n with torch.no_grad():\n orig_opt_base_mesh = opt_base_mesh.eval().clone()\n lap_loss_fn = regularizer.laplace_regularizer_const(opt_detail_mesh, orig_opt_base_mesh)\n else:\n lap_loss_fn = regularizer.laplace_regularizer_const(opt_detail_mesh)\n\n # ==============================================================================================\n # Setup torch optimizer\n # ==============================================================================================\n\n optimizer = torch.optim.Adam(trainable_list, lr=FLAGS.learning_rate)\n\n scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda x: max(0.0, 10**(-x*0.0002))) \n\n # ==============================================================================================\n # Image loss\n # ==============================================================================================\n image_loss_fn = createLoss(FLAGS)\n\n # Background color\n if FLAGS.background == 'checker':\n background = torch.tensor(util.checkerboard(FLAGS.display_res, 8), dtype=torch.float32, device='cuda')\n elif FLAGS.background == 'white':\n background = torch.ones((1, FLAGS.display_res, FLAGS.display_res, 3), dtype=torch.float32, device='cuda')\n else:\n background = None\n\n # ==============================================================================================\n # Training loop\n # ==============================================================================================\n img_cnt = 0\n ang = 0.0\n img_loss_vec = []\n lap_loss_vec = []\n iter_dur_vec = []\n glctx = dr.RasterizeGLContext()\n for it in range(FLAGS.iter+1):\n # ==============================================================================================\n # Display / save outputs. Do it before training so we get initial meshes\n # ==============================================================================================\n\n # Show/save image before training step (want to get correct rendering of input)\n display_image = FLAGS.display_interval and (it % FLAGS.display_interval == 0)\n save_image = FLAGS.save_interval and (it % FLAGS.save_interval == 0)\n if display_image or save_image:\n eye = np.array(FLAGS.camera_eye)\n up = np.array(FLAGS.camera_up)\n at = np.array([0,0,0])\n a_mv = util.lookAt(eye, at, up)\n a_mvp = np.matmul(proj_mtx, a_mv).astype(np.float32)[None, ...]\n a_lightpos = np.linalg.inv(a_mv)[None, :3, 3]\n a_campos = np.linalg.inv(a_mv)[None, :3, 3]\n\n params = {'mvp' : a_mvp, 'lightpos' : a_lightpos, 'campos' : a_campos, 'resolution' : [FLAGS.display_res, FLAGS.display_res], \n 'time' : 0}\n\n # Render images, don't need to track any gradients\n with torch.no_grad():\n # Center meshes\n _opt_detail = mesh.center_by_reference(opt_detail_mesh.eval(params), ref_mesh_aabb, mesh_scale)\n _opt_ref = mesh.center_by_reference(render_ref_mesh.eval(params), ref_mesh_aabb, mesh_scale)\n\n # Render\n if FLAGS.subdivision > 0:\n _opt_base = mesh.center_by_reference(opt_base_mesh.eval(params), ref_mesh_aabb, mesh_scale)\n img_base = render.render_mesh(glctx, _opt_base, a_mvp, a_campos, a_lightpos, FLAGS.light_power, FLAGS.display_res, \n num_layers=FLAGS.layers, background=background, min_roughness=FLAGS.min_roughness)\n img_base = util.scale_img_nhwc(img_base, [FLAGS.display_res, FLAGS.display_res])\n\n img_opt = render.render_mesh(glctx, _opt_detail, a_mvp, a_campos, a_lightpos, FLAGS.light_power, FLAGS.display_res, \n num_layers=FLAGS.layers, background=background, min_roughness=FLAGS.min_roughness)\n img_ref = render.render_mesh(glctx, _opt_ref, a_mvp, a_campos, a_lightpos, FLAGS.light_power, FLAGS.display_res, \n num_layers=1, spp=FLAGS.spp, background=background, min_roughness=FLAGS.min_roughness)\n\n # Rescale\n img_opt = util.scale_img_nhwc(img_opt, [FLAGS.display_res, FLAGS.display_res])\n img_ref = util.scale_img_nhwc(img_ref, [FLAGS.display_res, FLAGS.display_res])\n\n if FLAGS.subdivision > 0:\n img_disp = torch.clamp(torch.abs(displacement_map_var[None, ...]), min=0.0, max=1.0).repeat(1,1,1,3)\n img_disp = util.scale_img_nhwc(img_disp, [FLAGS.display_res, FLAGS.display_res])\n result_image = torch.cat([img_base, img_opt, img_ref], axis=2)\n else:\n result_image = torch.cat([img_opt, img_ref], axis=2)\n\n result_image[0] = util.tonemap_srgb(result_image[0])\n np_result_image = result_image[0].detach().cpu().numpy()\n if display_image:\n util.display_image(np_result_image, size=FLAGS.display_res, title='%d / %d' % (it, FLAGS.iter))\n if save_image:\n util.save_image(out_dir + '/' + ('img_%06d.png' % img_cnt), np_result_image)\n img_cnt = img_cnt+1\n\n # ==============================================================================================\n # Initialize training\n # ==============================================================================================\n\n iter_start_time = time.time()\n img_loss = torch.zeros([1], dtype=torch.float32, device='cuda')\n lap_loss = torch.zeros([1], dtype=torch.float32, device='cuda')\n\n iter_res = FLAGS.train_res\n iter_spp = FLAGS.spp\n if FLAGS.random_train_res:\n # Random resolution, 16x16 -> train_res. Scale up sample count so we always land close to train_res*samples_per_pixel samples\n iter_res = np.random.randint(16, FLAGS.train_res+1)\n iter_spp = FLAGS.spp * (FLAGS.train_res // iter_res)\n\n mvp = np.zeros((FLAGS.batch, 4,4), dtype=np.float32)\n campos = np.zeros((FLAGS.batch, 3), dtype=np.float32)\n lightpos = np.zeros((FLAGS.batch, 3), dtype=np.float32)\n\n # ==============================================================================================\n # Build transform stack for minibatching\n # ==============================================================================================\n for b in range(FLAGS.batch):\n # Random rotation/translation matrix for optimization.\n r_rot = util.random_rotation_translation(0.25)\n r_mv = np.matmul(util.translate(0, 0, -RADIUS), r_rot)\n mvp[b] = np.matmul(proj_mtx, r_mv).astype(np.float32)\n campos[b] = np.linalg.inv(r_mv)[:3, 3]\n lightpos[b] = util.cosine_sample(campos[b])*RADIUS\n\n\n params = {'mvp' : mvp, 'lightpos' : lightpos, 'campos' : campos, 'resolution' : [iter_res, iter_res], 'time' : 0}\n\n # Random bg color\n randomBgColor = torch.rand(FLAGS.batch, iter_res, iter_res, 3, dtype=torch.float32, device='cuda')\n\n # ==============================================================================================\n # Evaluate all mesh ops (may change when positions are modified etc) and center/align meshes\n # ==============================================================================================\n _opt_ref = mesh.center_by_reference(render_ref_mesh.eval(params), ref_mesh_aabb, mesh_scale)\n _opt_detail = mesh.center_by_reference(opt_detail_mesh.eval(params), ref_mesh_aabb, mesh_scale)\n\n # ==============================================================================================\n # Render reference mesh\n # ==============================================================================================\n with torch.no_grad():\n color_ref = render.render_mesh(glctx, _opt_ref, mvp, campos, lightpos, FLAGS.light_power, iter_res, \n spp=iter_spp, num_layers=1, background=randomBgColor, min_roughness=FLAGS.min_roughness)\n\n # ==============================================================================================\n # Render the trainable mesh\n # ==============================================================================================\n color_opt = render.render_mesh(glctx, _opt_detail, mvp, campos, lightpos, FLAGS.light_power, iter_res, \n spp=iter_spp, num_layers=FLAGS.layers, msaa=True , background=randomBgColor, \n min_roughness=FLAGS.min_roughness)\n\n # ==============================================================================================\n # Compute loss\n # ==============================================================================================\n # Image-space loss\n img_loss = image_loss_fn(color_opt, color_ref)\n\n # Compute laplace loss\n lap_loss = lap_loss_fn.eval(params)\n\n # Debug, store every training iteration\n # result_image = torch.cat([color_opt, color_ref], axis=2)\n # np_result_image = result_image[0].detach().cpu().numpy()\n # util.save_image(out_dir + '/' + ('train_%06d.png' % it), np_result_image)\n\n # Log losses\n img_loss_vec.append(img_loss.item())\n lap_loss_vec.append(lap_loss.item())\n\n # Schedule for laplacian loss weight\n if it == 0:\n if FLAGS.laplacian_factor is not None:\n lap_fac = FLAGS.laplacian_factor\n else:\n ratio = 0.1 / lap_loss.item() # Hack that assumes RMSE ~= 0.1\n lap_fac = ratio * 0.25\n min_lap_fac = lap_fac * 0.02\n else:\n lap_fac = (lap_fac - min_lap_fac) * 10**(-it*0.000001) + min_lap_fac\n\n # Compute total aggregate loss\n total_loss = img_loss + lap_loss * lap_fac\n\n # ==============================================================================================\n # Backpropagate\n # ==============================================================================================\n\n optimizer.zero_grad()\n total_loss.backward()\n optimizer.step()\n scheduler.step()\n\n # ==============================================================================================\n # Clamp trainables to reasonable range\n # ==============================================================================================\n\n normal_map_opt.clamp_(min=-1, max=1)\n kd_map_opt.clamp_(min=0, max=1)\n ks_map_opt.clamp_rgb_(minR=0, maxR=1, minG=FLAGS.min_roughness, maxG=1.0, minB=0.0, maxB=1.0)\n\n iter_dur_vec.append(time.time() - iter_start_time)\n\n # ==============================================================================================\n # Log & save outputs\n # ==============================================================================================\n\n # Print/save log.\n if log_interval and (it % log_interval == 0):\n img_loss_avg = np.mean(np.asarray(img_loss_vec[-log_interval:]))\n lap_loss_avg = np.mean(np.asarray(lap_loss_vec[-log_interval:]))\n iter_dur_avg = np.mean(np.asarray(iter_dur_vec[-log_interval:]))\n \n remaining_time = (FLAGS.iter-it)*iter_dur_avg\n print(\"iter=%5d, img_loss=%.6f, lap_loss=%.6f, lr=%.5f, time=%.1f ms, rem=%s\" % \n (it, img_loss_avg, lap_loss_avg*lap_fac, optimizer.param_groups[0]['lr'], iter_dur_avg*1000, util.time_to_text(remaining_time)))\n\n # Save final mesh to file\n obj.write_obj(os.path.join(out_dir, \"mesh/\"), opt_base_mesh.eval())\n\n#----------------------------------------------------------------------------\n# Main function.\n#----------------------------------------------------------------------------\n\ndef main():\n parser = argparse.ArgumentParser(description='diffmodeling')\n parser.add_argument('-i', '--iter', type=int, default=5000)\n parser.add_argument('-b', '--batch', type=int, default=1)\n parser.add_argument('-s', '--spp', type=int, default=1)\n parser.add_argument('-l', '--layers', type=int, default=1)\n parser.add_argument('-r', '--train-res', type=int, default=512)\n parser.add_argument('-rtr', '--random-train-res', action='store_true', default=False)\n parser.add_argument('-dr', '--display-res', type=int, default=None)\n parser.add_argument('-tr', '--texture-res', nargs=2, type=int, default=[1024, 1024])\n parser.add_argument('-di', '--display-interval', type=int, default=0)\n parser.add_argument('-si', '--save-interval', type=int, default=1000)\n parser.add_argument('-lr', '--learning-rate', type=float, default=None)\n parser.add_argument('-lp', '--light-power', type=float, default=5.0)\n parser.add_argument('-mr', '--min-roughness', type=float, default=0.08)\n parser.add_argument('-sd', '--subdivision', type=int, default=0)\n parser.add_argument('-mip', '--custom-mip', action='store_true', default=False)\n parser.add_argument('-rt', '--random-textures', action='store_true', default=False)\n parser.add_argument('-lf', '--laplacian-factor', type=float, default=None)\n parser.add_argument('-rl', '--relative-laplacian', type=bool, default=False)\n parser.add_argument('-bg', '--background', default='checker', choices=['black', 'white', 'checker'])\n parser.add_argument('--loss', default='logl1', choices=['logl1', 'logl2', 'mse', 'smape', 'relativel2'])\n parser.add_argument('-o', '--out-dir', type=str, default=None)\n parser.add_argument('--config', type=str, default=None, help='Config file')\n parser.add_argument('-rm', '--ref_mesh', type=str)\n parser.add_argument('-bm', '--base-mesh', type=str)\n \n FLAGS = parser.parse_args()\n\n FLAGS.camera_eye = [0.0, 0.0, RADIUS]\n FLAGS.camera_up = [0.0, 1.0, 0.0]\n FLAGS.skip_train = []\n FLAGS.displacement = 0.15\n FLAGS.mtl_override = None\n\n if FLAGS.config is not None:\n with open(FLAGS.config) as f:\n data = json.load(f)\n for key in data:\n print(key, data[key])\n FLAGS.__dict__[key] = data[key]\n\n if FLAGS.display_res is None:\n FLAGS.display_res = FLAGS.train_res\n if FLAGS.out_dir is None:\n out_dir = 'out/cube_%d' % (FLAGS.train_res)\n else:\n out_dir = 'out/' + FLAGS.out_dir\n\n optimize_mesh(FLAGS, out_dir)\n\n#----------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n main()\n\n#----------------------------------------------------------------------------\n","repo_name":"NVlabs/nvdiffmodeling","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":23343,"program_lang":"python","lang":"en","doc_type":"code","stars":419,"dataset":"github-code","pt":"77"}
+{"seq_id":"17384038267","text":"import sys\n\nn = int(input())\nl = list(map(int,sys.stdin.readline().split()))\nl.sort()\nleft, right = 0, len(l) - 1\nzero = sys.maxsize\nzl = [0,1]\nwhile left 0:\n if temp < zero:\n zero = temp\n zl[0], zl[1] = left, right\n right -=1\n else:\n if abs(temp) < zero:\n zero = abs(temp)\n zl[0], zl[1] = left, right\n left += 1\nprint(l[zl[0]],l[zl[1]])","repo_name":"galug/algorithm","sub_path":"python_algorithm/2467.py","file_name":"2467.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"29421583879","text":"# completa el código de la función\ndef amigos(a,b):\n lista1=[]\n lista2=[]\n acum1=0\n acum2=0\n amigo=0\n \n for i in range(1,a):\n if a%i==0:\n lista1.append(i)\n\n for i in range(1,b):\n if b%i==0:\n lista2.append(i)\n \n for e in lista1:\n acum1+=e\n\n for x in lista2:\n acum2+=x\n\n if acum1==b and acum2==a:\n amigo=True\n\n else:\n amigo=False\n \n \n return amigo","repo_name":"pabloschwarzenberg/grader","sub_path":"tema2_ej2/tema2_ej2_c015da74cfd6562a4a7693483516a92b.py","file_name":"tema2_ej2_c015da74cfd6562a4a7693483516a92b.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"10816661553","text":"import googleapiclient.discovery\nimport pymongo\nfrom pymongo import MongoClient\nimport mysql\nfrom config import API_KEY\nimport streamlit as st\nimport mysql.connector\nimport matplotlib.pyplot as plt\nfrom bson.objectid import ObjectId\nfrom pymongo.errors import DuplicateKeyError\nfrom datetime import datetime\nfrom dateutil import parser as date_parser\n\napi_service_name = \"youtube\"\napi_version = \"v3\"\n\nyoutube = googleapiclient.discovery.build(api_service_name, api_version, developerKey=API_KEY)\n\nmyclient = MongoClient(\"mongodb://localhost:27017/\")\nmydatabase = myclient[\"youtube\"]\nmycollection = mydatabase[\"details\"]\n\ndef get_channel_data(channel_id):\n response = youtube.channels().list(part='snippet,statistics', id=channel_id).execute()\n channel_data = response['items'][0]\n\n channel_title = channel_data['snippet']['title']\n channel_subscribers = int(channel_data['statistics']['subscriberCount'])\n channel_views = int(channel_data['statistics']['viewCount'])\n channel_description = channel_data['snippet']['description']\n\n return {\n \"Channel_Name\": {\n \"Channel_Name\": channel_title,\n \"Channel_Id\": channel_id,\n \"Subscription_Count\": channel_subscribers,\n \"Channel_Views\": channel_views,\n \"Channel_Description\": channel_description,\n \"Playlist_Id\": None\n }\n }\n\ndef get_playlist_data(channel_id):\n playlist_response = youtube.playlists().list(part='snippet', channelId=channel_id, maxResults=5).execute()\n playlists = playlist_response['items']\n\n # while 'nextPageToken' in playlist_response:\n # next_page_token = playlist_response['nextPageToken']\n # playlist_response = youtube.playlists().list(part='snippet', channelId=channel_id, maxResults=5, pageToken=next_page_token).execute()\n # playlists.extend(playlist_response['items'])\n\n return playlists\n\ndef get_video_data(channel_id):\n video_response = youtube.search().list(part='snippet', channelId=channel_id, type='video', maxResults=5).execute()\n videos = video_response['items']\n\n # while 'nextPageToken' in video_response:\n # next_page_token = video_response['nextPageToken']\n # video_response = youtube.search().list(part='snippet', channelId=channel_id, type='video', maxResults=5, pageToken=next_page_token).execute()\n # videos.extend(video_response['items'])\n\n \n for video in videos:\n video_id = video[\"id\"][\"videoId\"]\n video_details_response = youtube.videos().list(part='snippet,statistics,contentDetails', id=video_id).execute()\n video_details = video_details_response['items'][0]\n \n snippet = video_details.get('snippet', {})\n statistics = video_details.get('statistics', {})\n content_details = video_details.get('contentDetails', {})\n \n video[\"snippet\"][\"title\"] = snippet.get(\"title\", \"Title Not Available\")\n video[\"snippet\"][\"description\"] = snippet.get(\"description\", \"Description Not Available\")\n video[\"snippet\"][\"publishedAt\"] = snippet.get(\"publishedAt\", \"Published Date Not Available\")\n video[\"snippet\"][\"tags\"] = snippet.get(\"tags\", [])\n \n video[\"statistics\"] = {\n \"viewCount\": int(statistics.get(\"viewCount\", 0)),\n \"likeCount\": int(statistics.get(\"likeCount\", 0)),\n \"dislikeCount\": int(statistics.get(\"dislikeCount\", 0)),\n \"favoriteCount\": int(statistics.get(\"favoriteCount\", 0)),\n \"commentCount\": int(statistics.get(\"commentCount\", 0))\n }\n \n video[\"contentDetails\"] = {\n \"duration\": content_details.get(\"duration\", \"Duration Not Available\"),\n \"caption\": content_details.get(\"caption\", \"Not Available\")\n }\n\n return videos\n\ndef create_mysql_connection():\n connection = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n password=\"12345\",\n database=\"project11\"\n )\n cursor = connection.cursor()\n\n create_channels_table = \"\"\"\n CREATE TABLE IF NOT EXISTS channels (\n id INT AUTO_INCREMENT PRIMARY KEY,\n channel_id VARCHAR(255) UNIQUE,\n channel_name VARCHAR(255),\n subscription_count INT,\n channel_views BIGINT,\n channel_description TEXT\n ) ENGINE=InnoDB\n \"\"\"\n cursor.execute(create_channels_table)\n\n create_playlists_table = \"\"\"\n CREATE TABLE IF NOT EXISTS playlists (\n id INT AUTO_INCREMENT PRIMARY KEY,\n channel_id VARCHAR(255),\n playlist_id VARCHAR(255) UNIQUE,\n playlist_title VARCHAR(255)\n ) ENGINE=InnoDB\n \"\"\"\n cursor.execute(create_playlists_table)\n\n create_comments_table = \"\"\"\n CREATE TABLE IF NOT EXISTS comments (\n id INT AUTO_INCREMENT PRIMARY KEY,\n video_id VARCHAR(255),\n comment_text TEXT,\n comment_author VARCHAR(255),\n comment_date DATETIME\n ) ENGINE=InnoDB\n \"\"\"\n cursor.execute(create_comments_table)\n \n create_videos_table = \"\"\"\n CREATE TABLE IF NOT EXISTS videos (\n id INT AUTO_INCREMENT PRIMARY KEY,\n channel_id VARCHAR(255), \n video_id VARCHAR(255) UNIQUE,\n video_title VARCHAR(255),\n video_description TEXT,\n tags TEXT,\n published_at DATETIME,\n view_count INT,\n like_count INT,\n dislike_count INT,\n favorite_count INT,\n comment_count INT,\n duration VARCHAR(50),\n thumbnail TEXT,\n caption_status VARCHAR(50)\n ) ENGINE=InnoDB\n \"\"\"\n\n cursor.execute(create_videos_table)\n\n connection.commit()\n\n return connection, cursor\n\ndef migrate_to_mongodb(channel_data, playlists, videos):\n channel_id = channel_data[\"Channel_Name\"][\"Channel_Id\"]\n existing_channel = mycollection.find_one({\"_id\": channel_id})\n \n if not existing_channel:\n try:\n channel_data[\"_id\"] = channel_id\n mycollection.insert_one(channel_data)\n except DuplicateKeyError:\n # If the _id already exists, update the existing document\n mycollection.update_one({\"_id\": channel_id}, {\"$set\": channel_data})\n else:\n mycollection.update_one({\"_id\": channel_id}, {\"$set\": channel_data})\n\n for playlist in playlists:\n playlist_id = playlist[\"id\"]\n existing_playlist = mycollection.find_one({\"_id\": playlist_id})\n if not existing_playlist:\n try:\n playlist[\"_id\"] = playlist_id\n mycollection.insert_one({\"_id\": playlist_id, \"Playlist\": playlist})\n except DuplicateKeyError:\n # If the _id already exists, update the existing document\n mycollection.update_one({\"_id\": playlist_id}, {\"$set\": {\"Playlist\": playlist}})\n else:\n mycollection.update_one({\"_id\": playlist_id}, {\"$set\": {\"Playlist\": playlist}})\n \n for video in videos:\n video_id = video[\"id\"][\"videoId\"]\n existing_video = mycollection.find_one({\"_id\": video_id})\n if not existing_video:\n try:\n video[\"_id\"] = video_id\n mycollection.insert_one({\"_id\": video_id, \"Video\": video})\n except DuplicateKeyError:\n # If the _id already exists, update the existing document\n mycollection.update_one({\"_id\": video_id}, {\"$set\": {\"Video\": video}})\n else:\n mycollection.update_one({\"_id\": video_id}, {\"$set\": {\"Video\": video}})\n\ndef migrate_to_mysql(channel_data, playlists, videos, connection, cursor):\n channel_id = channel_data[\"Channel_Name\"][\"Channel_Id\"]\n \n existing_channel_sql = f\"\"\"\n SELECT *\n FROM channels\n WHERE channel_id = '{channel_id}'\n \"\"\"\n cursor.execute(existing_channel_sql)\n existing_channel = cursor.fetchone()\n\n if existing_channel:\n # Existing channel, update its attributes\n update_channel_sql = f\"\"\"\n UPDATE channels\n SET channel_name = %s,\n subscription_count = %s,\n channel_views = %s,\n channel_description = %s\n WHERE channel_id = %s\n \"\"\"\n update_channel_values = (\n channel_data[\"Channel_Name\"][\"Channel_Name\"],\n channel_data[\"Channel_Name\"][\"Subscription_Count\"],\n channel_data[\"Channel_Name\"][\"Channel_Views\"],\n channel_data[\"Channel_Name\"][\"Channel_Description\"],\n channel_id\n )\n cursor.execute(update_channel_sql, update_channel_values)\n else:\n # New channel, insert a new record\n channel_sql = \"\"\"\n INSERT INTO channels (channel_id, channel_name, subscription_count, channel_views, channel_description)\n VALUES (%s, %s, %s, %s, %s)\n \"\"\"\n channel_values = (\n channel_id,\n channel_data[\"Channel_Name\"][\"Channel_Name\"],\n channel_data[\"Channel_Name\"][\"Subscription_Count\"],\n int(channel_data[\"Channel_Name\"][\"Channel_Views\"]),\n channel_data[\"Channel_Name\"][\"Channel_Description\"]\n )\n cursor.execute(channel_sql, channel_values)\n\n connection.commit()\n\n for playlist in playlists:\n playlist_id = f\"playlist_{playlist['id']}\"\n \n existing_playlist_sql = f\"\"\"\n SELECT *\n FROM playlists\n WHERE playlist_id = '{playlist_id}'\n \"\"\"\n cursor.execute(existing_playlist_sql)\n existing_playlist = cursor.fetchone()\n\n if existing_playlist:\n # Existing playlist, update its attributes\n update_playlist_sql = f\"\"\"\n UPDATE playlists\n SET playlist_title = %s\n WHERE playlist_id = %s\n \"\"\"\n update_playlist_values = (\n playlist['snippet']['title'],\n playlist_id\n )\n cursor.execute(update_playlist_sql, update_playlist_values)\n else:\n # New playlist, insert a new record\n playlist_sql = \"\"\"\n INSERT INTO playlists (playlist_id, playlist_title)\n VALUES (%s, %s)\n \"\"\"\n playlist_values = (\n playlist_id,\n playlist['snippet']['title']\n )\n cursor.execute(playlist_sql, playlist_values)\n\n connection.commit()\n\n for video in videos:\n video_id = video[\"id\"][\"videoId\"]\n video[\"channel_id\"] = channel_id\n \n existing_video_sql = f\"SELECT * FROM videos WHERE video_id = '{video_id}' AND channel_id = '{channel_id}'\"\n cursor.execute(existing_video_sql)\n existing_video = cursor.fetchone()\n\n if existing_video:\n # Existing video, update its attributes\n update_video_sql = \"\"\"\n UPDATE videos\n SET video_title = %s,\n video_description = %s,\n tags = %s,\n published_at = %s,\n view_count = %s,\n like_count = %s,\n dislike_count = %s,\n favorite_count = %s,\n comment_count = %s,\n duration = %s,\n thumbnail = %s,\n caption_status = %s\n WHERE video_id = %s AND channel_id = %s\n \"\"\"\n update_video_values = (\n video[\"snippet\"][\"title\"],\n video[\"snippet\"][\"description\"],\n \",\".join(video[\"snippet\"].get(\"tags\", [])),\n date_parser.parse(video[\"snippet\"][\"publishedAt\"]).strftime('%Y-%m-%d %H:%M:%S'),\n video[\"statistics\"][\"viewCount\"],\n video[\"statistics\"][\"likeCount\"],\n video[\"statistics\"][\"dislikeCount\"],\n video[\"statistics\"][\"favoriteCount\"],\n video[\"statistics\"][\"commentCount\"],\n video[\"contentDetails\"][\"duration\"],\n video[\"snippet\"][\"thumbnails\"][\"default\"][\"url\"],\n video[\"contentDetails\"].get(\"caption\", \"Not Available\"),\n video_id,\n channel_id\n )\n cursor.execute(update_video_sql, update_video_values)\n else:\n # New video, insert a new record\n video_sql = \"\"\"\n INSERT INTO videos (channel_id, video_id, video_title, video_description, tags, published_at, view_count,\n like_count, dislike_count, favorite_count, comment_count, duration, thumbnail, caption_status)\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\n \"\"\"\n video_values = (\n channel_id,\n video_id,\n video[\"snippet\"][\"title\"],\n video[\"snippet\"][\"description\"],\n \",\".join(video[\"snippet\"].get(\"tags\", [])),\n date_parser.parse(video[\"snippet\"][\"publishedAt\"]).strftime('%Y-%m-%d %H:%M:%S'),\n video[\"statistics\"][\"viewCount\"],\n video[\"statistics\"][\"likeCount\"],\n video[\"statistics\"][\"dislikeCount\"],\n video[\"statistics\"][\"favoriteCount\"],\n video[\"statistics\"][\"commentCount\"],\n video[\"contentDetails\"][\"duration\"],\n video[\"snippet\"][\"thumbnails\"][\"default\"][\"url\"],\n video[\"contentDetails\"].get(\"caption\", \"Not Available\")\n )\n cursor.execute(video_sql, video_values)\n connection.commit()\n\ndef retrieve_data_for_channels(channel_ids, connection, cursor):\n channels_data = []\n\n for channel_id in channel_ids:\n channel_sql = f\"\"\"\n SELECT *\n FROM channels\n WHERE channel_id = '{channel_id}'\n \"\"\"\n cursor.execute(channel_sql)\n channel_data = cursor.fetchone()\n\n playlists_sql = f\"\"\"\n SELECT *\n FROM playlists\n WHERE channel_id = '{channel_id}'\n \"\"\"\n cursor.execute(playlists_sql)\n playlists_data = cursor.fetchall()\n\n videos_sql = f\"\"\"\n SELECT *\n FROM videos\n WHERE channel_id = '{channel_id}'\n \"\"\"\n cursor.execute(videos_sql)\n videos_data = cursor.fetchall()\n\n channels_data.append({\n \"Channel\": channel_data,\n \"Playlists\": playlists_data,\n \"Videos\": videos_data\n })\n\n return channels_data\n\ndef execute_sql_queries(connection, cursor):\n query1 = \"\"\"\n SELECT video_title, channel_name\n FROM videos\n INNER JOIN channels ON videos.channel_id = channels.channel_id\n \"\"\"\n cursor.execute(query1)\n result1 = cursor.fetchall()\n st.write(\"Names of all videos and their corresponding channels:\")\n st.table(result1)\n\n query2 = \"\"\"\n SELECT channel_name, COUNT(*) AS num_videos\n FROM videos\n INNER JOIN channels ON videos.channel_id = channels.channel_id\n GROUP BY channel_name\n ORDER BY num_videos DESC\n \"\"\"\n cursor.execute(query2)\n result2 = cursor.fetchall()\n st.write(\"Channels with the most number of videos:\")\n st.table(result2)\n\n query3 = \"\"\"\n SELECT video_title, channel_name, view_count\n FROM videos\n INNER JOIN channels ON videos.channel_id = channels.channel_id\n ORDER BY view_count DESC\n LIMIT 10\n \"\"\"\n cursor.execute(query3)\n result3 = cursor.fetchall()\n st.write(\"Top 10 most viewed videos and their respective channels:\")\n st.table(result3)\n\n query4 = \"\"\"\n SELECT video_title, COUNT(*) AS num_comments\n FROM comments\n INNER JOIN videos ON comments.video_id = videos.video_id\n GROUP BY video_title\n \"\"\"\n cursor.execute(query4)\n result4 = cursor.fetchall()\n # st.write(\"Number of comments on each video:\")\n # st.table(result4)\n\n # video_titles = [row[0] for row in result4]\n # num_comments = [row[1] for row in result4]\n\n # fig, ax = plt.subplots(figsize=(10, 6))\n # ax.bar(video_titles, num_comments)\n # ax.set_xlabel('Video Titles')\n # ax.set_ylabel('Number of Comments')\n # ax.set_title('Number of Comments on Each Video')\n # plt.xticks(rotation=45)\n # st.pyplot(fig)\n\n query5 = \"\"\"\n SELECT video_title, channel_name, like_count\n FROM videos\n INNER JOIN channels ON videos.channel_id = channels.channel_id\n ORDER BY like_count DESC\n LIMIT 10\n \"\"\"\n cursor.execute(query5)\n result5 = cursor.fetchall()\n st.write(\"Videos with the highest number of likes and their corresponding channels:\")\n st.table(result5)\n\n query6 = \"\"\"\n SELECT video_title, SUM(like_count) AS total_likes, SUM(dislike_count) AS total_dislikes\n FROM videos\n GROUP BY video_title\n \"\"\"\n cursor.execute(query6)\n result6 = cursor.fetchall()\n st.write(\"Total likes and dislikes for each video:\")\n st.table(result6)\n\n query7 = \"\"\"\n SELECT channel_name, SUM(view_count) AS total_views\n FROM videos\n INNER JOIN channels ON videos.channel_id = channels.channel_id\n GROUP BY channel_name\n \"\"\"\n cursor.execute(query7)\n result7 = cursor.fetchall()\n st.write(\"Total views for each channel:\")\n st.table(result7)\n\n query8 = \"\"\"\n SELECT DISTINCT channel_name\n FROM videos\n INNER JOIN channels ON videos.channel_id = channels.channel_id\n WHERE YEAR(published_at) = 2022\n \"\"\"\n cursor.execute(query8)\n result8 = cursor.fetchall()\n st.write(\"Channels with videos published in the year 2022:\")\n st.table(result8)\n\n query9 = \"\"\"\n SELECT channel_name, AVG(duration) AS average_duration\n FROM videos\n INNER JOIN channels ON videos.channel_id = channels.channel_id\n GROUP BY channel_name\n \"\"\"\n cursor.execute(query9)\n result9 = cursor.fetchall()\n st.write(\"Average duration of videos in each channel:\")\n st.table(result9)\n\n query10 = \"\"\"\n SELECT video_title, channel_name, COUNT(*) AS num_comments\n FROM comments\n INNER JOIN videos ON comments.video_id = videos.video_id\n INNER JOIN channels ON videos.channel_id = channels.channel_id\n GROUP BY video_title, channel_name\n ORDER BY num_comments DESC\n LIMIT 10\n \"\"\"\n cursor.execute(query10)\n result10 = cursor.fetchall()\n # st.write(\"Videos with the highest number of comments and their corresponding channels:\")\n # st.table(result10)\n\ndef main():\n st.title(\"YouTube Channel Migration\")\n\n channel_ids = st.text_area(\"Enter YouTube Channel IDs (one per line):\")\n channel_ids = channel_ids.strip().split(\"\\n\") if channel_ids else []\n\n if not channel_ids:\n st.write(\"No YouTube Channel IDs provided.\")\n return\n\n connection, cursor = create_mysql_connection()\n channels_data = []\n\n for channel_id in channel_ids:\n channel_data = get_channel_data(channel_id)\n playlists = get_playlist_data(channel_id)\n videos = get_video_data(channel_id)\n\n channel_data[\"_id\"] = ObjectId()\n\n for playlist in playlists:\n playlist[\"_id\"] = ObjectId()\n for video in videos:\n video[\"_id\"] = ObjectId()\n\n try:\n mycollection.insert_one({\"_id\": channel_id, **channel_data[\"Channel_Name\"]})\n for playlist in playlists:\n playlist_id = f\"playlist_{playlist['id']}\"\n mycollection.insert_one({\"_id\": playlist_id, \"Playlist\": playlist})\n for video in videos:\n video_id = f\"video_{video['id']['videoId']}\"\n mycollection.insert_one({\"_id\": video_id, \"Video\": video})\n except DuplicateKeyError as e:\n st.write(f\"Skipping insertion of channel {channel_data['Channel_Name']['Channel_Name']} \"\n f\"({channel_data['Channel_Name']['Channel_Id']}) as it already exists in MongoDB.\")\n\n migrate_to_mysql(channel_data, playlists, videos, connection, cursor)\n\n st.write(\"Data stored in MongoDB and MySQL!\")\n\n st.write(\"---------------------------------------------------------------\")\n st.write(f\"Channel Name: {channel_data['Channel_Name']['Channel_Name']}\")\n st.write(f\"Channel ID: {channel_data['Channel_Name']['Channel_Id']}\")\n st.write(f\"Channel Subscribers: {channel_data['Channel_Name']['Subscription_Count']}\")\n st.write(f\"Channel Views: {channel_data['Channel_Name']['Channel_Views']}\")\n st.write(f\"Channel Description: {channel_data['Channel_Name']['Channel_Description']}\")\n for playlist in playlists:\n st.write(f\"Playlist Title: {playlist['snippet']['title']}\")\n st.write(f\"Playlist ID: {playlist['id']}\")\n for video in videos:\n st.write(f\"Video Title: {video['snippet']['title']}\")\n st.write(f\"Video ID: {video['id']['videoId']}\")\n\n st.write(\"Data stored in MongoDB and MySQL!\")\n\n channels_data.append({\n \"Channel\": channel_data,\n \"Playlists\": playlists,\n \"Videos\": videos\n })\n\n connection.close()\n cursor.close()\n myclient.close()\n\n connection, cursor = create_mysql_connection()\n channels_data = retrieve_data_for_channels(channel_ids, connection, cursor)\n \n execute_sql_queries(connection, cursor)\n\n \n cursor.close()\n connection.close()\n\nif __name__ == \"__main__\":\n main()","repo_name":"sugin22/YouTube-Data-Harvesting-and-Warehousing-using-SQL-MongoDB-and-Streamlit","sub_path":"Project1.py","file_name":"Project1.py","file_ext":"py","file_size_in_byte":21248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"10817126924","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection,Line3DCollection\r\n\r\nclass model:\r\n\r\n def __init__(self):\r\n # 空间划分:固定 √\r\n self.Xspace = 100; self.Yspace = 100; self.Zspace = 100 # 模型在三个方向的\"总大小\"!\r\n self.a = 10; self.b = 10; self.c = 10 # 单个方块的3边长\r\n self.block_total = int((self.Xspace / self.a) * (self.Yspace / self.b) * (self.Zspace / self.c)) # 总网格块体数(转int): self.block_total\r\n\r\n # 每个立方体的坐标:固定 √ 一层一层生成:先x后y,最后是z!\r\n self.x0 = [xtmp1 for xtmp1 in np.arange(self.a / 2, self.Xspace, self.a) for xtmp2 in np.arange(0, self.b * self.c)]\r\n self.y0 = [ytmp1 for ytmp1 in np.arange(self.b / 2, self.Yspace, self.b) for ytmp2 in np.arange(0, self.c)] * self.a\r\n self.z0 = [ztmp1 for ztmp1 in np.arange(self.c / 2, self.Zspace, self.c)] * (self.a * self.b)\r\n self.Pointxyz = [(self.x0[xyz], self.y0[xyz], self.z0[xyz]) for xyz in np.arange(0, self.block_total)]\r\n\r\n # 观测点分布:固定 √\r\n self.Xmin = 5; self.dx = 10; self.Nx = 10 # x向10个观测点,起点5,间距10\r\n self.Ymin = 5; self.dy = 10; self.Ny = 10 # y向同上\r\n self.Zplane = 90 # 观测点所在的平面\r\n self.ober_total = self.Nx * self.Ny # 总观测点数:10x10 = 100\r\n\r\n self.oberx0 = [ xtmp1 for xtmp1 in range(self.Xmin, self.Xspace, self.Nx) ] * 10\r\n self.obery0 = [ ytmp1 for ytmp1 in range(self.Ymin, self.Yspace, self.Ny) for ytmp2 in range(10) ]\r\n self.oberz0 = [self.Zplane]*100\r\n\r\n # 1. 画所有\"上面\"\r\n def surface_up(self, ax, kappa_position):\r\n for num in range(self.block_total):\r\n # 块体中心点:\r\n center = self.Pointxyz[num]\r\n # \"上面\"的4个顶点:\r\n point1 = (center[0] - self.a / 2, center[1] - self.b / 2, center[2] - self.c / 2)\r\n point2 = (center[0] - self.a / 2, center[1] + self.b / 2, center[2] - self.c / 2)\r\n point3 = (center[0] + self.a / 2, center[1] + self.b / 2, center[2] - self.c / 2)\r\n point4 = (center[0] + self.a / 2, center[1] - self.b / 2, center[2] - self.c / 2)\r\n # 顶点汇总:\r\n verts = [point1, point2, point3, point4]\r\n poly3d = [verts]\r\n\r\n # 画顶点(同时限定空间范围):必须有!\r\n x = (point1[0], point2[0], point3[0], point4[0])\r\n y = (point1[1], point2[1], point3[1], point4[1])\r\n z = (point1[2], point2[2], point3[2], point4[2])\r\n ax.scatter(x, y, z, c='k', marker='None')\r\n\r\n if num in kappa_position:\r\n # 画\"下面\":\r\n ax.add_collection3d(Poly3DCollection(poly3d, facecolors='y', linewidths=2, alpha=1))\r\n continue\r\n\r\n # 画\"下面\":\r\n ax.add_collection3d(Poly3DCollection(poly3d, facecolors='b', linewidths=1, alpha=0.05))\r\n\r\n # 2. 画所有\"下面\"\r\n def surface_down(self, ax, kappa_position):\r\n for num in range(self.block_total):\r\n # 块体中心点:\r\n center = self.Pointxyz[num]\r\n # \"上面\"的4个顶点:\r\n point5 = (center[0] - self.a / 2, center[1] - self.b / 2, center[2] + self.c / 2)\r\n point6 = (center[0] - self.a / 2, center[1] + self.b / 2, center[2] + self.c / 2)\r\n point7 = (center[0] + self.a / 2, center[1] + self.b / 2, center[2] + self.c / 2)\r\n point8 = (center[0] + self.a / 2, center[1] - self.b / 2, center[2] + self.c / 2)\r\n # 顶点汇总:\r\n verts = [point5, point6, point7, point8]\r\n poly3d = [verts]\r\n\r\n # 画顶点(同时限定空间范围):必须有!\r\n x = (point5[0], point6[0], point7[0], point8[0])\r\n y = (point5[1], point6[1], point7[1], point8[1])\r\n z = (point5[2], point6[2], point7[2], point8[2])\r\n ax.scatter(x, y, z, c='k', marker='None')\r\n\r\n if num in kappa_position:\r\n # 画\"下面\":\r\n ax.add_collection3d(Poly3DCollection(poly3d, facecolors='y', linewidths=2, alpha=1))\r\n continue\r\n\r\n # 画\"下面\":\r\n ax.add_collection3d(Poly3DCollection(poly3d, facecolors='b', linewidths=1, alpha=0.05))\r\n\r\n # 3. 画所有\"前面\"\r\n def surface_forward(self, ax, kappa_position):\r\n for num in range(self.block_total):\r\n # 块体中心点:\r\n center = self.Pointxyz[num]\r\n # \"前面\"的4个顶点:\r\n point2 = (center[0] - self.a / 2, center[1] + self.b / 2, center[2] - self.c / 2)\r\n point3 = (center[0] + self.a / 2, center[1] + self.b / 2, center[2] - self.c / 2)\r\n point7 = (center[0] + self.a / 2, center[1] + self.b / 2, center[2] + self.c / 2)\r\n point6 = (center[0] - self.a / 2, center[1] + self.b / 2, center[2] + self.c / 2)\r\n # 顶点汇总:\r\n verts = [point2, point3, point7, point6]\r\n poly3d = [verts]\r\n\r\n # 画顶点(同时限定空间范围):必须有!\r\n x = (point2[0], point3[0], point7[0], point6[0])\r\n y = (point2[1], point3[1], point7[1], point6[1])\r\n z = (point2[2], point3[2], point7[2], point6[2])\r\n ax.scatter(x, y, z, c='k', marker='None')\r\n\r\n if num in kappa_position:\r\n # 画\"下面\":\r\n ax.add_collection3d(Poly3DCollection(poly3d, facecolors='y', linewidths=2, alpha=1))\r\n continue\r\n\r\n # 画\"下面\":\r\n ax.add_collection3d(Poly3DCollection(poly3d, facecolors='b', linewidths=1, alpha=0.05))\r\n\r\n # 4. 画所有的\"后面\"\r\n def surface_back(self, ax, kappa_position):\r\n for num in range(self.block_total):\r\n # 块体中心点:\r\n center = self.Pointxyz[num]\r\n # \"后面\"的4个顶点:\r\n point1 = (center[0] - self.a / 2, center[1] - self.b / 2, center[2] - self.c / 2)\r\n point4 = (center[0] + self.a / 2, center[1] - self.b / 2, center[2] - self.c / 2)\r\n point8 = (center[0] + self.a / 2, center[1] - self.b / 2, center[2] + self.c / 2)\r\n point5 = (center[0] - self.a / 2, center[1] - self.b / 2, center[2] + self.c / 2)\r\n # 顶点汇总:\r\n verts = [point1, point4, point8, point5]\r\n poly3d = [verts]\r\n\r\n # 画顶点(同时限定空间范围):必须有!\r\n x = (point1[0], point4[0], point8[0], point5[0])\r\n y = (point1[1], point4[1], point8[1], point5[1])\r\n z = (point1[2], point4[2], point8[2], point5[2])\r\n ax.scatter(x, y, z, c='k', marker='None')\r\n\r\n if num in kappa_position:\r\n # 画\"下面\":\r\n ax.add_collection3d(Poly3DCollection(poly3d, facecolors='y', linewidths=2, alpha=1))\r\n continue\r\n\r\n # 画\"下面\":\r\n ax.add_collection3d(Poly3DCollection(poly3d, facecolors='b', linewidths=1, alpha=0.05))\r\n\r\n # 5. 画所有的\"左面\"\r\n def surface_left(self, ax, kappa_position):\r\n for num in range(self.block_total):\r\n # 块体中心点:\r\n center = self.Pointxyz[num]\r\n # \"左面\"的4个顶点:\r\n point1 = (center[0] - self.a / 2, center[1] - self.b / 2, center[2] - self.c / 2)\r\n point2 = (center[0] - self.a / 2, center[1] + self.b / 2, center[2] - self.c / 2)\r\n point6 = (center[0] - self.a / 2, center[1] + self.b / 2, center[2] + self.c / 2)\r\n point5 = (center[0] - self.a / 2, center[1] - self.b / 2, center[2] + self.c / 2)\r\n # 顶点汇总:\r\n verts = [point1, point2, point6, point5]\r\n poly3d = [verts]\r\n\r\n # 画顶点(同时限定空间范围):必须有!\r\n x = (point1[0], point2[0], point6[0], point5[0])\r\n y = (point1[1], point2[1], point6[1], point5[1])\r\n z = (point1[2], point2[2], point6[2], point5[2])\r\n ax.scatter(x, y, z, c='k', marker='None')\r\n\r\n if num in kappa_position:\r\n # 画\"下面\":\r\n ax.add_collection3d(Poly3DCollection(poly3d, facecolors='y', linewidths=2, alpha=1))\r\n continue\r\n\r\n # 画\"下面\":\r\n ax.add_collection3d(Poly3DCollection(poly3d, facecolors='b', linewidths=1, alpha=0.05))\r\n\r\n # 6. 画所有的\"右面\"\r\n def surface_right(self, ax, kappa_position):\r\n for num in range(self.block_total):\r\n # 块体中心点:\r\n center = self.Pointxyz[num]\r\n # \"右面\"的4个顶点:\r\n point4 = (center[0] + self.a / 2, center[1] - self.b / 2, center[2] - self.c / 2)\r\n point3 = (center[0] + self.a / 2, center[1] + self.b / 2, center[2] - self.c / 2)\r\n point7 = (center[0] + self.a / 2, center[1] + self.b / 2, center[2] + self.c / 2)\r\n point8 = (center[0] + self.a / 2, center[1] - self.b / 2, center[2] + self.c / 2)\r\n # 顶点汇总:\r\n verts = [point4, point3, point7, point8]\r\n poly3d = [verts]\r\n\r\n # 画顶点(同时限定空间范围):必须有!\r\n x = (point4[0], point3[0], point7[0], point8[0])\r\n y = (point4[1], point3[1], point7[1], point8[1])\r\n z = (point4[2], point3[2], point7[2], point8[2])\r\n ax.scatter(x, y, z, c='k', marker='None')\r\n\r\n if num in kappa_position:\r\n # 画\"下面\":\r\n ax.add_collection3d(Poly3DCollection(poly3d, facecolors='y', linewidths=2, alpha=1))\r\n continue\r\n\r\n # 画\"下面\":\r\n ax.add_collection3d(Poly3DCollection(poly3d, facecolors='b', linewidths=1, alpha=0.05))\r\n\r\n # 7. 画观测面:\r\n def surface_ober(self, ax):\r\n # 观测点:\r\n ax.scatter(self.oberx0, self.obery0, self.oberz0, c = 'r', marker='*')\r\n # 观测面:\r\n for numy in range(1,10):\r\n for numx in range(1,10):\r\n point1 = ( self.Xmin + self.dx*(numx-1), self.Ymin + self.dy*(numy-1), self.Zplane )\r\n point2 = ( self.Xmin + self.dx*(numx), self.Ymin + self.dy*(numy-1), self.Zplane )\r\n point3 = ( self.Xmin + self.dx*(numx), self.Ymin + self.dy*(numy), self.Zplane )\r\n point4 = ( self.Xmin + self.dx*(numx-1), self.Ymin + self.dy*(numy), self.Zplane )\r\n\r\n verts = [point1, point2, point3, point4]\r\n poly3d = [verts]\r\n ax.add_collection3d(Poly3DCollection(poly3d, facecolors='m', linewidths=2, alpha=1))\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n mymodel = model()\r\n kappa_position = input('输入观测点位置(空格间隔,回车结束):')\r\n kappa_position = list( map(int, kappa_position.split(' ')) )\r\n\r\n # 创建图:\r\n fig = plt.figure()\r\n ax = fig.gca(projection='3d')\r\n # 分别、一次性画完所有块体的6个面\r\n mymodel.surface_up(ax, kappa_position)\r\n mymodel.surface_down(ax, kappa_position)\r\n mymodel.surface_forward(ax, kappa_position)\r\n mymodel.surface_back(ax, kappa_position)\r\n mymodel.surface_left(ax, kappa_position)\r\n mymodel.surface_right(ax, kappa_position)\r\n # 画观测面 + 观测点:\r\n mymodel.surface_ober(ax)\r\n # 关闭网格\r\n plt.axis('off')\r\n\r\n from matplotlib.pyplot import savefig\r\n savefig(\"quan3.pdf\")\r\n","repo_name":"EZ4BYG/Python-Tools","sub_path":"3dmodel.py","file_name":"3dmodel.py","file_ext":"py","file_size_in_byte":11652,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"71081102330","text":"\r\nimport os\r\nimport sys\r\nimport argparse\r\nimport multiprocessing\r\nimport threading\r\nimport functools\r\nimport time\r\n\r\nfrom . import wikitableprocessing\r\nfrom . import multistreamfilehandling\r\nfrom . import tosql\r\n\r\n\r\n# Progress bar code\r\ndef progress_animator(indicators, symbol_loop=('--', \"\\\\\", '|', '/'), suffix='', \r\n task='Processing files ... ', interval=0.1):\r\n \"\"\"Progress indicator\"\"\"\r\n \r\n state = 0\r\n message = ''\r\n while not indicators['end']:\r\n length = len(message)\r\n state = (state + 1) % len(symbol_loop)\r\n time.sleep(interval)\r\n prefix = task + '[' + str(indicators['done']) + '/' + str(indicators['total']) + '] '\r\n message = prefix + symbol_loop[state] + suffix\r\n print(length * ' ', end='\\r')\r\n print(message, end='\\r')\r\n print('')\r\n\r\n if indicators['terminate']:\r\n print('Process Terminated')\r\n sys.exit(0)\r\n else:\r\n print('DONE!')\r\n\r\n\r\ndef associate_to_index(data_directory):\r\n \"\"\"\r\n Associate each multistream file to its corresponding index.\r\n\r\n :param data_directory: path as string\r\n :return: list of associations where each association is of the form:\r\n [multistream_filename, index_filename]\r\n \"\"\"\r\n\r\n parsed_filenames = [n.split('-') for n in os.listdir(data_directory) if\r\n os.path.isfile(os.path.join(data_directory, n)) and\r\n os.path.splitext(os.path.join(data_directory, n))[1] == '.bz2']\r\n\r\n to_process = []\r\n for p in parsed_filenames:\r\n if p[-2].split('.')[-1] == 'xml':\r\n for j in parsed_filenames:\r\n if p[-1] == j[-1] and j[-2].split('.')[-1] == 'txt':\r\n # form: (data, index)\r\n to_process.append(('-'.join(p), '-'.join(j)))\r\n return to_process\r\n\r\n\r\n# Full part processing\r\ndef process_part(part_file, parts_directory, last_part_name, parts_decompression_directory, database):\r\n \"\"\"Process one part of one multistream file into an sql database.\"\"\"\r\n\r\n # decompress part file\r\n decompressed_part_file = multistreamfilehandling.decompress_part(parts_directory, part_file,\r\n parts_decompression_directory)\r\n if part_file == last_part_name:\r\n wikitableprocessing.prepend_file(os.path.join(parts_decompression_directory, decompressed_part_file))\r\n # extract wikitables and parse to lists\r\n parsed = wikitableprocessing.parse_wikitables_from_file(os.path.join(parts_decompression_directory,\r\n decompressed_part_file))\r\n # process into sql database\r\n tosql.process_many_wikitables_into_sql_database(parsed, database)\r\n\r\n\r\ndef prompt_continue(name):\r\n \"\"\"Prompt for required user intervention.\"\"\"\r\n\r\n print(name + \" already exists. \" + \"Data will be added to \" + name + \" if you continue. \")\r\n prompt = \"Do you want to continue? (y/n): \"\r\n inp = input(prompt).strip().lower()\r\n if inp not in ['y', 'n']:\r\n print(inp + \" is not a valid option, please try again...\")\r\n return prompt_continue(name)\r\n return inp == 'y'\r\n\r\n\r\ndef cleanup(files_dict):\r\n \"\"\"\r\n Removal of intermediate files.\r\n \"\"\"\r\n\r\n if os.path.exists(files_dict['decompressed_index_filename']):\r\n os.remove(files_dict['decompressed_index_filename'])\r\n for f in os.listdir(files_dict['parts_directory']):\r\n os.remove(os.path.join(files_dict['parts_directory'], f))\r\n os.rmdir(files_dict['parts_directory'])\r\n for f in os.listdir(files_dict['parts_decompression_directory']):\r\n os.remove(os.path.join(files_dict['parts_decompression_directory'], f))\r\n os.rmdir(files_dict['parts_decompression_directory'])\r\n\r\n\r\ndef get_database_filename(data_directory):\r\n \"\"\"\r\n Determine database filename.\r\n\r\n :param data_directory: path as string\r\n :return: filename as string\r\n \"\"\"\r\n\r\n base = os.path.commonprefix(os.listdir(data_directory))\r\n return base + '.db'\r\n\r\n\r\ndef main():\r\n remove_intermediate_files = True\r\n\r\n parser = argparse.ArgumentParser(description='Extract wikitables from multistream wikipedia database dump '\r\n 'and process them into a sqlite3 database.')\r\n parser.add_argument('path', metavar='folder', type=str, nargs=1,\r\n help='wikipedia multistream folder path')\r\n args = parser.parse_args()\r\n wiki_path = args.path[0]\r\n \r\n indicators = {}\r\n indicators['done'] = 0\r\n indicators['end'] = False\r\n indicators['terminate'] = False\r\n\r\n data_index_pairs = associate_to_index(wiki_path)\r\n indicators['total'] = len(data_index_pairs)\r\n database_filename = get_database_filename(wiki_path)\r\n\r\n progress = threading.Thread(target=progress_animator, args=(indicators,))\r\n \r\n # Check if database exists\r\n if os.path.exists(database_filename):\r\n indicators['terminate'] = not prompt_continue(database_filename)\r\n if indicators['terminate']:\r\n print(\"Process Terminated.\")\r\n sys.exit(0)\r\n else:\r\n tosql.sql_table_creation(database_filename)\r\n \r\n print(\"Database filename: \", database_filename)\r\n \r\n progress.start()\r\n \r\n for i in data_index_pairs:\r\n files_info = multistreamfilehandling.prepare_parts_using_index(wiki_path, i[0], i[1], indicators['done'])\r\n process_part_directory_set = \\\r\n functools.partial(process_part, parts_directory=files_info['parts_directory'],\r\n last_part_name=files_info['last_part_name'],\r\n parts_decompression_directory=files_info['parts_decompression_directory'],\r\n database=database_filename)\r\n parts = os.listdir(files_info['parts_directory'])\r\n \r\n # main multiprocessing loop (by batch of 100 pages)\r\n with multiprocessing.Pool() as pool:\r\n pool.map(process_part_directory_set, parts)\r\n\r\n if remove_intermediate_files:\r\n cleanup(files_info)\r\n\r\n indicators['done'] += 1\r\n indicators['end'] = True\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"eddyydde/wikitablestosql","sub_path":"wikitablestosql/wikitablestosql.py","file_name":"wikitablestosql.py","file_ext":"py","file_size_in_byte":6277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"27609543267","text":"from django.conf import settings\nfrom django.db import models\nfrom django.db.models import Manager\n\nfrom thunderstore.core.mixins import TimestampMixin\nfrom thunderstore.core.utils import ChoiceEnum\n\n\nclass CommunityMemberRole(ChoiceEnum):\n owner = \"owner\"\n moderator = \"moderator\"\n member = \"member\"\n\n\nclass CommunityMembership(TimestampMixin, models.Model):\n objects: \"Manager[CommunityMembership]\"\n\n community = models.ForeignKey(\n \"community.Community\",\n related_name=\"members\",\n on_delete=models.CASCADE,\n db_index=True,\n )\n user = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n related_name=\"community_memberships\",\n on_delete=models.CASCADE,\n )\n role = models.CharField(\n max_length=64,\n default=CommunityMemberRole.member,\n choices=CommunityMemberRole.as_choices(),\n )\n\n def __str__(self):\n return f\"{self.user.username} membership to {self.community.name}\"\n\n class Meta:\n constraints = [\n models.UniqueConstraint(\n fields=(\"user\", \"community\"), name=\"one_community_membership_per_user\"\n ),\n ]\n verbose_name = \"community member\"\n verbose_name_plural = \"community members\"\n","repo_name":"thunderstore-io/Thunderstore","sub_path":"django/thunderstore/community/models/community_membership.py","file_name":"community_membership.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","stars":81,"dataset":"github-code","pt":"77"}
+{"seq_id":"35828303077","text":"\r\nimport sys\r\nimport math\r\nfrom queue import PriorityQueue\r\n\r\ndef dijktra(Graph, source):\r\n\r\n dist = [math.inf] * len(Graph)\r\n dist[source - 1] = 0\r\n\r\n visited = [False] * len(Graph)\r\n prev = [None] * len(Graph)\r\n\r\n Q = PriorityQueue()\r\n Q.put((dist[source - 1], source))\r\n\r\n while Q.empty() is False:\r\n u = Q.get()[1]\r\n if visited[u - 1]:\r\n continue\r\n visited[u - 1] = True\r\n if Graph[u] is not None:\r\n for x in G[u]:\r\n v = x[0]\r\n alt = dist[u - 1] + x[1]\r\n if alt < dist[v - 1]:\r\n dist[v - 1] = alt\r\n prev[v - 1] = u\r\n Q.put((dist[v - 1], v))\r\n\r\n\r\n if len(prev) == 1:\r\n print(1)\r\n else:\r\n a = prev[-1]\r\n array = [len(prev)]\r\n while True:\r\n if a is None:\r\n break\r\n else:\r\n array.append(a)\r\n a = prev[a - 1]\r\n array.reverse()\r\n for x in array:\r\n print(x, end=\" \")\r\n print()\r\n\r\n\r\nsys.stdin = open(\"input2.txt\", \"r\")\r\nsys.stdout = open(\"output2.txt\", \"w\")\r\n\r\ninputs = open(\"input1.txt\", \"r\").readlines()\r\n\r\ncaseNo = int(input())\r\n\r\ncases = []\r\nrouts = []\r\n\r\nfor i in range(1, len(inputs)):\r\n a = inputs[i].split()\r\n if len(a) == 2:\r\n cases.append(a)\r\n else:\r\n routs.append(a)\r\nfor i in cases:\r\n graph = {}\r\n for j in range(int(i[1])):\r\n edges = []\r\n val = list(map(int, routs.pop(0)))\r\n if val[0] in graph.keys():\r\n edges = graph[val[0]]\r\n edges.append(val[1:])\r\n graph[val[0]] = edges\r\n for k in range(1, int(i[0]) + 1):\r\n if k not in graph:\r\n graph[k] = None\r\n graph = {u: v for u, v in sorted(graph.items())}\r\n dijktra(graph, 1)","repo_name":"Musfiqur-shovon/CSE221","sub_path":"07_20301332_04/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"14883543324","text":"import os\nimport requests\nfrom datetime import datetime\n\nfrom flask import Blueprint, redirect, url_for, request, render_template, jsonify\nfrom flask_login import current_user\n\nfrom app import alerts\nfrom app.forms import EventForm\nfrom app.models import Address, Account, db\nfrom app.models import Event\n\nevents_blueprint = Blueprint('events', __name__)\n\ngoogle_maps_api = os.environ.get('GOOGLE_MAPS_API')\n\n\n@events_blueprint.route('/events_page')\ndef events_page():\n # Retrieve all events from the database\n # with app.app_context():\n events = Event.query.all()\n # Render the events page and pass the events to the template\n return render_template('events_page.html', events=events)\n\n\ndef parse_location(location_string):\n print(f\"Trying to parse: {location_string}\") # Add this line\n components = location_string.split(',')\n\n # Check if we have all the required components\n if len(components) != 4:\n raise ValueError(\"Invalid location string provided.\")\n\n street = components[0].strip()\n city = components[1].strip()\n state = components[2].strip()\n country = components[3].strip()\n\n return street, city, state, country\n\n\n@events_blueprint.route('/add_event', methods=['GET', 'POST'])\ndef add_event():\n form = EventForm()\n if request.method == 'POST':\n # Add new event to the database here\n # Then redirect to the events page or some other page\n data = request.form\n\n # Extract data fields\n start_time_str = data.get('start_time')\n end_time_str = data.get('end_time')\n\n # Convert the date strings to datetime objects\n start_time = datetime.strptime(start_time_str, \"%Y-%m-%dT%H:%M\")\n end_time = datetime.strptime(end_time_str, \"%Y-%m-%dT%H:%M\")\n\n street, city, state, country = parse_location(form.location.data)\n # address = Address(\n # street=street,\n # city=city,\n # state=state,\n # country=country\n # )\n # db.session.add(address)\n # db.session.commit()\n\n event = Event(\n name=form.name.data,\n description=form.description.data,\n start_time=start_time,\n end_time=end_time,\n audience=form.audience.data,\n event_type=form.event_type.data,\n\n cost=form.cost.data,\n created_by=current_user.id,\n created_at=datetime.now(),\n sponsor=form.sponsor.data,\n expected_attendees=form.expected_attendees.data,\n actual_attendees=form.actual_attendees.data,\n marketing_channel=form.marketing_channel.data,\n # NEW FORM FIELDS\n registration_link=form.registration_link.data,\n responsibility=form.responsibility.data,\n street_address=parse_location(form.location.data)[0],\n city=parse_location(form.location.data)[1],\n state=parse_location(form.location.data)[2],\n # zip_code=parse_location(form.location.data)[3],\n industry=form.industry.data,\n )\n\n # Generate an alert\n # generate_event_alert(event)\n # Generate an alert for nearby users\n alerts.generate_event_alert_for_nearby_users(event)\n\n db.session.add(event)\n db.session.commit()\n return redirect(url_for('events.events_page'))\n return render_template('add_event.html', form=form)\n\n\n@events_blueprint.route('/event_list//')\ndef event_list(account_id, event_city):\n account = Account.query.get(account_id)\n addresses = Address.query.filter_by(city=event_city).all()\n events = []\n\n for address in addresses:\n if address.event:\n events.append(address.event)\n return render_template('event_list.html', events=events, account=account)\n\n\ndef get_distance(city1, city2):\n # Define the base URL for the Distance Matrix API\n base_url = \"https://maps.googleapis.com/maps/api/distancematrix/json\"\n\n # Define the parameters for the GET request\n params = {\n \"origins\": city1,\n \"destinations\": city2,\n \"units\": \"imperial\",\n \"key\": google_maps_api,\n }\n\n # Send the GET request\n response = requests.get(base_url, params=params)\n\n # Convert the response to JSON\n data = response.json()\n\n # Make sure to handle cases where the API returns an error or no routes are found\n if data['status'] == 'OK' and data['rows'][0]['elements'][0]['status'] == 'OK':\n # Extract the distance from the JSON response\n distance = data[\"rows\"][0][\"elements\"][0][\"distance\"][\"text\"]\n\n # Remove any text from the end of the distance string, remove any commas and convert it to a float\n distance = float(distance.split(\" \")[0].replace(\",\", \"\"))\n\n return distance\n else:\n # if this scenario, then return to add event page and flash error message\n return 1000\n\n\n@events_blueprint.route('/events_in_area', methods=['GET'])\ndef get_events_in_area():\n # Get the optional miles_from_event parameter\n miles_from_event = request.args.get('miles_from_event', default=0, type=int)\n\n # Get the list of accounts from the database\n accounts = Account.query.all()\n\n # This will store the final list of events\n events_in_area = []\n\n # Iterate over each account\n for account in accounts:\n # Get the corresponding address based on the city\n address = Address.query.filter_by(city=account.BillingCity).first()\n\n # If the address exists and the event exists\n if address and address.event:\n # If miles_from_event is specified, check the distance\n if miles_from_event > 0:\n distance = get_distance((account.BillingLatitude, account.BillingLongitude),\n (address.event.location.latitude, address.event.location.longitude))\n\n # If the event is within the specified range, add it to the list\n if distance <= miles_from_event:\n events_in_area.append(address.event)\n else:\n # If miles_from_event is not specified, simply add the event to the list\n events_in_area.append(address.event)\n\n # Convert the list of events to JSON and return it\n return jsonify([event.to_dict() for event in events_in_area])\n\n\n@events_blueprint.route('/api/events', methods=['GET'])\ndef get_events():\n # query all events that are greater than the current time\n events = Event.query.filter(Event.start_time > datetime.now()).all()\n events_list = []\n for event in events:\n events_list.append({\n 'name': event.name,\n 'description': event.description,\n 'start_time': event.start_time,\n 'end_time': event.end_time,\n 'audience': event.audience,\n 'event_type': event.event_type.value,\n 'city': event.city,\n 'state': event.state,\n\n })\n events_list.sort(key=lambda x: x['start_time'])\n return jsonify(events_list)\n","repo_name":"contactatfp/ARRmy---Top-Of-The-Funnel","sub_path":"app/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":7065,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"42788637615","text":"#!usr/bin/env/python3\r\n\r\n\"\"\"A palindrome is a word or phrase that reads the same both forward and\r\n\tbackward. Some examples include “racecar,” “kayak,” and “deified.”\r\n# \"\"\"\r\n\r\n# def palindrome_checker(string): # O(N)\r\n# \t#Start the leftIndex at index 0:\r\n# \tleftIndex = 0\r\n# \t#Start rightIndex at last index of array:\r\n# \trightIndex = len(string) - 1\r\n# \tmid = len(string)//2\r\n# \t#Iterate until leftIndex reaches the middle of the array:\r\n# \twhile (leftIndex < mid):\r\n# \t\tif(string[leftIndex] != string[rightIndex]):\r\n# \t\t\treturn False\r\n\r\n# \t\tleftIndex = leftIndex + 1\r\n# \t\trightIndex = rightIndex - 1\r\n\t# return True\r\n\t\t\r\n\r\n#Test Case:\r\n# data = ['racecar']\r\n# print(palindrome_checker(data))\r\n\r\n\r\ndef reverse(x):\r\n num1=str(x)[::-1]\r\n if num1==str(x):\r\n return True\r\n return False\r\nprint(reverse('racecar'))","repo_name":"yeboahd24/programming","sub_path":"palindrome.py","file_name":"palindrome.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"77"}
+{"seq_id":"35442823382","text":"from flask import Flask\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nfrom os import path\r\nfrom flask_login import LoginManager\r\nfrom flask_mongoengine import MongoEngine\r\n\r\ndb = SQLAlchemy()\r\nDB_NAME = \"database.db\"\r\nmongo_db = MongoEngine()\r\n\r\ndef create_app():\r\n app = Flask(__name__)\r\n app.config.from_pyfile(\"../settings.py\")\r\n app.config[\"SQLALCHEMY_DATABASE_URI\"] = f\"sqlite:///{DB_NAME}\"\r\n # app.config[\"SQLALCHEMY_DATABASE_URI\"] = \"mysql://jakesboo_books:eDbeQisxc9hgetSNeJLA@server/jakesboo_books\"\r\n db.init_app(app)\r\n\r\n from .views import views\r\n from .auth import auth\r\n app.register_blueprint(views, url_prefix=\"/\")\r\n app.register_blueprint(auth, url_prefix=\"/\")\r\n\r\n from .mongo_models import User, BookEntry\r\n # create_database(app)\r\n mongo_db.init_app(app)\r\n\r\n login_manager = LoginManager()\r\n login_manager.login_view = \"auth.login\"\r\n login_manager.init_app(app)\r\n\r\n @login_manager.user_loader\r\n def load_user(id):\r\n return User.objects(id=id).first()\r\n\r\n return app\r\n\r\n\r\ndef create_database(app):\r\n if not path.exists(\"website/\" + DB_NAME):\r\n db.create_all(app=app)\r\n print(\"Created Database!\")\r\n","repo_name":"CrazyheadJake/Book-List","sub_path":"website/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"37979245908","text":"# %%\n\"\"\"\n정수 n개가 주어졌을 때, n개의 합을 구하는 함수를 작성하시오.\n\na: 합을 구해야 하는 정수 n개가 저장되어 있는 리스트 (0 ≤ a[i] ≤ 1,000,000, 1 ≤ n ≤ 3,000,000)\n\n리턴값: a에 포함되어 있는 정수 n개의 합 (정수)\n\"\"\"\ndef solve(a):\n return sum(a)\n\n# %%\n\"\"\"\n셀프 넘버는 1949년 인도 수학자 D.R. Kaprekar가 이름 붙였다.\n\n양의 정수 n에 대해서 d(n)을 n과 n의 각 자리수를 더하는 함수라고 정의하자.\n\n예를 들어, d(75) = 75+7+5 = 87이다.\n\n양의 정수 n이 주어졌을 때,\n\n이 수를 시작해서 n, d(n), d(d(n)), d(d(d(n))), ...과 같은 무한 수열을 만들 수 있다. \n\n예를 들어, 33으로 시작한다면 다음 수는 33 + 3 + 3 = 39이고,\n\n그 다음 수는 39 + 3 + 9 = 51, 다음 수는 51 + 5 + 1 = 57이다.\n\n이런식으로 다음과 같은 수열을 만들 수 있다.\n\n33, 39, 51, 57, 69, 84, 96, 111, 114, 120, 123, 129, 141, ...\n\nn을 d(n)의 생성자라고 한다.\n\n위의 수열에서 33은 39의 생성자이고, 39는 51의 생성자, 51은 57의 생성자이다.\n\n생성자가 한 개보다 많은 경우도 있다. 예를 들어, 101은 생성자가 2개(91과 100) 있다. \n\n생성자가 없는 숫자를 셀프 넘버라고 한다. 100보다 작은 셀프 넘버는 총 13개가 있다.\n\n1, 3, 5, 7, 9, 20, 31, 42, 53, 64, 75, 86, 97\n\n10000보다 작거나 같은 셀프 넘버를 한 줄에 하나씩 출력하는 프로그램을 작성���시오.\n\"\"\"\ndef d(n):\n k = 0\n for i in range(len(str(n))):\n k += int(str(n)[i])\n return k + n\n\nrun = True\ns = 1\nl2 = []\nwhile run:\n n = d(s)\n if n <= 10000:\n l2.append(n)\n elif s == 10001:\n run = False\n s += 1\n \nfor i in range(1, 10001):\n if i not in l2:\n print(i)\n\n# %%\n\"\"\"\n어떤 양의 정수 X의 각 자리가 등차수열을 이룬다면, 그 수를 한수라고 한다.\n\n등차수열은 연속된 두 개의 수의 차이가 일정한 수열을 말한다.\n\nN이 주어졌을 때, 1보다 크거나 같고, N보다 작거나 같은\n\n한수의 개수를 출력하는 프로그램을 작성하시오. \n\"\"\"\ndef solve(n):\n lst = []\n for i in range(1, n+1):\n l = []\n if i < 100:\n lst.append(i)\n else:\n for j in range(len(str(i))-1):\n m = int(str(i)[j]) - int(str(i)[j+1])\n l.append(m)\n \n if len(set(l)) == 1:\n lst.append(i)\n \n return lst\n\nn = int(input())\nlst = solve(n)\nprint(len(lst))\n","repo_name":"prierKT/self_study","sub_path":"algorithm/Baekjoon_function.py","file_name":"Baekjoon_function.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"18571363849","text":"import sys\nfrom PyQt6.QtCore import Qt\nfrom PyQt6.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QTextEdit, QScrollArea, QLabel\n\nclass ScrollViewExample(QMainWindow):\n def __init__(self):\n super().__init__()\n\n self.initUI()\n\n def initUI(self):\n self.setWindowTitle('Scroll View Example')\n self.setGeometry(100, 100, 600, 400)\n\n # Create a central widget\n central_widget = QWidget(self)\n self.setCentralWidget(central_widget)\n\n # Create a vertical layout for the central widget\n layout = QVBoxLayout()\n central_widget.setLayout(layout)\n\n # Title Tec System\n Title_Tec_System = QLabel()\n Title_Tec_System.setText(\"Tec_System\\n\") # Create Title\n\n # Add the Title to the central layout\n layout.addWidget(Title_Tec_System)\n\n # Create a QTextEdit widget to put inside the scroll view\n #text_edit = QTextEdit()\n text_edit = QLabel()\n text_edit.setText(\"This is some text that will be scrollable.\\n\" * 20) # Create a long text\n\n # Create a scroll area\n scroll_area = QScrollArea()\n scroll_area.setWidget(text_edit)\n scroll_area.setWidgetResizable(True) # Make the widget inside the scroll area resizable\n\n # Add the scroll area to the central layout\n layout.addWidget(scroll_area)\n\ndef main():\n app = QApplication(sys.argv)\n window = ScrollViewExample()\n window.show()\n sys.exit(app.exec())\n\nif __name__ == '__main__':\n main()\n","repo_name":"WilsonQueirozdeOliveira/Tec_do_Brasil","sub_path":"tec_system/tec_system_0.6.0.0.py","file_name":"tec_system_0.6.0.0.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"75304768889","text":"from django.db import models\nfrom django.conf import settings\n\n\nclass Cenario(models.Model):\n imagem = models.ImageField(\n \"Imagem\",\n upload_to=\"cenario/\",\n null=True,\n blank=True,\n )\n criador = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)\n nome = models.CharField('Nome', max_length=64)\n data_criacao = models.DateTimeField('Data de Criação', auto_now_add=True)\n\n class Meta:\n verbose_name = 'Cenário'\n verbose_name_plural = 'Cenários'\n ordering = ['nome', 'data_criacao']\n\n def __str__(self) -> str:\n return self.nome\n","repo_name":"leonextlevel/universo-nextlevel","sub_path":"universo_nextlevel/core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"22776261557","text":"#!/usr/bin/env python\nimport os, time, sys\nout = open(\"out.c\", \"w\")\npreprocessor_vars = {}\npreprocessor_str_const = {}\npreprocessor_env = []\nmacros = {}\nwords = {}\nimports = [sys.argv[1]]\npreprocessed = []\nstringmode = False\nstrbuffer = \"\"\ncomment = False\nloops = 0\ncurrent_loop = 0\nindex = -1\nprocs = []\nproc = False\ndef preprocess(program, main=True):\n global preprocessed\n program = program.split(\"\\n\")\n index = -1\n for x in program:\n if not x.startswith(\"#\"):\n index += len(x.split(\" \"))\n continue\n x = x.replace(\"#\", \"\")\n x = x.split(\" \")\n if x[0] == \"CONST\":\n preprocessor_vars[x[1]] = int(x[2])\n elif x[0] == \"SCONST\":\n preprocessor_str_const[x[1]] = \" \".join(x[2:])\n elif x[0] == \"MACRO\":\n macros[x[1]] = x[2:]\n elif x[0] == \"WORD\":\n words[x[1]] = x[2:]\n elif x[0] == \"process\":\n if x[1] not in imports:\n if os.path.exists(\"./\"+x[1]): \n print(\"processing: \" + x[1])\n imports.append(x[1])\n preprocess(open(x[1],\"r\").read(), False)\n elif os.path.exists(\"/opt/fifthc/\"+x[1]):\n print(\"processing: \" + x[1])\n imports.append(x[1])\n preprocess(open(\"/opt/fifthc/\"+x[1],\"r\").read(), False)\n elif x[0] == \"include\":\n old_preprocessed = preprocessed\n preprocessed = []\n if x[1] not in imports:\n if os.path.exists(\"./\"+x[1]): \n print(\"compiling: \" + x[1])\n imports.append(x[1])\n preprocess(open(x[1],\"r\").read())\n compile(open(x[1],\"r\").read().replace(\"\\n\",\" \").replace(\"\\t\",\"\").split(\" \"))\n elif os.path.exists(\"/opt/fifthc/\"+x[1]):\n print(\"compiling: \" + x[1])\n imports.append(x[1])\n preprocess(open(\"/opt/fifthc/\"+x[1],\"r\").read())\n compile(open(\"/opt/fifthc/\"+x[1],\"r\").read().replace(\"\\n\",\" \").replace(\"\\t\",\"\").split(\" \"))\n else:\n print(\"[INFO] Skipped \"+x[1] + \" because its already compiled\")\n preprocessed = old_preprocessed\n if main:\n for _ in range(len(x)+1):\n preprocessed.append(index+_)\n index+=len(x)\ndef pop(var):\n out.write(var + \" = stack[--stack_ptr];\\n\")\ndef push(value):\n out.write(\"stack[stack_ptr++] = \" + str(value) + \";\\n\")\ndef adds():\n pop(\"x\")\n pop(\"y\")\n out.write(\"x = x + y;\\n\")\n push(\"x\")\ndef subs():\n pop(\"x\")\n pop(\"y\")\n out.write(\"x = x - y;\\n\")\n push(\"x\")\ndef muls():\n pop(\"x\")\n pop(\"y\")\n out.write(\"x = x * y;\\n\")\n push(\"x\")\ndef divs():\n pop(\"x\")\n pop(\"y\")\n out.write(\"x = x / y;\\n\")\n push(\"x\")\ndef compile(program):\n global out\n global preprocessed\n global preprocessor_vars\n global preprocessor_str_const\n global funcs\n global stringmode\n global strbuffer\n global proc\n global comment\n global loops\n global current_loop\n global index\n global words\n for x in program:\n index+=1\n if index in preprocessed:\n continue\n if stringmode:\n if x == \"\\\"\":\n out.write(\"strcpy(strings[ssp++],\\\"{}\\\");\\n\".format(strbuffer[0:-1]))\n stringmode = False\n strbuffer = \"\"\n continue\n else:\n strbuffer += x + \" \"\n continue\n if comment:\n if x == \"//\":\n comment = False\n continue\n if proc:\n out.write(x+\"(){\\n\")\n procs.append(x)\n proc = False\n continue\n try:\n push(str(int(x)))\n except:\n if x in procs:\n out.write(\"proc_\"+x+\"();\\n\")\n elif x in words:\n compile(words[x])\n elif x.startswith(\"p!\"):\n push(str(preprocessor_vars[x.replace(\"p!\",\"\")]))\n elif x.startswith(\"p$\"):\n compile(macros[x.replace(\"p$\",\"\")])\n elif x.startswith(\"p@\"):\n out.write(\"strcpy(strings[ssp++],\\\"{}\\\");\\n\".format(preprocessor_str_const[x.replace(\"p@\",\"\")]))\n elif x.startswith(\"'\"):\n push(str(ord(x[1])))\n elif x == \"+\":\n adds()\n elif x == \"-\":\n subs()\n elif x == \"*\":\n muls()\n elif x == \"/\":\n divs()\n elif x == \"exit\":\n pop(\"x\")\n out.write(\"exit(x);\")\n elif x == \"%\":\n pop(\"x\")\n pop(\"y\")\n out.write(\"x = y % x;\\n\")\n push(\"x\")\n elif x == \",\":\n out.write(\"scanf(\\\"%d\\\", &x);\\n\")\n push(\"x\")\n elif x == \"if\":\n pop(\"x\")\n pop(\"y\")\n out.write(\"if (\")\n elif x == \"==\":\n out.write(\"x == y){\\n\")\n elif x == \"!=\":\n out.write(\"x != y){\\n\")\n elif x == \">\":\n out.write(\"x > y){\\n\")\n elif x == \"<\":\n out.write(\"x < y){\\n\")\n elif x == \"<=\":\n out.write(\"x <= y){\\n\")\n elif x == \">=\":\n out.write(\"x >= y){\\n\")\n elif x == \"end\":\n out.write(\"}\\n\")\n elif x == \"endl\":\n out.write(\"}\\n\")\n current_loop -= 1\n elif x == '\"':\n stringmode = True\n elif x == \"loop\":\n pop(\"x\")\n out.write(\"int loop_\" + str(loops) + \" = x;\\n\")\n out.write(\"int loop_counter_\" + str(loops) + \"= 0;\\n\")\n out.write(f\"while(loop_counter_{str(loops)} < loop_{str(loops)})\"+\"{\\n\")\n out.write(f\"loop_counter_\"+str(loops)+\"++;\\n\")\n loops += 1\n current_loop += 1\n elif x == \"setvar\":\n pop(\"x\")\n pop(\"y\")\n out.write(\"variables[x] = y;\\n\")\n elif x == \"getvar\":\n pop(\"x\")\n out.write(\"y = variables[x];\\n\")\n push(\"y\")\n elif x == \"//\":\n comment = True\n elif x == \"loopf\":\n out.write(\"while(1){\")\n elif x == \"break\":\n out.write(\"break;\\n\")\n elif x == \"sleep\":\n pop(x)\n out.write(\"usleep(x*1000);\\n\")\n elif x == \"fflush\":\n pop(x)\n out.write(\"fflush(FILE_BUFFER[x]);\\n\")\n elif x == \"cwrite\":\n pop(\"x\")\n pop(\"y\")\n out.write(\"fputc((char)y, FILE_BUFFER[x]);\\n\")\n elif x == \"swrite\":\n pop(\"x\")\n out.write(\"fputs(strings[--ssp],FILE_BUFFER[x]);\\n\")\n elif x == \"ofw\": # open file write\n pop(\"x\")\n out.write(\"if (x >= 10){\\n\")\n out.write(\"printf(\\\"File number too large!\\\\n\\\");\\n\")\n out.write(\"exit(1);\\n\")\n out.write(\"}\\n\")\n out.write(\"FILE_BUFFER[x] = fopen(strings[--ssp], \\\"w\\\");\\n\")\n out.write(\"if (FILE_BUFFER == NULL){\\n\")\n out.write(\"printf(\\\"File error!\\\\n\\\");\")\n out.write(\"exit(1);\\n\")\n out.write(\"}\\n\")\n elif x == \"close\":\n pop(\"x\")\n out.write(\"if (FILE_BUFFER[x] == NULL){\")\n out.write(\"printf(\\\"ERROR: File never opened..\\\\n\\\");\\n\")\n out.write(\"exit(1);}\\n\")\n out.write(\"fclose(FILE_BUFFER[x]);\\n\")\n elif x == \"continue\":\n out.write(\"continue;\\n\")\n elif x == \"plc\":\n out.write(\"x = loop_counter_\"+str(current_loop-1)+\";\\n\")\n push(\"x\")\n elif x == \"its\":\n pop(\"x\")\n out.write(\"sprintf(strings[ssp++], \\\"%\"+\"d\\\", x);\\n\")\n elif x == \"sti\":\n out.write(\"x = atoi(strings[--ssp]);\\n\")\n push(\"x\")\n elif x == \"argv\":\n pop(\"x\")\n out.write(\"strcpy(strings[ssp++], argv[x]);\\n\")\n elif x == \">R\":\n pop(\"x\")\n out.write(\"temp[tsp++] = x;\\n\")\n elif x == \"R>\":\n out.write(\"x = temp[--tsp];\\n\")\n push(\"x\")\n elif x == \"@>R\":\n pop(\"x\")\n out.write(\"temp[tsp++] = x;\\n\")\n push(\"x\")\n elif x == \"strdup\":\n out.write(\"strcpy(sb1,strings[--ssp]);\\n\")\n out.write(\"strcpy(strings[ssp++],sb1);\\n\")\n out.write(\"strcpy(strings[ssp++],sb1);\\n\")\n elif x == \"strcmp\":\n out.write(\"if(strcmp(strings[--ssp],strings[--ssp]) == 0){\\n\")\n push(1)\n out.write(\"}\\n\")\n out.write(\"else{\\n\")\n push(0)\n out.write(\"}\\n\")\n elif x == \"proc\":\n out.write(\"int proc_\")\n proc = True\nif sys.argv[1] == \"install\":\n os.system(\"cp ./fifthc.py /usr/bin/fifthc\")\n print(\" ./fifthc.py > /usr/bin/fifthc \")\n os.system(\"cp ./std.fc /opt/fifthc/std.fc\")\n print(\" ./std.fc > /opt/fifthc/std.fc \")\n os.system(\"cp ./colors.fc /opt/fifthc/colors.fc\")\n print(\" ./colors.fc > /opt/fifthc/colors.fc \")\n print(\"Installed!\")\n print(\"Testing..\")\n os.system(\"fifthc test.fc && ./fout\")\n os.remove(\"fout\")\n exit()\ndef com():\n out.write(\"#include \\n\")\n out.write(\"#include \\n\")\n out.write(\"#include \\n\")\n out.write(\"#include \\n\")\n out.write(\"#include \\n\")\n out.write(\"int x,y;\\n\")\n out.write(\"FILE * FILE_BUFFER[11];\\n\")\n out.write(\"char sb1[512];\\n\")\n out.write(\"char sb2[512];\\n\")\n out.write(\"int stack[1024];\\n\")\n out.write(\"int stack_ptr = 0;\\n\")\n out.write(\"int variables[512];\\n\")\n out.write(\"int temp[10];\\n\")\n out.write(\"int tsp;\\n\")\n out.write(\"char strings[20][512];\\n\")\n out.write(\"int ssp;\\n\")\n compile_time_start = time.perf_counter()\n preprocessor_program = open(sys.argv[1], \"r\").read()\n preprocess(preprocessor_program)\n program = open(sys.argv[1], \"r\").read().replace(\"\\n\",\" \").replace(\"\\t\",\"\").split(\" \")\n compile(program)\n out.write(\"int main(int argc, char *argv[]){\\n\")\n out.write(\"FILE_BUFFER[10] = stdout;\\n\")\n out.write(\"proc_main();}\\n\")\n out.close()\n compile_time_end = time.perf_counter()\n compile_time = round((compile_time_end - compile_time_start) * 1000 * 1000) # in microseconds\n print(\"Transpile time: \" + str(compile_time) + \"μs\")\n compile_time_start = time.perf_counter()\n os.system(\"gcc out.c -o fout\")\n #os.remove(\"out.c\")\n compile_time_end = time.perf_counter()\n compile_time = round((compile_time_end - compile_time_start) * 1000)\n print(\"Compile time: \" + str(compile_time) + \"ms\")\ncom()","repo_name":"poggingfish/fifthc","sub_path":"fifthc.py","file_name":"fifthc.py","file_ext":"py","file_size_in_byte":11236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"36899428746","text":"from typing import List, Optional\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nimport numpy as np\n\nLIME_VIZ_CMAP = matplotlib.colors.ListedColormap(['white', 'royalblue'])\n\n\ndef _argsort_bin(b):\n # https://stackoverflow.com/a/46953582\n b_view = np.ascontiguousarray(b).view(np.dtype((np.void, b.dtype.itemsize * b.shape[1])))\n return np.argsort(b_view.ravel())\n\n\ndef visualize_lime_internals(sequence_tokens: List[str], token_mask, probabilities,\n width_per_sample: Optional[float] = 0.1,\n height_per_token: Optional[float] = 0.1,\n file_path: Optional[str] = None,\n allow_large_samples: Optional[bool] = False,\n sort_key: Optional[str] = None,\n **kwargs):\n \"\"\" Plot predicted probability as a function of feature indicators used in LIME. The plot is a combination of\n two subplots:\n (1) scatterplot displaying the probabilities for samples (top)\n (2) binary heatmap displaying whether a word is present in a certain sample or not (*)\n\n (*) Note that this is the behaviour in default LIME. The actual interpretation of values 0/1 in `token_mask` is up\n to the caller.\n\n Args:\n sequence_tokens:\n List of words in the sequence. Shape: [num_samples]\n token_mask:\n 0/1 matrix that determines whether a token is present in sample. Shape: [num_samples, num_tokens]\n probabilities:\n Probabilities for samples provided via `token_mask`. Shape: [num_samples]\n width_per_sample:\n Width (in inches) that each sample is assigned. Total figure width is num_samples * width_per_sample.\n file_path:\n Where to save the figure. If not provided, displays the plot on screen.\n allow_large_samples:\n Disable safeguard that prevents the user from visualizing too big samples.\n sort_key:\n Plot samples in ascending sorted order, guided by this key. Possible choices are\n 'token_mask' (sort by binary value of masks), 'probabilities' (sort by probabilities) or None (don't sort).\n **kwargs:\n Additional plotting arguments (`ylabel`).\n \"\"\"\n MAX_INTENDED_SAMPLES = 1000\n _token_mask = token_mask if isinstance(token_mask, np.ndarray) else np.array(token_mask)\n _probabilities = probabilities if isinstance(probabilities, np.ndarray) else np.array(probabilities)\n\n _token_mask = _token_mask.astype(np.bool)\n num_samples = _token_mask.shape[0]\n\n if num_samples > MAX_INTENDED_SAMPLES and not allow_large_samples:\n raise ValueError(f\"Visualization is not intended to be used with such a large sample \"\n f\"({num_samples} > {MAX_INTENDED_SAMPLES}) as it can become extremely large and convoluted. \"\n f\"To disable this check, pass `allow_large_samples=True`.\")\n\n if sort_key == \"token_mask\":\n sort_inds = _argsort_bin(_token_mask)\n elif sort_key == \"probabilities\":\n sort_inds = np.argsort(_probabilities)\n elif sort_key == \"nnz\":\n sort_inds = np.argsort(np.sum(_token_mask, axis=1))\n elif sort_key is not None:\n raise ValueError(f\"Unrecognized sort key '{sort_key}'\")\n else:\n sort_inds = np.arange(num_samples)\n\n _token_mask = _token_mask[sort_inds].T # [num_tokens, num_samples]\n _probabilities = _probabilities[sort_inds]\n num_tokens = len(sequence_tokens)\n\n # Top plot is fixed to a reasonable height, bottom height can be adjusted if visualizing long sequence\n fig1_height = 3.0\n fig2_height = num_tokens * height_per_token\n\n fig, ax = plt.subplots(2, 1, gridspec_kw={\"wspace\": 0.0, \"hspace\": 0.0,\n \"height_ratios\": [fig1_height, fig2_height]})\n fig.set_figwidth(num_samples * width_per_sample)\n fig.set_figheight(fig1_height + fig2_height)\n fig.subplots_adjust(wspace=0, hspace=0)\n\n ax[0].plot(np.arange(num_samples) + 0.5, _probabilities, \"bo\", linestyle=\"none\")\n ax[0].set_xlim([0, num_samples])\n ax[0].set_xticks(np.arange(num_samples))\n ax[0].set_xticklabels([\"\"] * num_samples)\n ax[0].set_yticks(np.arange(0.0, 1.0 + 1e-5, 0.2))\n ax[0].set_ylabel(kwargs.get(\"ylabel\", \"Probability\"))\n ax[0].grid(which=\"both\", linestyle=\"--\")\n # Remove space before 0\n ax[0].margins(x=0)\n\n ax[1].pcolormesh(_token_mask.astype(np.int32)[::-1],\n antialiased=True, cmap=LIME_VIZ_CMAP, edgecolors='black', linewidths=0.5)\n ax[1].set_xticks([])\n ax[1].set_yticks(np.arange(num_tokens) + 0.5)\n ax[1].set_yticklabels(sequence_tokens[::-1])\n ax[1].set_xlabel(\"Samples\")\n\n plt.tight_layout()\n\n if file_path is not None:\n plt.savefig(file_path)\n else:\n plt.show()\n\n plt.clf()\n\n\nif __name__ == \"__main__\":\n sequence = [\"$This$\", \"$is$\", \"$the$\", \"$most$\", \"$useless$\", \"$product$\", \"$I$\", \"$have$\", \"$ever$\", \"$seen$\"]\n mask = np.array([\n [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n [1, 0, 1, 0, 1, 0, 1, 0, 1, 0]\n ])\n probas = np.array([\n 0.9,\n 0.2\n ])\n\n visualize_lime_internals(sequence, token_mask=mask, probabilities=probas,\n width_per_sample=3.0, sort_key=\"token_mask\")\n","repo_name":"matejklemen/pete","sub_path":"explain_nlp/visualizations/internal.py","file_name":"internal.py","file_ext":"py","file_size_in_byte":5340,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"77"}
+{"seq_id":"1662373620","text":"import copy\nfrom abc import ABC\n\nimport torch.nn as nn\n\n# Create a model that copies the last layers of a transformer model. This enables us to intervene or insert new\n# embeddings within the model and see what the output would be.\n# Core functionality is in TailTransformer (the tail end of the model), with specific classes for different types\n# of models (e.g., cloze vs. QA)\n\n\nclass TailTransformer(nn.Module, ABC):\n def __init__(self, qa_model, layer_idx):\n super().__init__()\n # Taken from: https://huggingface.co/transformers/_modules/transformers/modeling_bert.html#BertModel\n self.transformer = copy.deepcopy(qa_model.base_model.encoder)\n self.layers = nn.ModuleList(self.transformer.layer[layer_idx:])\n self.transformer.layer = self.layers\n\n def forward(self, x):\n hidden_inputs = {'hidden_states': x}\n outputs = self.transformer(**hidden_inputs)\n return outputs\n\n\n# Model the last few layers of a pre-trained Transformer-based Question-Answering model.\n# Just leverages the tail end of the transformer plus the linear layer at the end, which is used for logits over\n# the start and end tokens.\nclass QATail(nn.Module):\n def __init__(self, qa_model, layer_idx):\n super().__init__()\n self.transformer = TailTransformer(qa_model, layer_idx)\n self.last_layer = qa_model.qa_outputs\n\n def forward(self, x):\n transformer_output = self.transformer(x)[0]\n logits = self.last_layer(transformer_output)\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1) # (bs, max_query_len)\n end_logits = end_logits.squeeze(-1) # (bs, max_query_len)\n return start_logits, end_logits\n\n# Model for cloze task, which predicts a missing word.\nclass ClozeTail(nn.Module):\n def __init__(self, cloze_model, layer_idx):\n super(ClozeTail, self).__init__()\n self.transformer = TailTransformer(cloze_model, layer_idx)\n self.last_layer = cloze_model.cls\n\n def forward(self, x):\n transformer_output = self.transformer(x)[0]\n logits = self.last_layer(transformer_output)\n return logits","repo_name":"mycal-tucker/causal-probe","sub_path":"src/models/intervention_model.py","file_name":"intervention_model.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"43751001322","text":"from qdrant_client import QdrantClient\nfrom qdrant_client.models import Distance, VectorParams\n\nimport numpy as np\nfrom qdrant_client.models import PointStruct\n\ndata_path = \"vector.db\"\n\nclient = QdrantClient(path=data_path)\n\n\nclient.recreate_collection(\n collection_name=\"my_collection\",\n vectors_config=VectorParams(size=100, distance=Distance.COSINE),\n)\n\n\nvectors = np.random.rand(100, 100)\nvectors = (vectors - 0.5) * 2\nprint(vectors[0])\n\n\npoints = []\nrun_id = 1\n\nfor idx, vector in enumerate(vectors):\n ps = PointStruct(\n id = idx + (run_id * 100),\n vector = vector.tolist(),\n payload = {\"id\": idx, \"run\": run_id}\n )\n points.append(ps)\n\nclient.upsert(\n collection_name=\"my_collection\",\n points=points\n)\n\n\nquery_vector = np.random.rand(100)\nquery_vector = (query_vector -0.5) * 2\nhits = client.search(\n collection_name=\"my_collection\",\n query_vector=query_vector,\n limit=5 # Return 5 closest points\n)\n\nfor result in hits:\n print(result)\n\n","repo_name":"faush01/FacialRecognition","sub_path":"scripts/vector_example.py","file_name":"vector_example.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"29400451185","text":"\"\"\"Connect to a PostgreSQL database and execute queries\"\"\"\n\nimport sys, os\nimport psycopg2\nfrom dotenv import load_dotenv\nimport pandas as pd\n\nclass Database:\n \"\"\"PostgreSQL Database class\"\"\"\n\n def __init__(self):\n load_dotenv()\n self.host = os.getenv('DATABASE_HOST')\n self.username = os.getenv('DATABASE_USERNAME')\n self.password = os.getenv('DATABASE_PASSWORD')\n self.port = os.getenv('DATABASE_PORT')\n self.dbname = os.getenv('DATABASE_NAME')\n self.conn = None\n\n\n def connect(self):\n \"\"\"Connect to a Postgres database.\"\"\"\n if self.conn is None:\n try:\n self.conn = psycopg2.connect(host=self.host,\n user=self.username,\n password=self.password,\n port=self.port,\n dbname=self.dbname)\n except psycopg2.DatabaseError as e:\n print('Error in connecting to database ', e)\n sys.exit()\n\n\n def select_rows(self, query, *args):\n \"\"\"Run a SQL query to select rows from table\"\"\"\n self.connect()\n with self.conn.cursor() as cur:\n cur.execute(query, args)\n records = [row for row in cur.fetchall()]\n cur.close()\n return records\n\n\n def select_df(self, query, *args):\n \"\"\"Run a SQL query to select rows from table and return pandas dataframe\"\"\"\n self.connect()\n dat = pd.read_sql_query(query, self.conn)\n self.conn = None\n return dat\n\n def insert_row(self, query, *args):\n \"\"\"Run a SQL query to update rows in table\"\"\"\n try:\n self.connect()\n with self.conn.cursor() as cur:\n # cur.mogrify(query, args)\n cur.execute(query, args)\n self.conn.commit()\n cur.close()\n except Exception as e:\n self.conn.rollback()\n # get details about the exception\n e_type, e_obj, traceback = sys.exc_info()\n # get the line number when exception occured\n line_num = traceback.tb_lineno\n # print the connect() error\n print (\"\\npsycopg2 ERROR:\", e, \"on line number:\", line_num)\n print (\"psycopg2 traceback:\", traceback, \"-- type:\", e_type)\n\n def insert_rows(self, query, *args):\n \"\"\"Run a SQL query to update rows in table\"\"\"\n self.connect()\n with self.conn.cursor() as cur:\n cur.executemany(query, args)\n self.conn.commit()\n cur.close()\n","repo_name":"WAzaizeh/Halal_o_Meter","sub_path":"src/data/data_collection/storage_managers/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":2663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"26201244879","text":"import csv\n\nfrom itertools import islice\n\nfrom django.core.management.base import BaseCommand\n\nfrom rsvp.models import Invitation, Guest\n\nFIRST = 'First Name(s)'\nLAST = 'Last Name(s)'\nADDY = 'Address'\nEMAIL = 'Email'\nFIELDS = [FIRST, LAST, ADDY, EMAIL]\n\n\nclass Command(BaseCommand):\n help = 'Imports guests from a given CSV file'\n\n def add_arguments(self, parser):\n parser.add_argument('csvfile', help='file path to the csv file')\n parser.add_argument('-d', '--dry-run', action='store_true', default=False)\n\n def handle(self, *args, **options):\n rows = []\n with open(options['csvfile']) as file:\n reader = csv.DictReader(islice(file, 3, None))\n for row in reader:\n rows.append({col: row[col] for col in row if col in FIELDS})\n rows = self.find_pairs(rows)\n\n for row in rows:\n if not options['dry_run']:\n invite = self.make_invite(row)\n guest = self.make_guest(row, invite)\n print(\"Added {} to {}\".format(guest, invite))\n else:\n print(\"Invitation: {}\".format(row[ADDY]))\n print(\"Has Plus One?: {}\".format(row.get('has_plus_one', False)))\n print (\"Guest: {} {}\".format(row.get(FIRST), row.get(LAST)))\n print(\"Is Plus One?: {}\".format(row.get('is_plus_one', False)))\n\n def find_pairs(self, rows):\n new_rows = []\n last_row = {}\n for row in rows:\n if 'Guest' in row[LAST] or 'Guest' in row[FIRST]:\n # skip this row if they don't actually have a name\n continue\n if not (row.get(FIRST) or row.get(LAST)):\n # skip if they don't have names\n continue\n if 'Guest' in row.get(ADDY, ''):\n # mark this invite as having a plus one\n row['has_plus_one'] = True\n if not row.get(ADDY) and 'Guest' in last_row.get(ADDY, ''):\n # this person is a plus one if they don't have an address\n # and previous row listed a guest\n row['is_plus_one'] = True\n if not row.get(ADDY) and last_row.get(ADDY):\n # no address for this person\n # they're probably part of the previous invite\n row[ADDY] = last_row.get(ADDY)\n new_rows.append(row)\n last_row = row\n return new_rows\n\n def make_invite(self, row):\n try:\n invite = Invitation.objects.get(address=row[ADDY])\n except Invitation.DoesNotExist:\n invite = Invitation.objects.create(\n address=row[ADDY],\n plus_one=row.get('has_plus_one', False),\n )\n return invite\n\n def make_guest(self, row, invite):\n guest = Guest.objects.create(\n first_name=row[FIRST],\n last_name=row[LAST],\n email=row.get(EMAIL),\n is_plus_one=row.get('is_plus_one', False),\n invitation=invite,\n )\n return guest\n","repo_name":"noslouch/wedding-api","sub_path":"rsvp/management/commands/import_invites.py","file_name":"import_invites.py","file_ext":"py","file_size_in_byte":3062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"31843530709","text":"from typing import List\n\nfrom asyncpg import Connection\nfrom fastapi import Depends, FastAPI, status\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi.routing import APIRoute\n\nfrom .auth import get_current_user\nfrom .database import get_db\nfrom .models import Game, Player, PlayerScore, PlayerStatus, PlayerStatusPatch, User\n\napp = FastAPI()\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n\n@app.get(\"/\")\ndef healthcheck():\n return \"ok\"\n\n\n@app.get(\"/games\", response_model=List[Game])\ndef get_games(user: User = Depends(get_current_user), db: Connection = Depends(get_db)):\n \"\"\"Get the current user's games.\"\"\"\n raise NotImplementedError()\n\n\n@app.post(\"/games\", status_code=status.HTTP_201_CREATED, response_model=Game)\ndef create_game(\n user: User = Depends(get_current_user),\n db: Connection = Depends(get_db),\n):\n \"\"\"Create a new game owned by the current user.\"\"\"\n raise NotImplementedError()\n\n\n@app.post(\"/games/{gid}/join-request\", status_code=status.HTTP_204_NO_CONTENT)\ndef create_join_request(\n gid: str, user: User = Depends(get_current_user), db: Connection = Depends(get_db)\n):\n \"\"\"Create a new join request for a given game.\"\"\"\n\n\n@app.get(\"/games/{gid}/my-status\", response_model=PlayerStatus)\ndef get_my_status(\n gid: str, user: User = Depends(get_current_user), db: Connection = Depends(get_db)\n):\n \"\"\"Get the current user's status in a given game.\"\"\"\n return PlayerStatus(is_active=False, has_hunter=False, prey_name=None)\n\n\n@app.patch(\"/games/{gid}/my-status\", status_code=status.HTTP_204_NO_CONTENT)\ndef patch_my_status(\n gid: str,\n patch: PlayerStatusPatch,\n user: User = Depends(get_current_user),\n db: Connection = Depends(get_db),\n):\n \"\"\"Update the current user's status in a given game.\"\"\"\n return \"ok\"\n\n\n@app.get(\"/games/{gid}/scores\", response_model=List[PlayerScore])\ndef get_scores(\n gid: str, user: User = Depends(get_current_user), db: Connection = Depends(get_db)\n):\n \"\"\"Get the current user's status in a given game.\"\"\"\n return []\n\n\n@app.post(\"/games/{gid}/assassinations\", status_code=status.HTTP_204_NO_CONTENT)\ndef create_assassination(\n gid: str, user: User = Depends(get_current_user), db: Connection = Depends(get_db)\n):\n \"\"\"Record an assassination of the current user.\"\"\"\n return \"ok\"\n\n\n@app.get(\"/games/{gid}/admin/players\", response_model=List[Player])\ndef get_players(\n gid: int,\n user: User = Depends(get_current_user),\n db: Connection = Depends(get_db),\n):\n \"\"\"Get players in a given game. Only callable by game owner.\"\"\"\n return []\n\n\n@app.delete(\"/games/{gid}/admin/players/{pid}\", status_code=status.HTTP_204_NO_CONTENT)\ndef delete_player(\n gid: int,\n pid: int,\n user: User = Depends(get_current_user),\n db: Connection = Depends(get_db),\n):\n \"\"\"Remove a given player from the game. Only callable by game owner.\"\"\"\n\n\n@app.post(\n \"/games/{gid}/admin/players/{pid}/approval\", status_code=status.HTTP_204_NO_CONTENT\n)\ndef approve_player(\n gid: int,\n pid: int,\n user: User = Depends(get_current_user),\n db: Connection = Depends(get_db),\n):\n \"\"\"Get players in a given game. Only callable by game owner.\"\"\"\n return []\n\n\n@app.post(\"/games/{gid}/admin/archive\", status_code=status.HTTP_204_NO_CONTENT)\ndef archive_game(\n gid: int,\n user: User = Depends(get_current_user),\n db: Connection = Depends(get_db),\n):\n \"\"\"Archive a given game. Only callable by game owner.\"\"\"\n\n\nfor route in app.routes:\n if isinstance(route, APIRoute):\n route.operation_id = route.name\n","repo_name":"thetimmorland/assassin-api","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"6047256587","text":"from Data_Downloader import FuturesDailyDataDownloader, N2FuturesDailyDataDownloader\nimport sys\n\nif __name__ == '__main__':\n if sys.argv[5] == 'n1':\n for i in range(int(sys.argv[2]), int(sys.argv[3]) + 1):\n fut_data_downloader = FuturesDailyDataDownloader(\n symbol=sys.argv[1],\n contract_month=int(sys.argv[4]),\n contract_year=i\n )\n\n fut_data_downloader.download_data()\n\n elif sys.argv[5] == 'n2':\n for i in range(int(sys.argv[2]), int(sys.argv[3]) + 1):\n fut_data_downloader = N2FuturesDailyDataDownloader(\n symbol=sys.argv[1],\n contract_month=int(sys.argv[4]),\n contract_year=i\n )\n\n fut_data_downloader.download_data()\n","repo_name":"Green-Canvas-Partners/Barchart-Data-Pipeline","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"72649315770","text":"import pandas as pd\nimport numpy as np\n\n\nclass MarkovChainAttribution:\n def __init__(self, data, null_exists):\n \"\"\"\n :param data: a dataframe with path, total_conversions columns\n :param null_exists: whether data's path only have conversion or have conversion and null\n \"\"\"\n self.data = data\n self.null_exists = null_exists\n\n @staticmethod\n def list_to_char(input_list):\n output_str = \"\"\n for idx, element in enumerate(input_list):\n if idx == 0:\n output_str = str(element).replace(\"'\", '')\n else:\n output_str = output_str + ' > ' + str(element).replace(\"'\", '')\n return output_str\n\n def markov_chain_preprocessing(self):\n \"\"\" Markov chain attribution model have single path problem. While calculating removal_effects, single path lose\n its own conversions to other channels. Assume single path 'start -> A -> A -> Conversion : 11' In markov chain\n attribution, A cannot take whole 11 conversions. Finally single channel's are undervalued and attribution distorted.\n Therefore, split data to single, multi channel. And run markov chain model for only multichannel data.\n :return: singlechannel data, multichannel data\n \"\"\"\n\n self.data['Unique Path Num'] = self.data['path'].apply(lambda x: len(list(set(x))))\n singlechnl_df = self.data.loc[self.data['Unique Path Num'] == 1]\n singlechnl_df['path'] = singlechnl_df['path'].apply(lambda x: x[0])\n singlechnl_df = singlechnl_df.drop(['Unique Path Num'], axis=1)\n\n multichnl_df = self.data.loc[self.data['Unique Path Num'] != 1]\n multichnl_df = multichnl_df.drop(['Unique Path Num'], axis=1)\n multichnl_df['path'].apply(lambda x: x.insert(0, 'start'))\n multichnl_df['path'].apply(lambda x: x.append('conv'))\n multichnl_df['path'] = multichnl_df['path'].apply(self.list_to_char)\n multichnl_df = multichnl_df.reindex(multichnl_df.index.repeat(multichnl_df.total_conversions)) #for kolon's data.\n multichnl_df = multichnl_df.drop(['total_conversions'], axis=1)\n multichnl_df.columns = ['Paths']\n\n if not self.null_exists:\n null_row = {'Paths': 'start > Kobby > Jayden > null'}\n multichnl_df = multichnl_df.append(null_row, ignore_index=True)\n\n return singlechnl_df, multichnl_df\n\n def cal_removal_effect(self, df, cvr):\n \"\"\" Calculate removal effect. Removal Effect(i) = {1-P(S without i)/P(S)}*100 (%)\n In this code, solve Loop Issue by using markov matrix's stability. Due to markov matrix's stability, we can\n assume steady state.\n :param df: channel data\n :param cvr: conversion rate\n :return:\n \"\"\"\n removal_effect_res = dict()\n channels = df.drop(['conv', 'null', 'start'], axis=1).columns\n for channel in channels:\n removal_df = df.drop(channel, axis=1)\n removal_df = removal_df.drop(channel, axis=0)\n for col in removal_df.columns:\n trans_prob_sum = np.sum(list(removal_df.loc[col]))\n null_prob = float(1) - trans_prob_sum\n if null_prob == 0:\n continue\n else:\n removal_df.loc[col]['null'] = null_prob\n removal_df.loc['null']['null'] = 1.0\n R = removal_df[['null', 'conv']]\n R = R.drop(['null', 'conv'], axis=0)\n Q = removal_df.drop(['null', 'conv'], axis=1)\n Q = Q.drop(['null', 'conv'], axis=0)\n t = len(Q.columns)\n # Markov Matrix's absolute stability -> steady state\n N = np.linalg.inv(np.identity(t) - np.asarray(Q))\n M = np.dot(N, np.asarray(R))\n\n removal_cvr = pd.DataFrame(M, index=R.index)[[1]].loc['start'].values[0]\n removal_effect = 1.0 - removal_cvr / cvr\n removal_effect_res[channel] = removal_effect\n\n return removal_effect_res\n\n\n def cal_markov_chain_attribution(self, multichnl_df):\n \"\"\" Calculate markov chain attribution\n :param multichnl_df: multichannel path data\n :return: markov chain attribution data\n \"\"\"\n paths = np.array(multichnl_df).tolist()\n sublist = []\n total_paths = 0\n for path in paths:\n for touchpoint in path:\n userpath = touchpoint.split(' > ')\n sublist.append(userpath)\n total_paths += 1\n paths = sublist\n\n unique_touch_list = set(x for element in paths for x in element)\n conv_dict = {}\n total_conversions = 0\n for item in unique_touch_list:\n conv_dict[item] = 0\n for path in paths:\n if 'conv' in path:\n total_conversions += 1\n conv_dict[path[-2]] += 1\n\n transitionStates = {}\n for x in unique_touch_list:\n for y in unique_touch_list:\n transitionStates[x + \">\" + y] = 0\n\n for possible_state in unique_touch_list:\n if possible_state != \"null\" and possible_state != \"conv\":\n for user_path in paths:\n if possible_state in user_path:\n indices = [i for i, s in enumerate(user_path) if possible_state == s]\n for col in indices:\n transitionStates[user_path[col] + \">\" + user_path[col + 1]] += 1\n\n transitionMatrix = []\n actual_paths = []\n for state in unique_touch_list:\n if state != \"null\" and state != \"conv\":\n counter = 0\n index = [i for i, s in enumerate(transitionStates) if s.startswith(state + '>')]\n for col in index:\n if transitionStates[list(transitionStates)[col]] > 0:\n counter += transitionStates[list(transitionStates)[col]]\n for col in index:\n if transitionStates[list(transitionStates)[col]] > 0:\n state_prob = float((transitionStates[list(transitionStates)[col]])) / float(counter)\n actual_paths.append({list(transitionStates)[col]: state_prob})\n transitionMatrix.append(actual_paths)\n\n flattened_matrix = [item for sublist in transitionMatrix for item in sublist]\n transState = []\n transMatrix = []\n for item in flattened_matrix:\n for key in item:\n transState.append(key)\n for key in item:\n transMatrix.append(item[key])\n\n tmatrix = pd.DataFrame({'paths': transState,\n 'prob': transMatrix})\n tmatrix = tmatrix.join(tmatrix['paths'].str.split('>', expand=True).add_prefix('channel'))[\n ['channel0', 'channel1', 'prob']]\n column = list()\n for k, v in tmatrix.iterrows():\n if v['channel0'] in column:\n continue\n else:\n column.append(v['channel0'])\n test_df = pd.DataFrame()\n for col in unique_touch_list:\n test_df[col] = 0.00\n test_df.loc[col] = 0.00\n for k, v in tmatrix.iterrows():\n x = v['channel0']\n y = v['channel1']\n val = v['prob']\n test_df.loc[x][y] = val\n test_df.loc['conv']['conv'] = 1.0\n test_df.loc['null']['null'] = 1.0\n R = test_df[['null', 'conv']]\n R = R.drop(['null', 'conv'], axis=0)\n Q = test_df.drop(['null', 'conv'], axis=1)\n Q = Q.drop(['null', 'conv'], axis=0)\n O = pd.DataFrame()\n t = len(Q.columns)\n for col in range(0, t):\n O[col] = 0.00\n for col in range(0, len(R.columns)):\n O.loc[col] = 0.00\n N = np.linalg.inv(np.identity(t) - np.asarray(Q))\n M = np.dot(N, np.asarray(R))\n cvr = pd.DataFrame(M, index=R.index)[[1]].loc['start'].values[0]\n removal_effects = self.cal_removal_effect(test_df, cvr)\n denominator = np.sum(list(removal_effects.values()))\n allocation_amount = list()\n for i in removal_effects.values():\n allocation_amount.append((i / denominator) * total_conversions)\n markov_conversions = dict()\n i = 0\n for channel in removal_effects.keys():\n markov_conversions[channel] = allocation_amount[i]\n i += 1\n conv_dict.pop('conv', None)\n conv_dict.pop('null', None)\n conv_dict.pop('start', None)\n\n return markov_conversions\n\n\n def run(self):\n singlechnl_df, multichnl_df = self.markov_chain_preprocessing()\n multichnl_markov_res = self.cal_markov_chain_attribution(multichnl_df)\n multichnl_attr_df = pd.DataFrame.from_dict(multichnl_markov_res, orient='index').reset_index()\n markov_chain_attribution = pd.concat([singlechnl_df, multichnl_attr_df], sort=False)\n markov_chain_attribution = markov_chain_attribution.groupby('path')['total_conversions'].sum().to_frame()\n markov_chain_attribution['total_conversions'] = markov_chain_attribution['total_conversions'].map(int)\n markov_chain_attribution = markov_chain_attribution.sort_values(by=['total_conversions'], ascending=False)\n\n return markov_chain_attribution\n\nif __name__ == '__main__':\n data = pd.read_csv('sample_data.csv')\n data['path'] = data['path'].apply(lambda x: x.replace(\"'\", \"\").replace('[', '').replace(']', '').replace(' ', '').split(','))\n\n markov_chain_attribution = MarkovChainAttribution(data=data, null_exists=False)\n markov_chain_res = markov_chain_attribution.run()\n print(markov_chain_res)\n","repo_name":"junsoo37/Data-Driven-Attribution","sub_path":"markov_chain.py","file_name":"markov_chain.py","file_ext":"py","file_size_in_byte":9693,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"16203765735","text":"import math\n\ndef quadro(a,b,c):\n delt = b*b - 4*a*c\n\n if delt<0:\n print('vo nghiem')\n elif delt == 0:\n print('Nghiem: ' + str(-b/(2*a)))\n else:\n print('Nghiem 1: ' + str((-b-math.sqrt(delt))/(2*a)))\n print('Nghiem 2: ' + str((-b+math.sqrt(delt))/(2*a)))\n\na = int(input('a: '))\nb = int(input('b: '))\nc = int(input('c: '))\n\nquadro(a, b, c)\n","repo_name":"L-Q-K/C4TAdHW","sub_path":"Test/test9.py","file_name":"test9.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"43435706414","text":"import os\n\ndef openChromeTab(url):\n\tcommand = \"\"\"/usr/bin/open -a \"/Applications/Google Chrome.app\" '{0}'\"\"\".format(url)\n\tos.system(command)\n\ndef openMultipleChromeTabs(urls):\n\turlList = \" \".join(urls)\n\tcommand = \"\"\"\n\t\tosascript \\\n\t\t\t-e 'on run(theUrls)' \\\n\t\t\t-e ' tell app id \"com.google.chrome\" to tell make new window' \\\n\t\t\t-e ' repeat with theUrl in theUrls' \\\n\t\t\t-e ' set newTab to make new tab ¬' \\\n\t\t\t-e ' with properties {{ url: theUrl }}' \\\n\t\t\t-e ' end repeat' \\\n\t\t\t-e ' tell tab 1 to close' \\\n\t\t\t-e ' end tell' \\\n\t\t\t-e 'end run' \\\n\t\t{0}\n\t\"\"\".format(urlList)\n\tos.system(command)\n\ndef openMultipleChromeWindows(windows):\n\tfor window in windows:\n\t\topenMultipleChromeTabs(window)","repo_name":"wmaxlloyd/customKeyboardEvents","sub_path":"keyboardActions/commands/chrome.py","file_name":"chrome.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"19384448699","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.contrib.gis.db.models.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='PlaceCategory',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('category_name', models.CharField(unique=True, max_length=128, verbose_name='Category Name')),\n ('description', models.TextField(verbose_name='Category Desc')),\n ('is_active', models.BooleanField(default=True, verbose_name='Active Category')),\n ('image', models.ImageField(upload_to=b'categories', null=True, verbose_name='Image', blank=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='PlaceDetail',\n fields=[\n ('place_id', models.CharField(max_length=1024, unique=True, serialize=False, verbose_name='Place ID', primary_key=True)),\n ('place_name', models.CharField(max_length=128, verbose_name='Place Name', blank=True)),\n ('address', models.CharField(max_length=1024, null=True, verbose_name='Address', blank=True)),\n ('state', models.CharField(max_length=64, verbose_name='State', blank=True)),\n ('country', models.CharField(max_length=64, verbose_name='Country', blank=True)),\n ('postcode', models.CharField(max_length=30, verbose_name='Post Code', blank=True)),\n ('opening_hours', models.CharField(max_length=1024, null=True, verbose_name='Opening Hours', blank=True)),\n ('coordinates', django.contrib.gis.db.models.fields.PointField(srid=4326, geography=True, null=True, verbose_name='Coordinates', blank=True)),\n ('open_now', models.BooleanField(default=False, verbose_name='Open Now')),\n ('types', models.CharField(max_length=1024, null=True, verbose_name='Place Types', blank=True)),\n ('icon', models.CharField(max_length=1024, null=True, verbose_name='Place Icon', blank=True)),\n ('phone_number', models.CharField(max_length=64, null=True, verbose_name='Phone Number', blank=True)),\n ('web_link', models.CharField(max_length=1024, null=True, verbose_name='Web Link', blank=True)),\n ('place_tags', models.TextField(verbose_name='Place Tags', blank=True)),\n ('date_added', models.DateTimeField(auto_now_add=True, verbose_name='Date Added')),\n ('last_modified', models.DateTimeField(auto_now=True, verbose_name='Last Modified')),\n ('category', models.ForeignKey(blank=True, to='search.PlaceCategory', null=True)),\n ],\n options={\n 'verbose_name': 'Place Search',\n 'verbose_name_plural': 'Places Search',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='ReportError',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('error', models.TextField(verbose_name='Report Error')),\n ('address', models.BooleanField(default=False, verbose_name='Place Address')),\n ('opening_hours', models.BooleanField(default=False, verbose_name='Place Opening Hours')),\n ('phone_number', models.BooleanField(default=False, verbose_name='Place Phone Number')),\n ('date_added', models.DateTimeField(auto_now_add=True, verbose_name='Date Added')),\n ('last_modified', models.DateTimeField(auto_now=True, verbose_name='Last Modified')),\n ('place', models.ForeignKey(related_name=b'place_ref_error', to='search.PlaceDetail')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","repo_name":"bharat-gera/Nautlus","sub_path":"search/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":4089,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"71144597688","text":"from board import buildGrid\nfrom board import toBoard\nfrom boardConfigurations import EASY_BOARD\nfrom boardConfigurations import MEDIUM_BOARD\nfrom boardConfigurations import HARD_BOARD\nfrom cleanUpPuzzle import CleanUpPuzzle\nfrom display import displayProblemSolution\nfrom search import astar_search\nfrom heuristics import nonAdmissibleHeuristic\nfrom heuristics import admissibleHeuristic\nfrom timer import Timer\n\nBOARD_SIZE = 11\nPRINT_SOLUTION = False\n\ndef run(puzzle = None, heuristicType = None, difficulty = None, h = None):\n watch = Timer()\n solution = astar_search(puzzle, h)\n watch.stop()\n if (PRINT_SOLUTION):\n displayProblemSolution(solution, 'astar_search (Heuristic type: ' + heuristicType + ', Difficulty ' + difficulty + ')', watch.getTotalTime())\n else: \n print('astar_search (Heuristic type: ' + heuristicType + ', Difficulty ' + difficulty + ') = ' + str(watch.getTotalTime()))\n return watch.getTotalTime()\n\ndef comparePerformance(nonAdmissible, admissible):\n indexes = ['EASY', 'MEDIUM', 'HARD']\n cols = ['Difficulty', 'Non Admissible Time (NA)', 'Admissible Time (A)', 'Time Diff (A - NA)', 'NA Time Saving %']\n headers = []\n rows = []\n STR_TEMPLATE = ' {:<25}'\n NUM_TEMPLATE = ' {:<25.10f}'\n PER_TEMPLATE = ' {:<25}'\n \n for col in cols:\n headers.append(STR_TEMPLATE.format(col))\n rows.append('|'.join(headers))\n \n for index in indexes:\n nonAdmissibleTime = nonAdmissible[index]\n admissibleTime = admissible[index]\n difference = admissible[index] - nonAdmissible[index]\n performance = (difference / nonAdmissibleTime) * 100\n label = ' slower'\n if performance > 0:\n label = ' faster'\n rows.append(\n '|'.join([\n STR_TEMPLATE.format(index),\n NUM_TEMPLATE.format(nonAdmissibleTime),\n NUM_TEMPLATE.format(admissibleTime),\n NUM_TEMPLATE.format(difference),\n PER_TEMPLATE.format('{:.5f}'.format(performance) + label)\n ])\n )\n print('\\n'.join(rows))\n\nGOAL_STATE = buildGrid(BOARD_SIZE)\nnonAdmissibleResultsByDifficulty = dict()\n# Non Admissible Heuristic\nnonAdmissibleResultsByDifficulty['EASY'] = run(CleanUpPuzzle(toBoard(EASY_BOARD), GOAL_STATE), 'Non admissible heuristic', 'EASY', nonAdmissibleHeuristic)\nnonAdmissibleResultsByDifficulty['MEDIUM'] = run(CleanUpPuzzle(toBoard(MEDIUM_BOARD), GOAL_STATE), 'Non admissible heuristic', 'MEDIUM', nonAdmissibleHeuristic)\nnonAdmissibleResultsByDifficulty['HARD'] = run(CleanUpPuzzle(toBoard(HARD_BOARD), GOAL_STATE), 'Non admissible heuristic','HARD', nonAdmissibleHeuristic)\n\nadmissibleResultsByDifficulty = dict()\n# Admissible Heuristic\nadmissibleResultsByDifficulty['EASY'] = run(CleanUpPuzzle(toBoard(EASY_BOARD), GOAL_STATE), 'Admissible', 'EASY', admissibleHeuristic)\nadmissibleResultsByDifficulty['MEDIUM'] = run(CleanUpPuzzle(toBoard(MEDIUM_BOARD), GOAL_STATE), 'Admissible', 'MEDIUM', admissibleHeuristic)\nadmissibleResultsByDifficulty['HARD'] = run(CleanUpPuzzle(toBoard(HARD_BOARD), GOAL_STATE), 'Admissible','HARD', admissibleHeuristic)\n\ncomparePerformance(nonAdmissibleResultsByDifficulty, admissibleResultsByDifficulty)","repo_name":"angelsalazar-zz/PSAWithHeuristic","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"11446148346","text":"#import os\n#os.environ[\"PROJ_LIB\"] = \"/anaconda3/envs/coawst/share/proj/\"\n#from mpl_toolkits.basemap import Basemap\nimport matplotlib.dates as mdates\nimport matplotlib.pyplot as plt\nfrom matplotlib.dates import DateFormatter\n#from mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\n#from matplotlib.ticker import LinearLocator, FormatStrFormatter\n#import warnings\nimport numpy as np\nimport datetime\nimport time\nimport netCDF4\nimport coawstpy\n#import pandas as pd\n\n# bring in the data\n#dir='/Users/mbiddle/Documents/Personal_Documents/Graduate_School/Thesis/COAWST/COAWST_RUNS/COAWST_OUTPUT/Full_20110702_20111101'\n#dir = '/Users/mbiddle/Documents/Personal_Documents/Graduate_School/Thesis/COAWST/COAWST_RUNS/COAWST_OUTPUT/Full_20110906_20110926'\ndir = '/Users/mbiddle/Documents/Personal_Documents/Graduate_School/Thesis/COAWST/COAWST_RUNS/COAWST_OUTPUT/Full_20110719T23_20111101'\n#dir = '/Volumes/Documents/COAWST_34_UPPER_CHES_FULL'\n#inputfile = dir+'/upper_ches_his.nc'\n#dir = '/Users/mbiddle/Documents/Personal_Documents/Graduate_School/Thesis/COAWST/COAWST_RUNS/COAWST_OUTPUT/Full_20110714201800_20111031231800'\ninputfile = dir+'/upper_ches_his.nc'\nf = netCDF4.Dataset(inputfile, 'r')\n\nCBIBS_file = '/Users/mbiddle/Documents/Personal_Documents/Graduate_School/Thesis/COAWST/Initialization_data/CBIBS_insitu_obs/NCEI_copy/S_2011.nc'\nfcbibs = netCDF4.Dataset(CBIBS_file, 'r')\n\nocean_time = f.variables['ocean_time'][:]\nlat = f.variables['lat_rho'][:][:]\nlon = f.variables['lon_rho'][:][:]\n\n## Do some date conversions ##\n#epoch_date = '%s %s'%(f.variables['ocean_time'].units.split(' ')[-2], f.variables['ocean_time'].units.split(' ')[-1])\n#dt_obj = datetime.datetime.strptime(epoch_date, '%Y-%m-%d %H:%M:%S')\n#time_diff = time.mktime(dt_obj.timetuple())-time.mktime(datetime.datetime(1970, 1, 1, 0, 0, 0).timetuple())\ndatetime_list=[]\nfor sec in ocean_time:\n datetime_list.append(\n netCDF4.num2date(sec, units=f.variables['ocean_time'].units, calendar=f.variables['ocean_time'].calendar))\n #ts = sec/(12*3600)\n #datetime_list.append(datetime.datetime.fromtimestamp(sec+time_diff))\n\n\n\ncbibs_turb = fcbibs.variables['turbidity'][:]\ncbibs_turb = np.ma.masked_equal(cbibs_turb, cbibs_turb.min())\ncbibs_time = fcbibs.variables['time2'][:]\n#Geolocation is 39.5404, -76.0736\ncbibs_lon = -76.0736\ncbibs_lat = 39.5404\n#cbibs_lat = fcbibs.variables['latitude'][:]\n#cbibs_lon = fcbibs.variables['longitude'][:]\n\ncbibs_date=[]\nfor i in range(len(cbibs_time)):\n cbibs_date.append(datetime.datetime.fromordinal(int(cbibs_time[i])) + datetime.timedelta(days=cbibs_time[i]%1) - datetime.timedelta(days = 366))\n\n# epoch_date = '%s %s'%(fcbibs.variables['time2'].units.split(' ')[-3], fcbibs.variables['time2'].units.split(' ')[-2])\n# dt_obj = datetime.datetime.strptime(epoch_date, '%Y-%m-%d %H:%M:%S')\n# time_diff = time.mktime(dt_obj.timetuple())-time.mktime(datetime.datetime(1970, 1, 1, 0, 0, 0).timetuple())\n# cbibs_date=[]\n# for sec in cbibs_time:\n# ts = sec/(12*3600)\n# cbibs_date.append(datetime.datetime.fromtimestamp(sec+time_diff))\n\nlat_pt = cbibs_lat\nlon_pt = cbibs_lon\n\ntry:\n lat_pt\n lon_pt\nexcept NameError:\n print(\"Using indexes x, y = (%i, %i)\" % (x, y))\nelse:\n print(\"Using geo-coords lat, lon = (%f, %f)\" % (lat_pt, lon_pt))\n x = np.abs(f.variables['lon_rho'][:, 1]-lon_pt).argmin()\n y = np.abs(f.variables['lat_rho'][1, :]-lat_pt).argmin()\n\n\n#plant_height = f.variables['plant_height'][0, 0, :, :]\n#plant_height = np.ma.masked_greater(plant_height, 1)\n#plant_height[x, y] = 1\n#plt.figure(1)\n#plt.pcolor(f.variables['lon_rho'][:][:], f.variables['lat_rho'][:][:], plant_height)\n\n\nmud_tot = f.variables['mud_01'][:, :, x, y]\n#mud = mud_tot\nmud = np.mean(mud_tot, axis=1) # integrate w/ depth\nsand_tot = f.variables['sand_01'][:, :, x, y]\n#sand = sand_tot\nsand = np.mean(sand_tot, axis=1) # integrate w/ depth\n\nSSC = mud + sand\nfig, (ax) = plt.subplots(nrows=1, ncols=1, sharex=True, figsize=(12, 8))\nax.plot_date(datetime_list,SSC,label='COAWST SSC',\n xdate=True, linestyle='-', linewidth=1,\n marker='', markersize=1, color='r')\n#ax.spines['left'].set_color('red')\nax.tick_params(axis='y', colors='red')\nax.set_ylabel('COAWST SSC [kg/m3]')\nax.yaxis.label.set_color('red')\nxlim = ax.get_xlim()\n#ax.grid(True)\nax2v = ax.twinx()\nax2v.plot_date(cbibs_date,cbibs_turb, label='CBIBS',\n xdate=True, linestyle='-', linewidth=1,\n marker='', markersize=1, color='b')\nax2v.set_ylabel('CBIBS Turbidity [NTU]')\nax2v.tick_params(axis='y', colors='blue')\nax2v.yaxis.label.set_color('blue')\n#ax2v.grid(True)\nax2v.set_xlim(xlim)\nax.xaxis.set_major_locator(mdates.DayLocator(interval=10))\nax.xaxis.set_major_formatter(DateFormatter(\"%m/%d\"))\n#fig.legend(loc='upper left')\n\n","repo_name":"MathewBiddle/coawst-py","sub_path":"comparisons/cbibs_turbidity.py","file_name":"cbibs_turbidity.py","file_ext":"py","file_size_in_byte":4767,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"143284937","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn import metrics\n\n# lets get the data ready for cooking.\nmsg = pd.read_csv('dataset6.csv', names=['message', 'label'])\nmsg['labelnum'] = msg.label.map({'pos': 1, 'neg': 0})\n\nX = msg.message\ny = msg.labelnum\n\nprint('the message and label are: ')\nfor a, b in zip(X, y):\n print(a, ',', b)\n\nX_train, X_test, y_train, y_test = train_test_split(X, y)\n\ncount_vector = CountVectorizer()\nxtrain_dtm = count_vector.fit_transform(X_train)\n\nprint('the total features extracted using countVectorizer ', xtrain_dtm.shape[1])\ndf = pd.DataFrame(np.array(xtrain_dtm.toarray()), columns=count_vector.get_feature_names())\n# features are the words whose frequencies add weightage to the document you are referring to. h\nprint('features are :\\n', df)\n\n# the actual cooking happens happens here.\nclassifier = MultinomialNB()\nclassifier.fit(xtrain_dtm, y_train) # this is where we train the data.\n\nxtest_dtm = count_vector.transform(X_test) # the data has been fit already during the training so we only transform.\npredicted = classifier.predict(xtest_dtm) # this is where we test our data against the trained model.\n\nprint('classification result of the testing samples are : ')\nfor doc, p in zip(X_test, predicted):\n pred = 'pos' if p == 1 else 'neg'\n print('%s -> %s ' % (doc, pred))\n\nprint('\\nAccuracy metrics')\nprint('Accuracy of the classifer is', metrics.accuracy_score(y_test, predicted))\nprint('Recall :', metrics.recall_score(y_test, predicted), metrics.precision_score(y_test, predicted))\nprint('Confusion matrix')\nprint(metrics.confusion_matrix(y_test, predicted))\n","repo_name":"Sudarshan-r-bhat/Python-ML-Workspace","sub_path":"Machine Learning Workspace/lab_programs/Bayesian_classifier_algorithm2.py","file_name":"Bayesian_classifier_algorithm2.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"15032615166","text":"from geolite2 import geolite2\nimport xml.etree.ElementTree as ETREE\nimport sys\n\ntree = ETREE.parse(sys.argv[1])\ntop=tree.getroot() #getting the top of the tree\n\nipadress=[]\nfor child in top:\n for nextchild in child:\n q=0\n for nnextchild in nextchild:\n rr=str(nnextchild.get('showname'))\n if rr[:-4] == \"Via: Internet.org\": #we will enter the next loop only if there is a showname in this proto with showname \"Via: Internet.orgr\\r\\n\"\n q = 1 #q=1 indicates there exists a field with the particular showname \"Via: Internet.org\\r\\n\"\n if q == 1:\n for nnextchild in nextchild:\n if nnextchild.get('name') == \"http.x_forwarded_for\": #for all names which are \"http.x_forwarded_for\" we are collecting their ip adresses\n ipadress.append(nnextchild.get('show'))\n\n\nunique_ips=set(ipadress) # selecting only non repeated ip adresses\ncountry_name=[] #list to store country names linked to the ip adresses\n\nfor ip in unique_ips:\n var = geolite2.reader()\n country =var.get(ip)['country']['names']['en'] #using geolite2 library to get country name from ip adress\n country_name.append(country)\n\ncountries = set(country_name) #selecting country names by not including repeated names\nrows=[]\nfor country in countries:\n x=country_name.count(country)\n rows.append([country,x]) # creating rows which contain country name and their frequency\n\nimport csv\n\nfilename = \"data.csv\"\nwith open(filename, 'w',newline=\"\") as csvfile:\n csvwriter = csv.writer(csvfile)\n csvwriter.writerows(rows) #writing all the rows into the csv file\n\n\n\n\n\n","repo_name":"pruthvi0105/Computer-networks-lab","sub_path":"Asgn 2/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"26571001591","text":"import os\nfrom dotenv import load_dotenv\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import scoped_session, sessionmaker\n\nload_dotenv(verbose=True)\nDB_URI = os.environ.get(\"DATABASE_URL\", None)\n\ndef start() -> scoped_session:\n db_url = DB_URI.replace(\"postgres://\", \"postgresql://\") if \"postgres://\" in DB_URI else DB_URI\n engine = create_engine(db_url)\n BASE.metadata.bind = engine\n BASE.metadata.create_all(engine)\n return scoped_session(sessionmaker(bind=engine, autoflush=False))\n\ntry:\n BASE = declarative_base()\n SESSION = start()\nexcept Exception as e:\n print(\"DB_URI is not configured!\", str(e))\n exit(1)\n","repo_name":"harshjais369/MatrimonyAPI","sub_path":"app/configs/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"73782632568","text":"import sequence\nimport os\nimport argparse\nimport csv\n\ndef main():\n\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"-i\", \"--input\", help=\"FASTA file to query from\", required=True)\n\tparser.add_argument(\"-q\", \"--query\", help=\"Query FASTA file\", required=True)\n\tparser.add_argument(\"-db\", \"--database\", help=\"Database output file name\", required=True)\n\tparser.add_argument(\"-r\", \"--reference\", help=\"Reference database \", default=\"uniprotkb\")\n\tparser.add_argument(\"-o\", \"--output\", help=\"Output path\", default=\"matchmyseqs\")\n\n\targs = parser.parse_args()\n\n\tseqDict = {}\n\ttier1seq = ''\n\trepresentative = ''\n\tfasta = {}\n\tseqsforCSV = {}\n\tprogress = 0\n\ttier1 = {}\n\ttier1_annots = {} # annotations that we want to include in the final dataset\n\n\tos.system('makeblastdb -dbtype prot -in ' + args.input + ' -out ' + args.database)\n\n\tdb = sequence.readFastaFile(args.input, sequence.Protein_Alphabet, ignore=True, parse_defline=False)\n\tdb_map = {} # map from \"long\" name to actual entry\n\tdb_map_short = {} # map from \"short\" name to entry\n\tfor s in db:\n\t db_map[s.name] = s\n\t db_map_short[sequence.parseDefline(s.name)[0]] = s\n\tprint(\"Database size is \" + str(len(db_map)))\n\n\tprint(\"Blast started, this might take a bit depending on your dataset size\")\n\tos.system(\"blastp -db \" + args.database + \" -outfmt 3 -num_descriptions 1 -num_alignments 0 -query \" + args.query + \" -out query.txt\")\n\t\n\n\tif args.reference == 'uniprotkb':\n\t\tos.system(\"grep -e \\\"^[st][pr]|\\\" query.txt | cut -d\\' \\' -f1 > UniProt_query.tab\")\n\n\t\t# Extract the resulting sequence identifiers\n\t\trepSeqNames = set([])\n\t\tf = open('UniProt_query.tab', 'rt')\n\t\tfor row in f:\n\t\t repSeqNames.add(sequence.parseDefline(row.strip())[0])\n\t\tf.close()\n\t\tprint(str(len(repSeqNames)), \" representative sequences have been found\")\n\n\t\t#Annot the representative sequences \n\t\tnotfound = []\n\t\tfor name in repSeqNames:\n\t\t\tif name in db_map_short:\n\t\t\t\ts = db_map_short[name]\n\t\t\t\tseqsforCSV[s.name] = \"\".join(s)\n\t\t\telse:\n\t\t\t\tnotfound.append(name)\n\t\tprint('Matched', len(repSeqNames)-len(notfound), 'of', len(repSeqNames))\n\n\t\twith open(\"query.txt\", newline='') as f:\n\t\t\treader = csv.reader(f)\n\t\t\tfor row in reader:\n\t\t\t\tif len(row) > 0 and row[0].startswith('Query'):\n\t\t\t\t\tquerySeq = (str(row).split(\"=\")[1][:-2].strip())\n\t\t\t\telif len(row) > 0 and (row[0].startswith('tr|') or row[0].startswith('sp|')):\n\t\t\t\t\trepresentative = (str(row).split(\" \")[0][2:].strip())\n\t\t\t\t\tseqDict[querySeq] = representative\n\n\telif args.reference == 'refseq':\n\t\tgrab = False\n\t\trepSeqNames = set([])\n\n\t\twith open(\"query.txt\", newline='') as f:\n\t\t\treader = csv.reader(f)\n\t\t\tfor row in reader:\n\t\t\t\tif len(row) > 0 and row[0].startswith('Query'):\n\t\t\t\t\tquerySeq = (str(row[0]).split(\"=\")[1][:-2].strip().split(\" \")[0])\n\t\t\t\telif len(row) > 0 and row[0].startswith('Sequences'):\n\t\t\t\t\tgrab = True\n\t\t\t\t\tcontinue\n\t\t\t\telif grab == True:\n\t\t\t\t\tif len(row) > 0 and not row[0].strip() == \"\":\n\t\t\t\t\t\trepresentative = (row[0].split('.')[0]+\".\"+row[0].split('.')[1].split(\" \")[0])\n\t\t\t\t\t\trepSeqNames.add(representative)\n\t\t\t\t\t\tseqDict[querySeq] = representative\n\t\t\t\t\t\tgrab = False\n\t\t\t#print(len(repSeqNames))\n\n\t\t\tnotfound = []\n\n\t\t\tfor name in repSeqNames:\n\t\t\t\tif name in db_map_short:\n\t\t\t\t\ts = db_map_short[name]\n\t\t\t\t\tseqsforCSV[s.name] = \"\".join(s)\n\t\t\t\telse:\n\t\t\t\t\tnotfound.append(name)\n\t\t\tprint('Matched', len(repSeqNames)-len(notfound), 'of', len(repSeqNames))\n\t\t\t \n\t\t\tprint(len(repSeqNames) , \" representative sequences found for \" + args.query)\n\n\n\n\n\n\n\t# done25 = False\n\t# done50 = False\n\t# done75 = False\n\t# for s,rep in seqDict.items():\n\t# \ttotal = (len(seqDict))\n\t# \tseq = (sequence.getSequence(rep,'uniprotkb'))\n\t# \tseqsforCSV[rep] = str(seq).split(\":\")[1].strip()\n\t# \telem = rep + str(seq)\n\t# \tprogress+=1\n\t# \tif (progress/total)*100 > 25 and not done25:\n\t# \t\tprint(\"25% done\")\n\t# \t\tdone25 = True\n\t# \telif (progress/total)*100 > 50 and not done50:\n\t# \t\tprint(\"50% done\")\n\t# \t\tdone50 = True\n\t# \telif (progress/total)*100 > 75 and not done75:\n\t# \t\tprint(\"75% done\")\n\t# \t\tdone75 = True\n\n\tfaOut = args.output + '.fa'\n\n\tseq_list = [sequence.Sequence(sequence=seq, name=seqname) for seqname, seq in seqsforCSV.items()]\n\n\tsequence.writeFastaFile(faOut, seq_list)\n\t\n\tcsvOut = args.output + '.csv'\n\n\twith open(csvOut, 'w', newline='') as f:\n\t fieldnames = ['Name', 'Representative', 'Sequence']\n\t thewriter = csv.DictWriter(f, fieldnames=fieldnames)\n\t \n\t thewriter.writeheader()\n\t for given,rep in seqDict.items():\n\t \tthewriter.writerow({'Name' : given, 'Representative' : rep, 'Sequence' : seqsforCSV[rep]})\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"asli-yoruk/toolkit","sub_path":"MATCH-MY-SEQS.py","file_name":"MATCH-MY-SEQS.py","file_ext":"py","file_size_in_byte":4577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"22576956888","text":"\nfrom gensim.test.utils import get_tmpfile\nfrom gensim.models import Word2Vec\nfrom gensim.models.doc2vec import Doc2Vec, TaggedDocument\nfrom gensim.utils import simple_preprocess\nimport json\nimport re\n\n\ndef input(filenames):\n data = []\n for filename in filenames:\n with open('./DataCollection/NodeScraper/'+filename, encoding='utf-8', mode='r') as f:\n for line in f:\n line = line.strip(',\\n')\n data.append(json.loads(line))\n return data\n\ndef clean(string):\n s = re.sub(r'\\[removed\\]|\\[deleted\\]|ELI5|\\(http[s]?://.+\\)','',string)\n return s\n\ndef preprocess(data):\n text = []\n for doc in data:\n string = \" \".join(doc.values())\n string = clean(string)\n string = simple_preprocess(string)\n text.append(string)\n return text\n\ndef doc_preprocess(data):\n text = []\n for i in range(len(data)):\n string = data[i]['answer']['text']\n string = clean(string)\n word_list = simple_preprocess(string)\n text.append(TaggedDocument(word_list, [i]))\n return text\n\nif __name__ == '__main__':\n\n # load the trained model\n model = Word2Vec.load(\"./src/word2vec.model\")\n vector = model.wv['blue']\n model.most_similar(['blue'])\n\n doc_model = Doc2Vec.load(\"./src/doc2vec.model\")\n # doc_model.n_similarity(Q_seqlist, A_seqlist)\n\n ### training process\n '''\n # data input\n filenames = ['QA.json','QA4.json','QA5.json','QA6.json','QA7.json']\n data = input(filenames)\n text = preprocess(data)\n\n # train with json files\n path = get_tmpfile(\"./src/word2vec.model\")\n model = Word2Vec(text, size=100, window=5, min_count=1, workers=4)\n model.save(\"word2vec.model\")\n \n #\n vector = model.wv['blue']\n model.most_similar(['blue'])\n\n # doc2vec\n filenames = ['QA8.json']\n docs = input(filenames)\n answers = doc_preprocess(docs)\n\n doc_model = Doc2Vec(answers, vector_size=5, window=5, min_count=1, workers=4)\n doc_model.save(\"doc2vec.model\")\n '''\n\n","repo_name":"erl-j/SearchEnginesGroup7","sub_path":"src/word2vec.py","file_name":"word2vec.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"70255569530","text":"import streamlit as st\nimport streamlit_utils as stu\nimport pandas as pd\n\ndef set_recipe(i, url):\n state.recipes[i] = url\n \ndef timefmt(minutes):\n hours = minutes//60\n if hours:\n minutes = minutes%60\n if minutes:\n return f\"{hours} {'timer' if hours>1 else 'time'} {minutes}min\"\n else:\n return f\"{hours} {'timer' if hours>1 else 'time'}\"\n else:\n return f\"{minutes}min\"\n\n\ndef build_menu_ui(state):\n st.header(\"Menu:\")\n state.servings = st.number_input(\"Kuverter:\", min_value=1.0, value=2.5, step=0.5)\n recipe_divs = []\n urls = []\n for i, recipe in enumerate(state.recipes):\n recipe_divs.append(st.container())\n columns = st.columns([10,1,1])\n url = columns[0].text_input(f\"recipe url\", value=recipe, placeholder=\"https://www.valdemarsro.dk/...\", key=f\"url_field_{i}\", label_visibility=\"collapsed\")\n columns[1].button(\"↻\", use_container_width=True, key=f\"rerun_{i}\", on_click=lambda i=i: set_recipe(i, stu.suggest_recipe()))\n columns[2].button(\"❌\", use_container_width=True, key=f\"delete_{i}\", on_click=lambda i=i: state.recipes.pop(i))\n urls.append(url)\n state.recipes = urls\n st.button(\"Tilføj måltid\", on_click=lambda: state.recipes.append(stu.suggest_recipe()))\n return recipe_divs\n\nstate = stu.state()\nrecipe_divs = build_menu_ui(state)\n\n\n# Build content\nbasket = {}\nfor div, recipe_url in zip(recipe_divs, state.recipes):\n if recipe_url:\n recipe = stu.get_recipe(recipe_url)\n ingredient_count = len(recipe.ingredients())\n with div:\n columns = st.columns([10,2])\n columns[0].markdown(f\"#### [{recipe.title()}]({recipe_url}) [{timefmt(recipe.total_time())}] {'' if ingredient_count else '!Ingredients missing!'}\")\n columns[1].markdown(f' ', unsafe_allow_html=True)\n for ingredient in stu.collect_ingredients(recipe_url, servings=state.servings):\n basket.setdefault(ingredient[\"item\"], []).append(ingredient[\"amount\"])\n\nif basket:\n combined_basket = {}\n for item, amounts in basket.items():\n s_amounts = sorted(amounts, key=lambda x: str(x.to_base_units().u))\n c_amounts = [s_amounts[0]]\n for amount in s_amounts[1:]:\n try:\n c_amounts[-1] = c_amounts[-1] + amount\n except TypeError:\n c_amounts.append(amount)\n combined_basket[item] = c_amounts\n\n combined_basket = pd.DataFrame(combined_basket.items(), columns=[\"item\", \"amounts\"])\n combined_basket[\"amounts\"] = combined_basket[\"amounts\"].apply(\n lambda a: \" + \".join(map(lambda x: f\"{round(x,2):~P}\", a))\n )\n combined_basket[\"købt\"] = combined_basket.item.str.match(\".*(oregano|paprika|olivenolie|timian).*\") | combined_basket.item.isin({\"vand\", \"salt og peber\", \"salt\", \"peber\"})\n combined_basket.sort_values([\"købt\", \"item\"], inplace=True)\n combined_basket.set_index(\"amounts\", drop=True, inplace=True)\n\n st.header(\"Inkøbsliste:\")\n n_rows = len(combined_basket)\n edit_combined_basket = st.experimental_data_editor(combined_basket, use_container_width=True, num_rows=\"dynamic\", height=int(35*(n_rows+8)))\n\n#st.write(str(ingredients))\n#st.dataframe(edit_combined_basket, use_container_width=True)\n\n","repo_name":"Happyzippy/minmadplan","sub_path":"streamlit_app.py","file_name":"streamlit_app.py","file_ext":"py","file_size_in_byte":3359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"48337889723","text":"import collections\nimport copy\nimport dataclasses\nimport logging\nimport math\nimport time\nfrom typing import ClassVar, Dict, List, Optional, Set, Tuple\n\nimport numpy as np\nimport torch\nfrom conf import agents_cfgs\nfrom fairdiplomacy import pydipcc\n\nfrom fairdiplomacy.agents.base_agent import AgentState\nfrom fairdiplomacy.agents.base_search_agent import (\n SearchResult,\n make_set_orders_dicts,\n sample_orders_from_policy,\n)\nfrom fairdiplomacy.agents.bilateral_stats import BilateralStats\nfrom fairdiplomacy.agents.searchbot_agent import SearchBotAgent, SearchBotAgentState, CFRData\nfrom fairdiplomacy.agents.base_strategy_model_rollouts import RolloutResultsCache\nfrom fairdiplomacy.agents.br_corr_bilateral_search import (\n extract_bp_policy_for_powers,\n compute_weights_for_opponent_joint_actions,\n compute_best_action_against_reweighted_opponent_joint_actions,\n sample_joint_actions,\n filter_invalid_actions_from_policy,\n rescore_bp_from_bilateral_views,\n compute_payoff_matrix_for_all_opponents,\n BRCorrBilateralSearchResult,\n)\nfrom fairdiplomacy.agents.base_strategy_model_wrapper import BaseStrategyModelWrapper\nfrom fairdiplomacy.agents.plausible_order_sampling import PlausibleOrderSampler\nfrom fairdiplomacy.models.consts import POWERS\nfrom fairdiplomacy.typedefs import (\n Action,\n BilateralConditionalValueTable,\n JointAction,\n Phase,\n PlausibleOrders,\n PlayerType,\n PlayerTypePolicies,\n Policy,\n Power,\n PowerPolicies,\n RolloutResults,\n)\nfrom fairdiplomacy.utils.timing_ctx import TimingCtx\nfrom fairdiplomacy.utils.sampling import sample_p_dict\nfrom fairdiplomacy.utils.agent_interruption import raise_if_should_stop\n\n\nRescoringPolicyName = str\n\n\nclass BRMResult(SearchResult):\n def __init__(\n self,\n bp_policies: PowerPolicies,\n ptype_avg_policies: PlayerTypePolicies,\n ptype_final_policies: PlayerTypePolicies,\n beliefs: Dict[Power, np.ndarray],\n agent_type: PlayerType,\n use_final_iter: bool,\n brm_data: Optional[\"BRMData\"],\n bilateral_stats: Optional[BilateralStats] = None,\n ):\n self.bp_policies = bp_policies\n self.ptype_avg_policies = ptype_avg_policies\n self.ptype_final_policies = ptype_final_policies\n self.brm_data = brm_data # type: ignore\n # make sure we don't hold on to mutable belief arrays\n self.beliefs = copy.deepcopy(beliefs)\n self.agent_type = agent_type\n self.use_final_iter = use_final_iter\n self.bilateral_stats = bilateral_stats\n\n def get_bp_policy(self) -> PowerPolicies:\n return self.bp_policies\n\n def get_agent_policy(self) -> PowerPolicies:\n return self.ptype_avg_policies[self.agent_type]\n\n def get_population_policy(self, power: Optional[Power] = None) -> PowerPolicies:\n return belief_weighted_policy(self.beliefs, self.ptype_avg_policies, power)\n\n def sample_action(self, power) -> Action:\n ptype_policies = (\n self.ptype_final_policies if self.use_final_iter else self.ptype_avg_policies\n )\n return sample_p_dict(ptype_policies[self.agent_type][power])\n\n def avg_utility(self, pwr: Power) -> float:\n assert self.brm_data is not None\n return sum(\n cfr_data.avg_utility(pwr) * self.beliefs[pwr][ptype]\n for ptype, cfr_data in self.brm_data.type_cfr_data.items()\n )\n\n def avg_action_utility(self, pwr: Power, a: Action) -> float:\n assert self.brm_data is not None\n return sum(\n cfr_data.avg_action_utility(pwr, a) * self.beliefs[pwr][ptype]\n for ptype, cfr_data in self.brm_data.type_cfr_data.items()\n )\n\n def is_early_exit(self) -> bool:\n return self.brm_data is None\n\n def get_bilateral_stats(self) -> BilateralStats:\n assert self.bilateral_stats is not None\n return self.bilateral_stats\n\n\nclass BRMData:\n def __init__(self, type_cfr_data: Dict[PlayerType, CFRData]):\n self.type_cfr_data: Dict[PlayerType, CFRData] = type_cfr_data\n\n def get_best_type_data(self):\n return self.type_cfr_data[0]\n\n def get_type_data(self, ptype: PlayerType):\n return self.type_cfr_data[ptype]\n\n\nclass BeliefState:\n def __init__(self, player_types: List[PlayerType]):\n self.player_types = player_types\n self.updated_phases: Set[str]\n self.beliefs: Dict[Power, np.ndarray]\n self.reset()\n\n @property\n def num_player_types(self):\n return len(self.player_types)\n\n def __str__(self):\n return \"\\n\".join(\n [\n f\"{pwr}: {np.array2string(belief, precision=2, suppress_small=True)}\\n\" # type: ignore\n for pwr, belief in self.beliefs.items()\n ]\n )\n\n def reset(self):\n self.updated_phases = set()\n self.beliefs = {\n pwr: np.ones(self.num_player_types) / self.num_player_types for pwr in POWERS\n }\n\n\ndef belief_weighted_policy(\n beliefs: Dict[Power, np.ndarray],\n ptype_policies: Dict[PlayerType, PowerPolicies],\n power: Optional[Power],\n) -> PowerPolicies:\n ret = {}\n for pwr in beliefs:\n if power is not None and pwr != power:\n continue\n ret[pwr] = {}\n for ptype, ptype_prob in enumerate(beliefs[pwr].tolist()):\n ptype_policy = ptype_policies[ptype][pwr]\n for action, action_prob in ptype_policy.items():\n if action not in ret[pwr]:\n ret[pwr][action] = 0\n ret[pwr][action] += ptype_prob * action_prob\n\n ret_sorted = {\n pwr: dict(sorted(pi.items(), key=lambda ac_p: -ac_p[1])) for pwr, pi in ret.items()\n }\n return ret_sorted\n\n\nclass BayesAgentState(SearchBotAgentState):\n def __init__(self, power: Power, player_types: List[PlayerType]):\n super().__init__(power)\n self.belief_state = BeliefState(player_types)\n self.dynamic_lambda_scale_cache: Dict[Phase, Dict[Power, float]] = {}\n\n\n@dataclasses.dataclass\nclass PlayerTypeSpec:\n # To be used to identify blueprint policy.\n BLUEPRINT_POLICY_NAME: ClassVar[RescoringPolicyName] = \"BP\"\n\n qre_lambda: float\n # Model path or BLUEPRINT_POLICY_NAME. Used to debug print and such.\n policy_name: RescoringPolicyName\n # Optional for BLUEPRINT_POLICY_NAME. Required otherwise.\n rescore_policy_path: Optional[str]\n\n # Arbitrary extra string to identify this type. The collection of all type should have unique names.\n extra_tag: str = \"\"\n\n @property\n def name(self) -> str:\n name = \"{:}*{:.2e}\".format(self.policy_name, self.qre_lambda)\n if self.extra_tag:\n name = f\"{name}_{self.extra_tag}\"\n return name\n\n def assert_valid(self) -> None:\n try:\n assert 0 <= self.qre_lambda\n assert (self.policy_name == self.BLUEPRINT_POLICY_NAME) == (\n self.rescore_policy_path is None\n )\n except AssertionError:\n logging.error(\"Invalid spec: %s\", self)\n raise\n\n\ndef _make_bqre_data(\n policies: Dict[RescoringPolicyName, PowerPolicies],\n specs: Dict[PlayerType, PlayerTypeSpec],\n qre: agents_cfgs.SearchBotAgent.QRE,\n scale_lambdas: float,\n pow_lambdas: float,\n scale_lambdas_by_power: Dict[Power, float],\n agent_power: Optional[Power],\n) -> BRMData:\n logging.info(f\"Making BQRE data with scale_lambdas {scale_lambdas} pow_lambdas {pow_lambdas}\")\n return BRMData(\n {\n player_type: CFRData(\n bp_policy=policies[spec.policy_name],\n use_optimistic_cfr=False,\n qre=agents_cfgs.SearchBotAgent.QRE(\n **{\n **qre.to_dict(),\n \"qre_lambda\": math.pow(spec.qre_lambda, pow_lambdas) * scale_lambdas,\n }\n ),\n agent_power=agent_power,\n scale_lambdas_by_power=scale_lambdas_by_power,\n )\n for player_type, spec in specs.items()\n }\n )\n\n\ndef _migrate_old_lambdas(cfg: agents_cfgs.BQRE1PAgent) -> agents_cfgs.BQRE1PAgent:\n # Next 2 lines -> deep copy.\n cfg_proto = type(cfg.to_editable())()\n cfg_proto.CopyFrom(cfg.to_editable())\n\n if cfg.player_types.which_player_types is not None:\n assert (\n cfg.lambda_min is None and cfg.lambda_multiplier is None\n ), \"Do not specify lambda_min and lambda_multiplier when using player_types\"\n else:\n assert cfg.lambda_min is not None and cfg.lambda_multiplier is not None\n assert cfg.lambda_min > 0.0, \"qre_lambda needs to be > 0\"\n assert (\n cfg.lambda_multiplier > 0.0 and cfg.lambda_multiplier != 1.0\n ), \"lambda_multiplier needs to be > 0 and not equal to 1\"\n\n cfg_proto.player_types.log_uniform.min_lambda = cfg.lambda_min * cfg.lambda_multiplier\n assert cfg.num_player_types is not None\n cfg_proto.player_types.log_uniform.max_lambda = cfg.lambda_min * (\n cfg.lambda_multiplier ** cfg.num_player_types\n )\n\n cfg_proto.ClearField(\"lambda_min\")\n cfg_proto.ClearField(\"lambda_multiplier\")\n\n logging.info(\"Migrated lambda-player-type configuration:\\n%s\", cfg_proto)\n\n return cfg_proto.to_frozen()\n\n\ndef _compute_player_specs(\n cfg: agents_cfgs.BQRE1PAgent.PlayerTypes, num_player_types: int\n) -> List[PlayerTypeSpec]:\n assert num_player_types >= 1\n if cfg.log_uniform is not None:\n subcfg = cfg.log_uniform\n assert subcfg.min_lambda is not None\n assert subcfg.max_lambda is not None\n\n num_policies = max(1, len(subcfg.policies))\n\n assert (num_player_types - int(subcfg.include_zero_lambda)) % num_policies == 0, (\n \"num_player_types should account for the zero type and all policies\",\n )\n\n num_lambdas = (num_player_types - int(subcfg.include_zero_lambda)) // num_policies\n if num_lambdas == 0:\n lambdas = []\n elif num_lambdas == 1:\n assert subcfg.max_lambda == subcfg.min_lambda\n lambdas = [subcfg.min_lambda]\n else:\n multiplier = (subcfg.max_lambda / subcfg.min_lambda) ** (1.0 / (num_lambdas - 1))\n # This slightly weird way of computing the lambda is to maintain exact consistency\n # with earlier behavior\n lambdas = [\n float(np.float32(subcfg.min_lambda / multiplier)) * (multiplier ** x)\n for x in range(1, num_lambdas + 1)\n ]\n specs = []\n if subcfg.include_zero_lambda:\n # We don't care wichh policy to user for lambda=0, as we will ignore\n # it anyways. So we just use the BP.\n specs.append(\n PlayerTypeSpec(\n qre_lambda=0.0,\n policy_name=PlayerTypeSpec.BLUEPRINT_POLICY_NAME,\n rescore_policy_path=None,\n )\n )\n if not subcfg.policies:\n # Using \"blueprint\" policy.\n specs.extend(\n PlayerTypeSpec(\n qre_lambda=qre_lambda,\n policy_name=PlayerTypeSpec.BLUEPRINT_POLICY_NAME,\n rescore_policy_path=None,\n )\n for qre_lambda in lambdas\n )\n else:\n for policy in subcfg.policies:\n if policy.model_path is None:\n assert policy.name is None\n specs.extend(\n PlayerTypeSpec(\n qre_lambda=qre_lambda,\n policy_name=PlayerTypeSpec.BLUEPRINT_POLICY_NAME,\n rescore_policy_path=None,\n )\n for qre_lambda in lambdas\n )\n else:\n assert policy.name is not None\n specs.extend(\n PlayerTypeSpec(\n qre_lambda=qre_lambda,\n policy_name=policy.name,\n rescore_policy_path=policy.model_path,\n )\n for qre_lambda in lambdas\n )\n else:\n raise RuntimeError(\"Unknown player types\")\n assert specs, \"No player types!\"\n # Names must be unique.\n [[most_common_name, freq]] = collections.Counter(x.name for x in specs).most_common(1)\n assert freq == 1, f\"Name duplication for player type: {most_common_name}\"\n return specs\n\n\nclass BQRE1PAgent(SearchBotAgent):\n \"\"\"One-ply bayes qre rm with base_strategy_model-policy rollouts\"\"\"\n\n def __init__(self, cfg: agents_cfgs.BQRE1PAgent, *, skip_base_strategy_model_cache=False):\n ################# refactored from base class ###########################\n super().__init__(\n cfg.base_searchbot_cfg, skip_base_strategy_model_cache=skip_base_strategy_model_cache\n )\n assert cfg.num_player_types is not None\n self.num_player_types = cfg.num_player_types\n assert cfg.agent_type is not None\n # The rest of the code uses 0-based indexing of the types. This should\n # be the only place we convert 1-based to 0-based.\n self.agent_type = cfg.agent_type - 1\n self.player_types = list(range(self.num_player_types))\n self.agent_type_is_public = cfg.agent_type_is_public\n\n assert self.exploited_agent_power is None, \"exploited agent power is not supported\"\n ##########################################################################\n\n self.qre_type2spec: Dict[PlayerType, PlayerTypeSpec] = {}\n self.qre_extra_rescoring_models: Dict[RescoringPolicyName, PlausibleOrderSampler] = {}\n self.pow_lambdas_1901 = cfg.pow_lambdas_1901\n self.scale_lambdas_1901 = cfg.scale_lambdas_1901\n self.pow_lambdas_1901_spring = cfg.pow_lambdas_1901_spring\n self.scale_lambdas_1901_spring = cfg.scale_lambdas_1901_spring\n\n self.dynamic_lambda_stdev_espilon = cfg.dynamic_lambda_stdev_espilon\n self.dynamic_lambda_stdev_baseline = cfg.dynamic_lambda_stdev_baseline\n self.dynamic_lambda_stdev_num_samples = cfg.dynamic_lambda_stdev_num_samples\n if self.dynamic_lambda_stdev_num_samples > 0:\n assert (\n self.dynamic_lambda_stdev_espilon is not None\n and self.dynamic_lambda_stdev_espilon > 0\n ), \"Must specify self.dynamic_lambda_stdev_epsilon if using dynamic lambda\"\n assert (\n self.dynamic_lambda_stdev_baseline is not None\n and self.dynamic_lambda_stdev_baseline > 0\n ), \"Must specify self.dynamic_lambda_stdev_baseline if using dynamic lambda\"\n\n cfg = _migrate_old_lambdas(cfg)\n self.set_player_type_spec(_compute_player_specs(cfg.player_types, len(self.player_types)))\n if cfg.base_searchbot_cfg.qre.target_pi != \"BLUEPRINT\":\n assert cfg.base_searchbot_cfg.qre.target_pi == \"UNIFORM\", cfg.base_searchbot_cfg.qre\n assert all(\n spec.rescore_policy_path is None for spec in self.qre_type2spec.values()\n ), \"When target_pi is uniform extra policies are not supported\"\n logging.info(\n \"Performing bayes quantal response equilibrium hedge with different player types:\\n%s\",\n \"\\n\".join(\n f\"{i}: {spec.name} {spec}\" for i, spec in enumerate(self.qre_type2spec.values())\n ),\n )\n self.log_intermediate_iterations = cfg.base_searchbot_cfg.log_intermediate_iterations\n assert self.qre is not None, \"base_searchbot_cfg qre needs to be set.\"\n logging.info(f\"Initialized BQRE1P Agent: {self.__dict__}\")\n\n def initialize_state(self, power: Power) -> AgentState:\n state = BayesAgentState(power=power, player_types=self.player_types)\n if self.agent_type_is_public:\n pure_type_belief = np.zeros(self.num_player_types)\n pure_type_belief[self.agent_type] = 1\n state.belief_state.beliefs[power] = pure_type_belief[:]\n return state\n\n def get_exploited_agent_power(self) -> Optional[Power]:\n assert self.exploited_agent is None\n return None\n\n def set_player_type_spec(\n self,\n specs: List[PlayerTypeSpec],\n *,\n skip_base_strategy_model_cache=False,\n allow_reuse_model=True,\n ) -> None:\n \"\"\"(Re-)initializes type configuration from a list of specs.\"\"\"\n assert len(self.player_types) == len(specs), (len(self.player_types), len(specs))\n base_strategy_model_wrapper_kwargs = dict(\n device=self.base_strategy_model.device,\n max_batch_size=self.base_strategy_model.max_batch_size,\n half_precision=self.base_strategy_model.half_precision,\n )\n self.qre_type2spec = dict(zip(self.player_types, specs))\n self.qre_extra_rescoring_models, old_qre_extra_rescoring_models = (\n {},\n self.qre_extra_rescoring_models,\n )\n for spec in self.qre_type2spec.values():\n spec.assert_valid()\n if (\n spec.rescore_policy_path is not None\n and spec.rescore_policy_path not in self.qre_extra_rescoring_models\n ):\n if (\n spec.rescore_policy_path in old_qre_extra_rescoring_models\n and allow_reuse_model\n ):\n self.qre_extra_rescoring_models[\n spec.policy_name\n ] = old_qre_extra_rescoring_models[spec.rescore_policy_path]\n else:\n base_strategy_model = BaseStrategyModelWrapper(\n spec.rescore_policy_path, **base_strategy_model_wrapper_kwargs\n )\n assert self.parlai_model_orders is None\n self.qre_extra_rescoring_models[spec.policy_name] = PlausibleOrderSampler(\n self.order_sampler.cfg, base_strategy_model=base_strategy_model\n )\n\n def get_player_type_strings(self) -> List[str]:\n return [self.qre_type2spec[x].name for x in self.player_types]\n\n def _get_scale_pow_lambdas(self, game: pydipcc.Game) -> Tuple[float, float]:\n scale_lambdas = 1.0\n pow_lambdas = 1.0\n if game.current_year == 1901:\n if self.scale_lambdas_1901 is not None:\n scale_lambdas = self.scale_lambdas_1901\n if self.pow_lambdas_1901 is not None:\n pow_lambdas = self.pow_lambdas_1901\n if game.current_short_phase == \"S1901M\":\n if self.scale_lambdas_1901_spring is not None:\n scale_lambdas = self.scale_lambdas_1901_spring\n if self.pow_lambdas_1901_spring is not None:\n pow_lambdas = self.pow_lambdas_1901_spring\n return (scale_lambdas, pow_lambdas)\n\n def _get_dynamic_lambda_scale(\n self, game: pydipcc.Game, agent_power: Optional[Power], agent_state: Optional[AgentState]\n ) -> Dict[Power, float]:\n if not self.dynamic_lambda_stdev_num_samples:\n return {power: 1.0 for power in POWERS}\n\n assert agent_state is not None, \"If using dynamic lambda, agent_state should not be None\"\n assert self.dynamic_lambda_stdev_espilon is not None\n assert self.dynamic_lambda_stdev_baseline is not None\n\n phase = game.get_current_phase()\n assert isinstance(agent_state, BayesAgentState)\n if phase not in agent_state.dynamic_lambda_scale_cache:\n # Rollout *through* exactly one set of movement phase orders.\n override_max_rollout_length = 1 if phase.endswith(\"M\") else 2\n # Shape [len(set_orders_dicts), num_powers, num_value_functions].\n rollout_results = self.base_strategy_model_rollouts.do_rollouts_multi(\n game,\n agent_power=agent_power,\n set_orders_dicts=[{}] * self.dynamic_lambda_stdev_num_samples,\n override_max_rollout_length=override_max_rollout_length,\n )\n rollout_results = rollout_results.squeeze(2)\n means_by_power = torch.mean(rollout_results, dim=0)\n variances_by_power = torch.mean(\n torch.square(rollout_results - means_by_power.unsqueeze(0)), dim=0\n )\n\n means_by_power_list = means_by_power.cpu().tolist()\n variances_by_power_list = variances_by_power.cpu().tolist()\n assert len(means_by_power_list) == len(POWERS)\n assert len(variances_by_power_list) == len(POWERS)\n\n epsilon = self.dynamic_lambda_stdev_espilon\n stdevs_by_power_list = [\n math.sqrt(variance + epsilon * epsilon) for variance in variances_by_power_list\n ]\n logging.info(\n f\"Dynamic lambda: power means: {list(zip(POWERS,['%.3f' % x for x in means_by_power_list]))}\"\n )\n logging.info(\n f\"Dynamic lambda: power stdevs (after epsilon {epsilon}): {list(zip(POWERS,['%.3f' % x for x in stdevs_by_power_list]))}\"\n )\n\n dynamic_lambda_scale_by_power_list = [\n stdev / self.dynamic_lambda_stdev_baseline for stdev in stdevs_by_power_list\n ]\n dynamic_lambda_scale_by_power = dict(zip(POWERS, dynamic_lambda_scale_by_power_list))\n agent_state.dynamic_lambda_scale_cache[phase] = dynamic_lambda_scale_by_power\n\n logging.info(\n f\"Dynamic lambda final scale: {[(power,'%.3f' % x) for (power,x) in agent_state.dynamic_lambda_scale_cache[phase].items()]}\"\n )\n return agent_state.dynamic_lambda_scale_cache[phase]\n\n def _handle_extra_plausible_and_rescoring(\n self,\n game: pydipcc.Game,\n bp_policy: PowerPolicies,\n extra_plausible_orders: Optional[PlausibleOrders],\n agent_power: Optional[Power],\n ):\n if extra_plausible_orders:\n for pwr, policy in extra_plausible_orders.items():\n for action in policy:\n if action not in bp_policy[pwr]:\n logging.info(f\"Adding extra plausible orders {pwr}: {action}\")\n bp_policy[pwr][action] = 0.0\n\n bp_policy = self.order_sampler.rescore_actions(\n game, has_press=self.has_press, agent_power=agent_power, input_policy=bp_policy\n )\n\n biasing_policies = {PlayerTypeSpec.BLUEPRINT_POLICY_NAME: bp_policy}\n for name, sampler in self.qre_extra_rescoring_models.items():\n logging.info(\"Querying %s\", name)\n biasing_policies[name] = sampler.rescore_actions(\n game, has_press=self.has_press, agent_power=agent_power, input_policy=bp_policy\n )\n return bp_policy, biasing_policies\n\n def run_search(\n self,\n game: pydipcc.Game,\n *,\n bp_policy: Optional[PowerPolicies] = None,\n early_exit_for_power: Optional[Power] = None,\n timings: Optional[TimingCtx] = None,\n extra_plausible_orders: Optional[PlausibleOrders] = None,\n agent_power: Optional[Power] = None,\n agent_state: Optional[AgentState],\n rollout_results_cache: Optional[RolloutResultsCache] = None,\n pre_rescored_bp: Optional[PowerPolicies] = None,\n ) -> BRMResult:\n \"\"\"Same as get_all_power_prob_distributions but also returns the stats about the bcfr\"\"\"\n # If there are no locations to order, bail\n if early_exit_for_power and len(game.get_orderable_locations()[early_exit_for_power]) == 0:\n if agent_power is not None:\n assert early_exit_for_power == agent_power\n return self._early_quit_bcfr_result(\n power=early_exit_for_power, agent_state=agent_state\n )\n\n if timings is None:\n timings = TimingCtx()\n timings.start(\"one-time\")\n\n deadline: Optional[float] = (\n time.monotonic() + self.max_seconds if self.max_seconds > 0 else None\n )\n\n if agent_state is not None:\n assert isinstance(agent_state, BayesAgentState)\n belief_state = agent_state.belief_state\n else:\n belief_state = BeliefState(self.player_types)\n\n logging.info(f\"BEGINNING BQRE run_search, agent_power={agent_power}\")\n if rollout_results_cache is not None:\n maybe_rollout_results_cache = rollout_results_cache\n else:\n maybe_rollout_results_cache = (\n self.base_strategy_model_rollouts.build_cache()\n if self.cache_rollout_results\n else None\n )\n\n # Compute blueprint policy for each of the different types\n with timings.create_subcontext() as sub_timings, sub_timings(\"get_plausible_order\"):\n if bp_policy is None:\n bp_policy = self.get_plausible_orders_policy(\n game, agent_power=agent_power, agent_state=agent_state\n )\n\n bp_policy, biasing_policies = self._handle_extra_plausible_and_rescoring(\n game, bp_policy, extra_plausible_orders, agent_power\n )\n\n scale_lambdas, pow_lambdas = self._get_scale_pow_lambdas(game)\n scale_lambdas_by_power = self._get_dynamic_lambda_scale(game, agent_power, agent_state)\n\n bqre_data = _make_bqre_data(\n biasing_policies,\n specs=self.qre_type2spec,\n qre=self.qre,\n pow_lambdas=pow_lambdas,\n scale_lambdas=scale_lambdas,\n scale_lambdas_by_power=scale_lambdas_by_power,\n agent_power=agent_power,\n )\n\n if agent_power is not None:\n bilateral_stats = BilateralStats(\n game, agent_power, bqre_data.get_best_type_data().power_plausible_orders\n )\n else:\n bilateral_stats = None\n power_is_loser = {} # make typechecker happy\n last_search_iter = False\n for bqre_iter in range(self.n_rollouts):\n if last_search_iter:\n logging.info(f\"Early exit from BCFR after {bqre_iter} iterations by timeout\")\n break\n elif deadline is not None and time.monotonic() >= deadline:\n last_search_iter = True\n timings.start(\"start\")\n # do verbose logging on 2^x iters\n verbose_log_iter = self.is_verbose_log_iter(bqre_iter) or last_search_iter\n\n # Sample player types\n ptypes = {\n pwr: np.random.choice(self.player_types, 1, p=belief_state.beliefs[pwr])[\n 0\n ] # type:ignore\n for pwr in POWERS\n }\n\n timings.start(\"query_policy\")\n\n # check if the *best* type is a loser\n power_is_loser = self.get_power_loser_dict(bqre_data.get_best_type_data(), bqre_iter)\n\n ptype_power_action_ps = {\n ptype: self.get_cur_iter_strategies(cfr_data, bqre_iter)\n for ptype, cfr_data in bqre_data.type_cfr_data.items()\n }\n\n power_action_ps = {\n pwr: ptype_power_action_ps[ptype][pwr] for pwr, ptype in ptypes.items()\n }\n\n timings.start(\"apply_orders\")\n # sample policy for all powers\n\n plausible_orders = {\n pwr: bqre_data.get_type_data(ptype).power_plausible_orders[pwr]\n for pwr, ptype in ptypes.items()\n }\n\n idxs, power_sampled_orders = sample_orders_from_policy(\n plausible_orders, power_action_ps\n )\n if bilateral_stats is not None:\n bilateral_stats.accum_bilateral_probs(power_sampled_orders, weight=bqre_iter)\n set_orders_dicts = make_set_orders_dicts(plausible_orders, power_sampled_orders)\n\n timings.stop()\n\n all_set_orders_dicts = list(set_orders_dicts)\n with timings.create_subcontext(\"rollout\") as inner_timings, inner_timings(\"rollout\"):\n all_rollout_results_tensor = self.base_strategy_model_rollouts.do_rollouts_multi_maybe_cached(\n game,\n agent_power=agent_power,\n set_orders_dicts=set_orders_dicts,\n cache=maybe_rollout_results_cache,\n timings=inner_timings,\n )\n\n timings.start(\"bcfr\")\n\n for pwr, actions in plausible_orders.items():\n # pop this power and player type's results\n scores, all_rollout_results_tensor = (\n all_rollout_results_tensor[: len(actions)],\n all_rollout_results_tensor[len(actions) :],\n )\n pwr_set_order_dicts, all_set_orders_dicts = (\n all_set_orders_dicts[: len(actions)],\n all_set_orders_dicts[len(actions) :],\n )\n # Results for the first value function as RolloutResults.\n default_results: RolloutResults = [\n (orders, dict(zip(POWERS, scores[..., 0].tolist())))\n for orders, scores in zip(pwr_set_order_dicts, scores)\n ]\n\n if bilateral_stats is not None:\n bilateral_stats.accum_bilateral_values(pwr, bqre_iter, default_results)\n\n # logging.info(f\"Results {pwr} = {results}\")\n # calculate regrets\n # Shape: [len(pwr_set_order_dicts), num value functions].\n all_action_utilities = scores[:, POWERS.index(pwr)]\n\n for cur_ptype in self.player_types:\n spec = self.qre_type2spec[cur_ptype]\n action_utilities = all_action_utilities[..., 0].tolist()\n\n cfr_data = bqre_data.get_type_data(cur_ptype)\n state_utility: float = np.dot(\n ptype_power_action_ps[cur_ptype][pwr], action_utilities\n ) # type: ignore\n\n # update bcfr data structures for particular player type and power\n cfr_data.update(\n pwr=pwr,\n actions=actions,\n state_utility=state_utility,\n action_utilities=action_utilities,\n which_strategy_to_accumulate=pydipcc.CFRStats.ACCUMULATE_PREV_ITER,\n cfr_iter=bqre_iter,\n )\n\n # log some action values\n if verbose_log_iter and cur_ptype == self.player_types[0] and actions[0] != ():\n self.log_bcfr_iter_state(\n game=game,\n pwr=pwr,\n actions=actions,\n brm_data=bqre_data,\n brm_iter=bqre_iter,\n state_utility=state_utility,\n action_utilities=action_utilities,\n power_sampled_orders=power_sampled_orders,\n beliefs=belief_state.beliefs[pwr],\n pre_rescore_bp=pre_rescored_bp[pwr] if pre_rescored_bp else None,\n )\n if maybe_rollout_results_cache is not None:\n logging.info(f\"{maybe_rollout_results_cache}\")\n\n assert (\n all_rollout_results_tensor.shape[0] == 0\n ), \"all_rollout_results_tensor should be empty\"\n timings.start(\"to_dict\")\n\n # return prob. distributions for each power, player type\n ptype_avg_ret, ptype_final_ret = {}, {}\n power_is_loser = self.get_power_loser_dict(bqre_data.get_best_type_data(), self.n_rollouts)\n for player_type in self.player_types:\n avg_ret, final_ret = {}, {}\n cfr_data = bqre_data.get_type_data(player_type)\n for p in POWERS:\n if power_is_loser[p] or p == self.exploited_agent_power:\n avg_ret[p] = final_ret[p] = cfr_data.bp_policy(p)\n else:\n avg_ret[p] = cfr_data.avg_policy(p)\n final_ret[p] = cfr_data.cur_iter_policy(p)\n\n ptype_avg_ret[player_type] = avg_ret\n ptype_final_ret[player_type] = final_ret\n\n logging.info(\n \"Raw Values: %s\",\n {\n p: f\"{x:.3f}\"\n for p, x in zip(\n POWERS,\n self.base_strategy_model.get_values(\n game, has_press=self.has_press, agent_power=agent_power\n ),\n )\n },\n )\n logging.info(\n \"BQRE Values (Agent Type: %s): %s\",\n self.agent_type,\n {p: f\"{bqre_data.get_type_data(self.agent_type).avg_utility(p):.3f}\" for p in POWERS},\n )\n\n timings.stop()\n timings.pprint(logging.getLogger(\"timings\").info)\n\n if bilateral_stats is not None:\n cfr_data = bqre_data.get_best_type_data()\n if self.log_bilateral_values:\n bilateral_stats.log(cfr_data, min_order_prob=self.bilateral_cfg.min_order_prob)\n\n # Update bcfr result cache\n bcfr_result = BRMResult(\n bp_policies=bp_policy,\n ptype_avg_policies=ptype_avg_ret,\n ptype_final_policies=ptype_final_ret,\n brm_data=bqre_data,\n beliefs=belief_state.beliefs,\n agent_type=self.agent_type,\n use_final_iter=self.use_final_iter,\n bilateral_stats=bilateral_stats,\n )\n\n return bcfr_result\n\n def run_bilateral_search_with_conditional_evs(\n self,\n game: pydipcc.Game,\n *,\n bp_policy: PowerPolicies,\n early_exit_for_power: Optional[Power] = None,\n timings: Optional[TimingCtx] = None,\n extra_plausible_orders: Optional[PlausibleOrders] = None,\n agent_power: Power,\n other_power: Power,\n agent_state: Optional[AgentState],\n conditional_evs: BilateralConditionalValueTable,\n pre_rescored_bp: Optional[PowerPolicies] = None,\n ) -> BRMResult:\n \"\"\"Same as run_search but with all conditional evs precomputed, and specialized to 2 players.\n\n This function is mostly a copypasta of run_search for performance, where a lot of options\n have been removed and the specialization to 2 players allows computing things much faster.\n \"\"\"\n # If there are no locations to order, bail\n if early_exit_for_power and len(game.get_orderable_locations()[early_exit_for_power]) == 0:\n assert early_exit_for_power == agent_power\n return self._early_quit_bcfr_result(\n power=early_exit_for_power, agent_state=agent_state\n )\n\n if timings is None:\n timings = TimingCtx()\n timings.start(\"rswce_one-time\")\n\n assert self.loser_bp_value <= 0\n assert self.exploited_agent_power is None\n\n if agent_state is not None:\n assert isinstance(agent_state, BayesAgentState)\n belief_state = agent_state.belief_state\n else:\n belief_state = BeliefState(self.player_types)\n\n logging.info(f\"BEGINNING BQRE run_search_with_conditional_evs, agent_power={agent_power}\")\n\n # Compute blueprint policy for each of the different types\n with timings.create_subcontext() as sub_timings, sub_timings(\"rswce_get_plausible_order\"):\n bp_policy, biasing_policies = self._handle_extra_plausible_and_rescoring(\n game, bp_policy, extra_plausible_orders, agent_power\n )\n\n scale_lambdas, pow_lambdas = self._get_scale_pow_lambdas(game)\n scale_lambdas_by_power = self._get_dynamic_lambda_scale(game, agent_power, agent_state)\n\n bqre_data = _make_bqre_data(\n biasing_policies,\n specs=self.qre_type2spec,\n qre=self.qre,\n pow_lambdas=pow_lambdas,\n scale_lambdas=scale_lambdas,\n scale_lambdas_by_power=scale_lambdas_by_power,\n agent_power=agent_power,\n )\n\n for bqre_iter in range(self.n_rollouts):\n timings.start(\"rswce_start\")\n # do verbose logging on 2^x iters\n verbose_log_iter = self.is_verbose_log_iter(bqre_iter)\n\n # Sample player types\n # Written as an iteration over POWERS specifically to preserve the ordering\n # of the items within the dictionary to be the same order as POWERS, which\n # affects the ordering of many downstream dictionaries and the order in which\n # our logs will record things.\n ptypes = {\n pwr: np.random.choice(self.player_types, 1, p=belief_state.beliefs[pwr])[\n 0\n ] # type:ignore\n for pwr in POWERS\n if pwr in (agent_power, other_power)\n }\n\n timings.start(\"rswce_query_policy\")\n\n ptype_power_action_ps = {\n ptype: self.get_cur_iter_strategies(cfr_data, bqre_iter)\n for ptype, cfr_data in bqre_data.type_cfr_data.items()\n }\n\n power_action_ps = {\n pwr: ptype_power_action_ps[ptype][pwr] for pwr, ptype in ptypes.items()\n }\n\n timings.start(\"rswce_apply_orders\")\n # sample policy for all powers\n\n plausible_orders = {\n pwr: bqre_data.get_type_data(ptype).power_plausible_orders[pwr]\n for pwr, ptype in ptypes.items()\n }\n\n _idxs, power_sampled_orders = sample_orders_from_policy(\n plausible_orders, power_action_ps\n )\n\n timings.stop()\n\n timings.start(\"rswce_bcfr\")\n\n for pwr, actions in plausible_orders.items():\n if pwr == agent_power:\n other_sampled_action = power_sampled_orders[other_power]\n scores_list = [\n conditional_evs[(agent_action, other_sampled_action)]\n for agent_action in actions\n ]\n else:\n agent_sampled_action = power_sampled_orders[agent_power]\n scores_list = [\n conditional_evs[(agent_sampled_action, other_action)]\n for other_action in actions\n ]\n\n # scores_list is a list of tensors of shape (7,), indicating the value estimate for all 7 players\n # conditional on each plausible action of pwr and the sampled action of the other power besides pwr.\n # Stack into an (N,7) tensor.\n scores = torch.stack(scores_list, 0)\n\n # logging.info(f\"Results {pwr} = {results}\")\n # calculate regrets\n # Shape: [len(pwr_set_order_dicts), num value functions].\n all_action_utilities = scores[:, POWERS.index(pwr)]\n\n for cur_ptype in self.player_types:\n spec = self.qre_type2spec[cur_ptype]\n action_utilities = all_action_utilities[..., 0].tolist()\n\n cfr_data = bqre_data.get_type_data(cur_ptype)\n state_utility: float = np.dot(\n ptype_power_action_ps[cur_ptype][pwr], action_utilities\n ) # type: ignore\n\n # update bcfr data structures for particular player type and power\n cfr_data.update(\n pwr=pwr,\n actions=actions,\n state_utility=state_utility,\n action_utilities=action_utilities,\n which_strategy_to_accumulate=pydipcc.CFRStats.ACCUMULATE_PREV_ITER,\n cfr_iter=bqre_iter,\n )\n\n # log some action values\n if verbose_log_iter and cur_ptype == self.player_types[0] and actions[0] != ():\n self.log_bcfr_iter_state(\n game=game,\n pwr=pwr,\n actions=actions,\n brm_data=bqre_data,\n brm_iter=bqre_iter,\n state_utility=state_utility,\n action_utilities=action_utilities,\n power_sampled_orders=power_sampled_orders,\n beliefs=belief_state.beliefs[pwr],\n pre_rescore_bp=pre_rescored_bp[pwr] if pre_rescored_bp else None,\n )\n\n timings.start(\"rswce_to_dict\")\n\n # return prob. distributions for each power, player type\n ptype_avg_ret, ptype_final_ret = {}, {}\n for player_type in self.player_types:\n avg_ret, final_ret = {}, {}\n cfr_data = bqre_data.get_type_data(player_type)\n for p in POWERS:\n avg_ret[p] = cfr_data.avg_policy(p)\n final_ret[p] = cfr_data.cur_iter_policy(p)\n\n ptype_avg_ret[player_type] = avg_ret\n ptype_final_ret[player_type] = final_ret\n\n logging.info(\n \"Raw Values: %s\",\n {\n p: f\"{x:.3f}\"\n for p, x in zip(\n POWERS,\n self.base_strategy_model.get_values(\n game, has_press=self.has_press, agent_power=agent_power\n ),\n )\n },\n )\n logging.info(\n \"BQRE Values (Agent Type: %s): %s\",\n self.agent_type,\n {p: f\"{bqre_data.get_type_data(self.agent_type).avg_utility(p):.3f}\" for p in POWERS},\n )\n\n timings.stop()\n\n # Update bcfr result cache\n bcfr_result = BRMResult(\n bp_policies=bp_policy,\n ptype_avg_policies=ptype_avg_ret,\n ptype_final_policies=ptype_final_ret,\n brm_data=bqre_data,\n beliefs=belief_state.beliefs,\n agent_type=self.agent_type,\n use_final_iter=self.use_final_iter,\n bilateral_stats=None,\n )\n\n return bcfr_result\n\n def run_best_response_against_correlated_bilateral_search(\n self,\n game: pydipcc.Game,\n *,\n bp_policy: Optional[PowerPolicies] = None,\n early_exit_for_power: Optional[Power] = None,\n timings: Optional[TimingCtx] = None,\n extra_plausible_orders: Optional[PlausibleOrders] = None,\n agent_power: Power,\n agent_state: Optional[AgentState] = None,\n ) -> SearchResult:\n assert agent_power is not None\n assert self.all_power_base_strategy_model_executor is not None\n\n # If there are no locations to order, bail\n if early_exit_for_power and len(game.get_orderable_locations()[early_exit_for_power]) == 0:\n if agent_power is not None:\n assert early_exit_for_power == agent_power\n return self._early_quit_bcfr_result(\n power=early_exit_for_power, agent_state=agent_state\n )\n\n if timings is None:\n timings = TimingCtx()\n\n if bp_policy is None:\n timings.start(\"corr_search_allpower_bp\")\n # this is the bp considering our (agent_power's) conversation with every other power\n bp_policy = self.get_plausible_orders_policy(\n game, agent_power=agent_power, agent_state=agent_state\n )\n bp_policy = filter_invalid_actions_from_policy(bp_policy, game)\n # 1) get pairwise bqre policies for all our opponents\n bqre_policies: PowerPolicies = {}\n timings.start(\"corr_search_rescore_bp\")\n if self.order_sampler.do_parlai_rescoring:\n opponent_rescored_policies = rescore_bp_from_bilateral_views(\n game, bp_policy, agent_power, self.order_sampler\n )\n else:\n # bp was not rescored by parlai model, i.e. no-press game\n opponent_rescored_policies = {\n power: bp_policy for power in bp_policy if power != agent_power\n }\n\n timings.start(\"corr_search_payoff_matrix\")\n value_table_cache = None\n if agent_state is not None:\n assert isinstance(agent_state, SearchBotAgentState)\n value_table_cache = agent_state.get_cached_value_tables(game)\n\n # power_value_matrices[pwr] stores the values of the joint actions between agent_power and pwr\n # each value matrix is a map from frozenset((pwr, action), (agent_pwr, action)) -> Tensor [7, 1]\n power_value_matrices: Dict[\n Power, BilateralConditionalValueTable\n ] = compute_payoff_matrix_for_all_opponents(\n game,\n all_power_base_strategy_model=self.all_power_base_strategy_model_executor,\n bp_policy=bp_policy,\n agent_power=agent_power,\n num_sample=self.br_corr_bilateral_search_cfg.bilateral_search_num_cond_sample,\n has_press=self.has_press,\n player_rating=self.player_rating,\n value_table_cache=value_table_cache,\n )\n\n timings.start(\"corr_search_pairwise_cfr\")\n for opponent, policy in bp_policy.items():\n if opponent == agent_power:\n continue\n if len(policy) == 1 and list(policy.keys())[0] == ():\n continue\n\n logging.info(f\"BQRE1P.run_search between {agent_power}, {opponent}\")\n if timings is not None:\n timings.start(\"corr_search_run_search\")\n rescored_pair_policy = extract_bp_policy_for_powers(\n opponent_rescored_policies[opponent], [agent_power, opponent],\n )\n search_result = self.run_bilateral_search_with_conditional_evs(\n game,\n bp_policy=rescored_pair_policy,\n early_exit_for_power=early_exit_for_power,\n extra_plausible_orders=extra_plausible_orders,\n agent_power=agent_power,\n other_power=opponent,\n agent_state=agent_state,\n conditional_evs=power_value_matrices[opponent],\n pre_rescored_bp=bp_policy,\n )\n bqre_policies[opponent] = search_result.get_population_policy(opponent)[opponent]\n\n result = BRCorrBilateralSearchResult(\n agent_power, bp_policy, bqre_policies, power_value_matrices\n )\n if len(bp_policy[agent_power]) == 1:\n [action] = list(bp_policy[agent_power])\n result.set_policy_and_value_for_power(agent_power, action, best_value=0)\n return result\n\n timings.start(\"corr_search_br_sample\")\n # 2) now we have both bp_policy and others uncorr_policy\n # next we sample k(=10 default) joint actions to use as candidates for reweighting\n opponent_joint_actions = sample_joint_actions(\n result.policies, self.br_corr_bilateral_search_cfg.br_num_sample\n )\n\n timings.start(\"corr_search_br_weight\")\n base_strategy_model_rescored_bp_policy = self.order_sampler.rescore_actions_base_strategy_model(\n game,\n has_press=self.has_press,\n agent_power=None, # agent_power,\n input_policy=bp_policy,\n model=self.base_strategy_model.model,\n )\n\n if self.br_corr_bilateral_search_cfg.use_all_power_for_p_joint:\n joint_action_weights = compute_weights_for_opponent_joint_actions(\n opponent_joint_actions,\n agent_power,\n game,\n self.all_power_base_strategy_model_executor.get_model().model,\n base_strategy_model_rescored_bp_policy,\n self.has_press,\n self.br_corr_bilateral_search_cfg.min_unnormalized_weight,\n self.br_corr_bilateral_search_cfg.max_unnormalized_weight,\n )\n else:\n assert self.br_corr_bilateral_search_cfg.joint_action_min_prob == 0\n joint_action_weights = [\n 1 / len(opponent_joint_actions) for _ in opponent_joint_actions\n ]\n\n with timings(\"interruption\"):\n raise_if_should_stop(post_pseudoorders=False)\n\n # 3) compute weighted best response\n br_regularize_lambda = self.br_corr_bilateral_search_cfg.br_regularize_lambda\n scale_lambdas, pow_lambdas = self._get_scale_pow_lambdas(game)\n scale_lambdas_by_power = self._get_dynamic_lambda_scale(game, agent_power, agent_state)\n\n logging.info(\n f\"Config br_regularize_lambda {br_regularize_lambda}, scale_lambdas {scale_lambdas}, pow_lambdas {pow_lambdas}\"\n )\n br_regularize_lambda = (\n scale_lambdas_by_power[agent_power]\n * scale_lambdas\n * (br_regularize_lambda ** pow_lambdas)\n )\n\n timings.start(\"corr_search_br_get_action\")\n best_action, best_value = compute_best_action_against_reweighted_opponent_joint_actions(\n game,\n agent_power,\n bp_policy[agent_power],\n opponent_joint_actions,\n joint_action_weights,\n self.all_power_base_strategy_model_executor,\n self.player_rating,\n br_regularize_lambda,\n )\n result.set_policy_and_value_for_power(agent_power, best_action, best_value)\n\n timings.stop()\n timings.pprint(logging.getLogger(\"timings\").info)\n return result\n\n def log_bcfr_iter_state(\n self,\n *,\n game: pydipcc.Game,\n pwr: Power,\n actions: List[Action],\n brm_data: BRMData,\n brm_iter: int,\n state_utility: float,\n action_utilities: List[float],\n power_sampled_orders: JointAction,\n beliefs: np.ndarray,\n pre_rescore_bp: Optional[Policy] = None,\n ):\n agent_cfr_data = brm_data.get_type_data(self.agent_type)\n logging.info(\n f\"<> [ {brm_iter+1} / {self.n_rollouts} ] {pwr} {game.phase} avg_utility={agent_cfr_data.avg_utility(pwr):.5f} cur_utility={state_utility:.5f} \"\n )\n logging.info(f\">> {pwr} cur action at {brm_iter+1}: {power_sampled_orders[pwr]}\")\n if pre_rescore_bp is None:\n logging.info(\n f\" {'agent_p':8s} {'pop_p':8s} {'bp_p':8s} {'avg_u':8s} {'cur_u':8s} orders\"\n )\n else:\n logging.info(\n f\" {'agent_p':8s} {'pop_p':8s} {'bp_p':8s} {'pre_bp_p':8s} {'avg_u':8s} {'cur_u':8s} orders\"\n )\n agent_type_action_probs: List[float] = agent_cfr_data.avg_strategy(pwr)\n population_action_probs = np.zeros(len(agent_type_action_probs))\n for player_type in self.player_types:\n population_action_probs += beliefs[player_type] * np.array(\n brm_data.get_type_data(player_type).avg_strategy(pwr)\n )\n bp_probs: List[float] = agent_cfr_data.bp_strategy(pwr)\n avg_utilities: List[float] = agent_cfr_data.avg_action_utilities(pwr)\n sorted_metrics = sorted(\n zip(\n actions,\n agent_type_action_probs,\n population_action_probs,\n bp_probs,\n avg_utilities,\n action_utilities,\n ),\n key=lambda ac: -ac[1],\n )\n for orders, a_p, p_p, bp_p, avg_u, cur_u in sorted_metrics:\n if pre_rescore_bp is None:\n logging.info(\n f\"|> {a_p:8.5f} {p_p:8.5f} {bp_p:8.5f} {avg_u:8.5f} {cur_u:8.5f} {orders}\"\n )\n else:\n logging.info(\n f\"|> {a_p:8.5f} {p_p:8.5f} {bp_p:8.5f} {pre_rescore_bp[orders]:8.5f} {avg_u:8.5f} {cur_u:8.5f} {orders}\"\n )\n\n def _early_quit_bcfr_result(\n self, power: Power, agent_state: Optional[AgentState], *, action: Action = tuple()\n ) -> BRMResult:\n ptype_policies = {ptype: {power: {action: 1.0}} for ptype in self.player_types}\n if agent_state is not None:\n assert isinstance(agent_state, BayesAgentState)\n belief_state = agent_state.belief_state\n else:\n belief_state = BeliefState(self.player_types)\n return BRMResult(\n bp_policies=ptype_policies[self.player_types[0]],\n ptype_avg_policies=ptype_policies,\n ptype_final_policies=ptype_policies,\n brm_data=None,\n beliefs=belief_state.beliefs,\n agent_type=self.agent_type,\n use_final_iter=self.use_final_iter,\n )\n\n\nif __name__ == \"__main__\":\n import pathlib\n import heyhi\n import sys\n\n logging.basicConfig(format=\"%(asctime)s [%(levelname)s]: %(message)s\", level=logging.INFO)\n\n np.random.seed(0) # type:ignore\n torch.manual_seed(0)\n\n game = pydipcc.Game()\n cfg = heyhi.load_config(\n pathlib.Path(__file__).resolve().parents[2]\n / \"conf/common/agents/bqre1p_20210723.prototxt\",\n overrides=[\"bqre1p.base_searchbot_cfg.n_rollouts=64\"] + sys.argv[1:],\n )\n print(cfg.bqre1p)\n agent = BQRE1PAgent(cfg.bqre1p)\n print(agent.get_orders(game, power=\"AUSTRIA\", state=agent.initialize_state(power=\"AUSTRIA\")))\n","repo_name":"facebookresearch/diplomacy_cicero","sub_path":"fairdiplomacy/agents/bqre1p_agent.py","file_name":"bqre1p_agent.py","file_ext":"py","file_size_in_byte":53680,"program_lang":"python","lang":"en","doc_type":"code","stars":1121,"dataset":"github-code","pt":"77"}
+{"seq_id":"72997501368","text":"import json\nfiles = ['outfile0.json', 'outfile1.json',\n 'outfile2.json', 'outfile3.json', 'outfile4.json']\ncount = 0\nfor i in files:\n with open(i, 'r') as f:\n data = json.load(f)\n dict_ = {}\n for j in data:\n if j['post_url'] not in dict_:\n dict_[j['post_url']] = 0\n with open(i+'_output.json', 'a+') as m:\n m.write(json.dumps(j) + ',\\n')\n with open(i+'_output.txt', 'w+') as g:\n for k in dict_.keys():\n g.write(k + '\\n')\n count += len(dict_)\nprint(count)\n","repo_name":"Heave6899/mediscrape_engine","sub_path":"CODE/processing/uniqueposts.py","file_name":"uniqueposts.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"13890637533","text":"import cv2 as cv\r\nimport numpy as np\r\n\r\nimg = cv.imread('images/chessboard.png')\r\ncv.imshow('Image', img)\r\n\r\ngray_image = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\r\ngray_image = np.float32(gray_image)\r\ndst = cv.cornerHarris(gray_image, 2, 3, 0.04)\r\n\r\ndst = cv.dilate(dst, None)\r\n\r\nimg[dst > 0.01 * dst.max()] = [0, 0, 255]\r\ncv.imshow('Result', img)\r\n\r\nif cv.waitKey(0) & 0xFF == 27:\r\n cv.destroyAllWindows()\r\n","repo_name":"JamiKazmi/ImageProcessingOpenCV-Python","sub_path":"30_harris_corner_detector.py","file_name":"30_harris_corner_detector.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"39292105740","text":"import pickle\r\nimport os\r\ndef main():\r\n try:\r\n filename = 'emails.txt'\r\n currentdictionary = read_file(filename);\r\n selectedoption = present_options()\r\n name = input('Enter name ')\r\n if not name:\r\n raise ValueError('Please enter a name')\r\n if selectedoption == '1':\r\n searchresult = lookup_emailaddresses(name,currentdictionary)\r\n if not searchresult:\r\n print('No email found for', name)\r\n else:\r\n print(searchresult[1], 'was found for', name)\r\n elif selectedoption == '2':\r\n add_emailaddresses(name, currentdictionary)\r\n elif selectedoption == '3':\r\n update_emailaddresses(name, currentdictionary)\r\n else:\r\n delete_emailaddresses(name, currentdictionary)\r\n if len(currentdictionary) > 0:\r\n write_file(filename, currentdictionary)\r\n except ValueError as inputerror:\r\n print(inputerror)\r\n except IOError as fileerror:\r\n print('There was an error processing the file ', filename)\r\n #menu\r\ndef present_options():\r\n print('Select the operation you would like to perform')\r\n print('Enter 1 to Lookup an Email in the List')\r\n print('Enter 2 to Add an Email to the List')\r\n print('Enter 3 to Update and Email in the List')\r\n print('Enter 4 to delete and email')\r\n choice = input('Enter 1, 2, 3 or 4 ')\r\n if not choice or (choice != '1' and choice != '2' and choice != '3' and choice != '4'):\r\n raise ValueError('Please enter 1, 2, 3 or 4. ')\r\n return choice\r\n#reads file\r\ndef read_file(filename):\r\n emaildictionary = {}\r\n if os.path.isfile(filename):\r\n file = open(filename, 'rb')\r\n emaildictionary = pickle.load(file)\r\n return emaildictionary\r\n\r\n#writing from a file\r\ndef write_file(filename, currentdictionary):\r\n file = open(filename, 'wb')\r\n pickle.dump(currentdictionary,file) \r\n \r\n#adding emails\r\ndef add_emailaddresses(name, currentdictionary):\r\n email = input('Enter the email address you would like to add ')\r\n if not email:\r\n raise ValueError('Please enter an email address')\r\n currentdictionary[name] = email\r\n print(name , 'and this email',email, 'has been added to the list')\r\n#looks for the email in the file\r\ndef lookup_emailaddresses(name, currentdictionary):\r\n for key, value in currentdictionary.items():\r\n if name.lower() == key.lower():\r\n return key, value\r\n#updating the email\r\ndef update_emailaddresses(name, currentdictionary):\r\n searchresult = lookup_emailaddresses(name,currentdictionary)\r\n if not searchresult:\r\n print(name, 'Was not found in the list')\r\n else:\r\n question = 'Enter the new email address you would like to replace ' + searchresult[1] + ' '\r\n newemail = input(question)\r\n if not newemail:\r\n raise ValueError('Please enter an email address')\r\n currentdictionary[searchresult[0]] = newemail\r\n print(newemail , 'has been replaced for ', name)\r\n#deleting the email\r\ndef delete_emailaddresses(name, currentdictionary):\r\n searchresult = lookup_emailaddresses(name,currentdictionary)\r\n if not searchresult:\r\n print(name, 'Was not found in the list')\r\n else:\r\n del currentdictionary[searchresult[0]]\r\n \r\n\r\n\r\nmain()\r\n","repo_name":"brandonanzalone/PRG105","sub_path":"MailMaintenance.py","file_name":"MailMaintenance.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"29332450729","text":"def solicitar_datos():\n ingreso = float(input(\"Ingrese su ingreso en pesos: \"))\n ano_nacimiento = int(input(\"Ingrese su año de nacimiento: \"))\n num_hijos = int(input(\"Ingrese el número de hijos que tiene: \"))\n anos_pertenencia = int(input(\"Ingrese los años de pertenencia al banco: \"))\n estado_civil = input(\"Ingrese su estado civil (S para soltero, C para casado): \")\n tipo_vivienda = input(\"Ingrese el tipo de vivienda (U para urbano, R para rural): \")\n \n return ingreso, ano_nacimiento, num_hijos, anos_pertenencia, estado_civil, tipo_vivienda\n\n\ndef aprobar_credito(ingreso, ano_nacimiento, num_hijos, anos_pertenencia, estado_civil, tipo_vivienda):\n if anos_pertenencia > 10 and num_hijos >= 2:\n return True\n\n if estado_civil == \"C\" and num_hijos > 3 and 45 <= (2023 - ano_nacimiento) <= 55:\n return True\n\n if ingreso > 2500000 and estado_civil == \"S\" and tipo_vivienda == \"U\":\n return True\n\n if ingreso > 3500000 and anos_pertenencia > 5:\n return True\n\n if tipo_vivienda == \"R\" and estado_civil == \"C\" and num_hijos < 2:\n return True\n\n return False\n\n\ndef main():\n ingreso, ano_nacimiento, num_hijos, anos_pertenencia, estado_civil, tipo_vivienda = solicitar_datos()\n if aprobar_credito(ingreso, ano_nacimiento, num_hijos, anos_pertenencia, estado_civil, tipo_vivienda):\n print(\"APROBADO\")\n else:\n print(\"RECHAZADO\")\n\n\n# Ejecutar el programa\nmain()\n\n ","repo_name":"pabloschwarzenberg/grader","sub_path":"hito1_ej3/hito1_ej3_f02e1999ea448f0d1226347d4d54664e.py","file_name":"hito1_ej3_f02e1999ea448f0d1226347d4d54664e.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"42957951662","text":"import pandas as pd\nimport numpy as np\nfrom scipy.special import beta\nfrom scipy import integrate\nimport matplotlib.pyplot as plt\n\n# import data:\ndf = pd.read_csv(\"./clms.txt\", header = None)((asddmomds))\ndf[\"x\"] = df[0]\n\n# Q1: \n\nfrom scipy import integrate\n\ndef prob_gb2(x_value):\n a_value = 0.8370464113216801\n b_value = 36324509.41502439\n p_value = 0.8013535696450651\n q_value = 9871.420693943379\n prob = a_value*x_value**(a_value*p_value-1)/b_value**(a_value*p_value)/beta(p_value, q_value)/(1+(x_value/b_value)**a_value)**(p_value + q_value)\n if prob < 1e-15:\n prob = 1e-15\n return prob\n\ndef prob_ga(x_value):\n alpha_value = 0.7102143006296369\n beta_value = 551.0179500811464\n prob = 1/(beta_value**(alpha_value) * math.gamma(alpha_value))*x_value**(alpha_value-1)*np.exp(-x_value/beta_value)\n\n if prob < 1e-15:\n prob = 1e-15\n return prob\n\n\ndef q2_pdf1(df, alpha_v, rho_v, mu_v, sigma_v):\n df[\"prob\"] = np.nan\n df[\"z\"] = np.nan\n for index, row in df.iterrows():\n if index == 0:\n prev_z = mu_v\n current_z = np.log(row.w/(1-alpha_v)/row.k**alpha_v)\n current_mean = (rho_v*prev_z) + (1- rho_v)*mu_v\n df.loc[index, \"z\"] = current_z\n prob_t = 1/sigma_v/math.sqrt(2*math.pi)*np.exp(-0.5*((current_z- current_mean)/sigma_v)**2)\n if prob_t < 1e-8:\n prob_t = 1e-8\n df.loc[index, \"prob\"] = prob_t\n \n else:\n t_prev = index -1\n prev_z = df.loc[t_prev, \"z\"]\n current_z = np.log(row.w/(1-alpha_v)/row.k**alpha_v)\n current_mean = (rho_v*prev_z) + (1- rho_v)*mu_v\n df.loc[index, \"z\"] = current_z\n prob_t = 1/sigma_v/math.sqrt(2*math.pi)*np.exp(-0.5*((current_z- current_mean)/sigma_v)**2)\n if prob_t < 1e-8:\n prob_t = 1e-8\n df.loc[index, \"prob\"] = prob_t\n return df[\"prob\"]\n\n\n\ndef crit_q2pdf1(params, *args):\n alpha_v, rho_v, mu_v, sigma_v = params\n df = list(args)[0]\n pdf_values = np.log(q2_pdf1(df, alpha_v, rho_v, mu_v, sigma_v))\n negloglik = -sum(pdf_values)\n return negloglik\n\n\n","repo_name":"xiangyum/StructEst_W20","sub_path":"ProblemSets/PS2/hw2_p2.py","file_name":"hw2_p2.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"77"}
+{"seq_id":"74940947127","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n'''\r\n@ref: A Context-Aware Click Model for Web Search\r\n@author: Jia Chen, Jiaxin Mao, Yiqun Liu, Min Zhang, Shaoping Ma\r\n@desc: Configurations and startups\r\n'''\r\nimport os\r\nimport argparse\r\nimport logging\r\nimport time\r\nfrom dataset import Dataset\r\nfrom model import Model\r\nfrom utils import *\r\n\r\ndef parse_args():\r\n parser = argparse.ArgumentParser('CACM')\r\n parser.add_argument('--train', action='store_true',\r\n help='train the model')\r\n parser.add_argument('--test', action='store_true',\r\n help='test on test set')\r\n parser.add_argument('--gpu', type=str, default='',\r\n help='specify gpu device')\r\n\r\n train_settings = parser.add_argument_group('train settings')\r\n train_settings.add_argument('--optim', default='adadelta',\r\n help='optimizer type')\r\n train_settings.add_argument('--learning_rate', type=float, default=0.001,\r\n help='learning rate')\r\n train_settings.add_argument('--weight_decay', type=float, default=1e-3,\r\n help='weight decay')\r\n train_settings.add_argument('--momentum', type=float, default=0.99,\r\n help='momentum')\r\n train_settings.add_argument('--dropout_rate', type=float, default=0.2,\r\n help='dropout rate')\r\n train_settings.add_argument('--batch_size', type=int, default=1,\r\n help='train batch size')\r\n train_settings.add_argument('--num_steps', type=int, default=20000,\r\n help='number of training steps')\r\n train_settings.add_argument('--num_train_files', type=int, default=1,\r\n help='number of training files')\r\n train_settings.add_argument('--num_dev_files', type=int, default=1,\r\n help='number of dev files')\r\n train_settings.add_argument('--num_test_files', type=int, default=1,\r\n help='number of test files')\r\n train_settings.add_argument('--num_label_files', type=int, default=1,\r\n help='number of label files')\r\n train_settings.add_argument('--reg_relevance', type=float, default=1.0,\r\n help='regularization for relevance training')\r\n\r\n model_settings = parser.add_argument_group('model settings')\r\n model_settings.add_argument('--algo', default='CACM',\r\n help='choose the algorithm to use')\r\n model_settings.add_argument('--embed_size', type=int, default=128,\r\n help='size of the embeddings')\r\n model_settings.add_argument('--hidden_size', type=int, default=256,\r\n help='size of LSTM hidden units')\r\n model_settings.add_argument('--max_d_num', type=int, default=10,\r\n help='max number of docs in a session')\r\n model_settings.add_argument('--max_sess_length', type=int, default=10,\r\n help='max session length')\r\n model_settings.add_argument('--use_knowledge', action=\"store_true\",\r\n help='whether use knowledge embedding')\r\n model_settings.add_argument('--use_knowledge_attention', action=\"store_true\",\r\n help='whether use knowledge attention')\r\n model_settings.add_argument('--use_state_attention', action=\"store_true\",\r\n help='whether use state attention')\r\n model_settings.add_argument('--combine', default='mul',\r\n help='type of combining the relevance and the examination to predict the click')\r\n\r\n path_settings = parser.add_argument_group('path settings')\r\n path_settings.add_argument('--train_dirs', nargs='+',\r\n default=['data/CACM/train_per_session.txt'],\r\n help='list of dirs that contain the preprocessed train data')\r\n path_settings.add_argument('--dev_dirs', nargs='+',\r\n default=['data/CACM/dev_per_session.txt'],\r\n help='list of dirs that contain the preprocessed dev data')\r\n path_settings.add_argument('--test_dirs', nargs='+',\r\n default=['data/CACM/test_per_session.txt'],\r\n help='list of dirs that contain the preprocessed test data')\r\n path_settings.add_argument('--label_dirs', nargs='+',\r\n default=['data/CACM/human_label_for_CACM.txt'],\r\n help='list of dirs that contain the preprocessed label data')\r\n path_settings.add_argument('--knowledge_type', default='simple',\r\n help='type of knowledge embedding')\r\n path_settings.add_argument('--data_dir', default='outputs/CACM/',\r\n help='the main dir')\r\n path_settings.add_argument('--model_dir', default='outputs/CACM/models/',\r\n help='the dir to store models')\r\n path_settings.add_argument('--result_dir', default='outputs/CACM/results/',\r\n help='the dir to output the results')\r\n path_settings.add_argument('--summary_dir', default='outputs/CACM/summary/',\r\n help='the dir to write tensorboard summary')\r\n path_settings.add_argument('--log_dir', default='outputs/CACM/log/',\r\n help='path of the log file. If not set, logs are printed to console')\r\n\r\n path_settings.add_argument('--eval_freq', type=int, default=2000,\r\n help='the frequency of evaluating on the dev set when training')\r\n path_settings.add_argument('--check_point', type=int, default=2000,\r\n help='the frequency of saving model')\r\n path_settings.add_argument('--patience', type=int, default=3,\r\n help='lr half when more than the patience times of evaluation\\' loss don\\'t decrease')\r\n path_settings.add_argument('--lr_decay', type=float, default=0.5,\r\n help='lr decay')\r\n path_settings.add_argument('--load_model', type=int, default=-1,\r\n help='load model global step')\r\n path_settings.add_argument('--data_parallel', type=bool, default=False,\r\n help='data_parallel')\r\n path_settings.add_argument('--gpu_num', type=int, default=1,\r\n help='gpu_num')\r\n\r\n return parser.parse_args()\r\n\r\ndef test(args):\r\n logger = logging.getLogger(\"CACM\")\r\n logger.info('Checking the data files...')\r\n for data_path in args.train_dirs + args.dev_dirs + args.test_dirs + args.label_dirs:\r\n assert os.path.exists(data_path), '{} file does not exist.'.format(data_path)\r\n dataset = Dataset(args, train_dirs=args.train_dirs, dev_dirs=args.dev_dirs, test_dirs=args.test_dirs, label_dirs=args.label_dirs)\r\n logger.info('Initialize the model...')\r\n model = Model(args, len(dataset.qid_nid), len(dataset.uid_nid), len(dataset.vtype_vid))\r\n logger.info('model.global_step: {}'.format(model.global_step))\r\n assert args.load_model > -1\r\n logger.info('Restoring the model...')\r\n model.load_model(model_dir=args.model_dir, model_prefix=args.algo, global_step=args.load_model)\r\n logger.info('Start computing LL & PPL for click prediction...')\r\n test_batches = dataset.gen_mini_batches('test', args.batch_size, shuffle=False)\r\n test_loss, test_LL, test_perplexity, test_perplexity_at_rank = model.evaluate(test_batches, dataset, result_dir=args.result_dir,\r\n result_prefix='test.predicted.{}.{}'.format(args.algo, model.global_step))\r\n logger.info('Loss: {}'.format(test_loss))\r\n logger.info('log likelihood: {}'.format(test_LL))\r\n logger.info('perplexity: {}'.format(test_perplexity))\r\n logger.info('Start computing NDCG@k for ranking performance')\r\n label_batches = dataset.gen_mini_batches('label', args.batch_size, shuffle=False)\r\n trunc_levels = [1, 3, 5, 10]\r\n ndcgs_version1, ndcgs_version2 = model.ndcg(label_batches, dataset, result_dir=args.result_dir,\r\n result_prefix='test.rank.{}.{}'.format(args.algo, model.global_step))\r\n for trunc_level in trunc_levels:\r\n ndcg_version1, ndcg_version2 = ndcgs_version1[trunc_level], ndcgs_version2[trunc_level]\r\n logger.info(\"NDCG@{}: {}, {}\".format(trunc_level, ndcg_version1, ndcg_version2))\r\n logger.info('Done with model testing!')\r\n\r\ndef train(args):\r\n logger = logging.getLogger(\"CACM\")\r\n logger.info('Checking the data files...')\r\n for data_path in args.train_dirs + args.dev_dirs + args.test_dirs + args.label_dirs:\r\n assert os.path.exists(data_path), '{} file does not exist.'.format(data_path)\r\n dataset = Dataset(args, train_dirs=args.train_dirs, dev_dirs=args.dev_dirs, test_dirs=args.test_dirs, label_dirs=args.label_dirs)\r\n logger.info('Initialize the model...')\r\n model = Model(args, len(dataset.qid_nid), len(dataset.uid_nid), len(dataset.vtype_vid))\r\n logger.info('model.global_step: {}'.format(model.global_step))\r\n if args.load_model > -1:\r\n logger.info('Restoring the model...')\r\n model.load_model(model_dir=args.model_dir, model_prefix=args.algo, global_step=args.load_model)\r\n logger.info('Training the model...')\r\n model.train(dataset)\r\n logger.info('Done with model training!')\r\n\r\ndef run():\r\n args = parse_args()\r\n assert args.batch_size % args.gpu_num == 0\r\n assert args.hidden_size % 2 == 0\r\n logger = logging.getLogger(\"CACM\")\r\n logger.setLevel(logging.INFO)\r\n formatter = logging.Formatter('%(asctime)s - %(message)s')\r\n check_path(args.model_dir)\r\n check_path(args.result_dir)\r\n check_path(args.summary_dir)\r\n if args.log_dir:\r\n check_path(args.log_dir)\r\n file_handler = logging.FileHandler(os.path.join(args.log_dir, time.strftime('%Y-%m-%d-%H:%M:%S',time.localtime(time.time())) + '.txt'))\r\n file_handler.setLevel(logging.INFO)\r\n file_handler.setFormatter(formatter)\r\n logger.addHandler(file_handler)\r\n else:\r\n console_handler = logging.StreamHandler()\r\n console_handler.setLevel(logging.INFO)\r\n console_handler.setFormatter(formatter)\r\n logger.addHandler(console_handler)\r\n\r\n logger.info('Running with args : {}'.format(args))\r\n\r\n logger.info('Checking the directories...')\r\n for dir_path in [args.model_dir, args.result_dir, args.summary_dir]:\r\n if not os.path.exists(dir_path):\r\n os.makedirs(dir_path)\r\n if args.train:\r\n train(args)\r\n if args.test:\r\n test(args)\r\n if args.rank:\r\n rank(args)\r\n logger.info('run done.')\r\n\r\n\r\nif __name__ == '__main__':\r\n run()\r\n","repo_name":"xuanyuan14/CACM","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":11063,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"77"}
+{"seq_id":"3745697920","text":"import numpy as np\nimport time\n\nEPSILON_ABSOLUTE = 1e-14\nEPSILON_RELATIVE = 1e-12\n\n\ndef create_simplex(point, func, c):\n simplex = [(point, func(point))]\n for i in range(len(point)):\n new_point = point.copy()\n new_point[i] +=c\n simplex.append((new_point, func(new_point)))\n\n simplex.sort(key=lambda x_f_pair: x_f_pair[1])\n return simplex\n\n\ndef stopping_criteria(f_new, f_old):\n return abs(f_new - f_old) < EPSILON_ABSOLUTE + EPSILON_RELATIVE * abs(f_old)\n\n\ndef reflection(x_b, x_h, r=1):\n return x_b + r * (x_b - x_h)\n\n\ndef expansion(x_r, x_b, e=1):\n return x_r + e * (x_r - x_b)\n\n\ndef contraction(x_b, x_h, c=0.5):\n return x_b + c * (x_h - x_b)\n\n\ndef scale(x, x_l, s=0.5):\n return x_l + s * (x - x_l)\n\n\ndef nelder_mead(func, initial_point, c=1, step_reduction=0.9, time_constraint=15):\n current_point = np.asarray(initial_point)\n x_f_min = current_point, func(current_point)\n\n iteration_count = 0\n simplex = create_simplex(current_point, func, c)\n start = time.time()\n\n while True:\n if time.time() - start >= time_constraint:\n print(\"Warning: time expired.\")\n return x_f_min\n iteration_count += 1\n simplex.sort(key=lambda x_f_pair: x_f_pair[1])\n x_f_h = simplex[-1]\n x_f_s = simplex[-2]\n x_f_l = simplex[0]\n if x_f_l[1] < x_f_min[1]:\n x_f_min = x_f_l\n if stopping_criteria(x_f_h[1], x_f_l[1]):\n if iteration_count >= 1 and stopping_criteria(x_f_min[1], x_f_l[1]):\n return x_f_min\n x_f_min = x_f_l\n c *= step_reduction\n simplex = create_simplex(x_f_l[0], func, c)\n continue\n\n x_b = 1.0 / len(simplex[:-1]) * sum(list(map(lambda x: x[0], simplex[:-1])))\n\n x_h = np.asarray(x_f_h[0], float)\n x_r = reflection(x_b, x_h)\n\n x_f_r = x_r, func(x_r)\n\n if x_f_r[1] >= x_f_l[1]:\n if x_f_r[1] <= x_f_h[1]:\n x_f_h = x_f_r\n if x_f_r[1] <= x_f_s[1]:\n simplex = [x_f_l, x_f_s, x_f_h]\n continue\n x_c = contraction(x_b, x_f_h[0])\n x_f_c = x_c, func(x_c)\n if x_f_c[1] <= x_f_h[1]:\n x_f_h = x_f_c\n x_l = scale(x_f_l[0], x_f_l[0])\n x_s = scale(x_f_s[0], x_f_l[0])\n x_h = scale(x_f_h[0], x_f_l[0])\n\n x_f_l = x_l, func(x_l)\n x_f_s = x_s, func(x_s)\n x_f_h = x_h, func(x_h)\n else:\n x_e = expansion(x_r, x_b)\n x_f_e = (x_e, func(x_e))\n\n if x_f_e[1] >= x_f_l[1]:\n x_f_h = x_f_e\n else:\n x_f_h = x_f_r\n\n simplex = [x_f_l, x_f_s, x_f_h]\n\n\nif __name__ == \"__main__\":\n #nm_test_function = lambda x: x[0] + x[1]\n nm_test_function_2 = lambda x: x[0] ** 2 + 2 * x[1] ** 2 + 2 * x[0] * x[1]\n #print(nelder_mead(nm_test_function, (0, 1)))\n print(nelder_mead(nm_test_function_2, (0, 1)))","repo_name":"matt-dees/optimization-algs","sub_path":"HW3/nelder_mead.py","file_name":"nelder_mead.py","file_ext":"py","file_size_in_byte":2991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"30490686719","text":"#!/usr/bin/env python\n\"\"\"\nPackage metadata for blockstore.\n\"\"\"\nimport os\nimport re\nimport sys\n\nfrom setuptools import find_packages, setup\n\n\ndef get_version(*file_paths):\n \"\"\"\n Extract the version string from the file.\n\n Input:\n - file_paths: relative path fragments to file with\n version string\n \"\"\"\n filename = os.path.join(os.path.dirname(__file__), *file_paths)\n version_file = open(filename).read()\n version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\",\n version_file, re.M)\n if version_match:\n return version_match.group(1)\n raise RuntimeError('Unable to find version string.')\n\n\ndef load_requirements(*requirements_paths):\n \"\"\"\n Load all requirements from the specified requirements files.\n\n Returns:\n list: Requirements file relative path strings\n \"\"\"\n requirements = set()\n for path in requirements_paths:\n requirements.update(\n line.split('#')[0].strip() for line in open(path).readlines()\n if is_requirement(line.strip())\n )\n return list(requirements)\n\n\ndef is_requirement(line):\n \"\"\"\n Return True if the requirement line is a package requirement.\n\n Returns:\n bool: True if the line is not blank, a comment, a URL, or\n an included file\n \"\"\"\n return line and not line.startswith(('-r', '#', '-e', 'git+', '-c'))\n\n\nVERSION = get_version('blockstore', '__init__.py')\n\nif sys.argv[-1] == 'tag':\n print(\"Tagging the version on github:\")\n os.system(\"git tag -a %s -m 'version %s'\" % (VERSION, VERSION))\n os.system(\"git push --tags\")\n sys.exit()\n\nREADME = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()\nCHANGELOG = open(os.path.join(os.path.dirname(__file__), 'CHANGELOG.rst')).read()\n\nsetup(\n name='openedx-blockstore',\n version=VERSION,\n description=\"\"\"Blockstore is a storage system for learning content in Open edX.\"\"\",\n long_description=README + '\\n\\n' + CHANGELOG,\n url='https://github.com/openedx/blockstore',\n packages=find_packages(include=[\"blockstore\", \"blockstore.*\"], exclude=[\"*tests\"]),\n include_package_data=True,\n install_requires=load_requirements('requirements/base.in'),\n python_requires=\">=3.8\",\n license=\"AGPL 3.0\",\n zip_safe=False,\n keywords='Python edx',\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Framework :: Django',\n 'Framework :: Django :: 3.2',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.8',\n ],\n)\n","repo_name":"openedx/blockstore","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2757,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"77"}
+{"seq_id":"40145820215","text":"import warnings\nimport os, contextlib, sys\nimport glob\n\nimport numpy as np\nimport pandas as pd\nimport pylab\n\nimport pyspeckit\nimport json\nimport csv\n\n\nfrom astropy.io import ascii, fits\nfrom astropy.table import Table\nfrom EQW import EQW\nfrom Restframe import Restframe\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib.colors import LogNorm, ListedColormap\nimport seaborn as sns\n\nfrom scipy.stats import norm, binned_statistic\nfrom scipy.optimize import least_squares, curve_fit, nnls\nfrom scipy.interpolate import griddata\nfrom datetime import datetime\nfrom extinction import fm07, apply\n\nfrom sklearn.linear_model import Lasso\n\nimport warnings\nimport os, contextlib, sys\nimport glob\n\nimport numpy as np\nimport pandas as pd\nimport pylab\n\nimport pyspeckit\nimport json\nimport csv\n\n\nfrom astropy.io import ascii, fits\nfrom astropy.table import Table\nfrom EQW import EQW\nfrom Restframe import Restframe\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib.colors import LogNorm, ListedColormap\nimport seaborn as sns\n\nfrom scipy.stats import norm, binned_statistic\nfrom scipy.optimize import least_squares, curve_fit, nnls\nfrom scipy.interpolate import griddata\nfrom datetime import datetime\nfrom extinction import fm07, apply\n\nfrom sklearn.linear_model import Lasso\n\n\n\n# Setting the frequency of the ASTROWAKEUP sound\n\nduration = 1 \nfreq = 440 \n\n# Sets the directory to the current directory\n\nos.chdir(sys.path[0])\n\n\n# Setting the frequency of the ASTROWAKEUP sound\n\nduration = 1 \nfreq = 440 \n\n# Sets the directory to the current directory\n\nos.chdir(sys.path[0])\n\ndef CE(wave, flux, err, pltname):\n\n # A function to smooth the fluxes from noise. Written by Kasper Heinz\n\n def smooth(y, box_pts):\n box = np.ones(box_pts)/box_pts\n y_smooth = np.convolve(y, box, mode='same')\n return y_smooth\n\n # A function to determine the model quasar. Based on equation 1 ...\n # in Fitzpatrick Massa and a script written by Kasper Heinz\n\n def drude(x, x0, gam):\n return (x**2.)/(((x**2. - x0**2.)**2.) + (x**2.)*(gam**2))\n\n def extinction_curve(wl_mod):\n x = 1/(1e-4 * wl_mod)\n k = np.zeros_like(wl_mod)\n D = drude(x, x0, gam)\n mask = (x <= c5)\n k[mask] = c1 + c2 * x[mask] + c3 * D[mask]\n k[~mask] = c1 + c2 * x[~mask] + c3 * D[~mask] + c4*((x[~mask] - c5)**2.)\n return -0.4*(k + rv)\n\n def extinction_absorption(wl_mod, ebv):\n k = extinction_curve(wl_mod)\n return ebv*k \n\n # The Voigt-Hjerting profile based on the numerical approximation by Garcia\n\n def H(a,x):\n P = x**2\n H0 = np.exp(-x**2)\n Q = 1.5/x**2\n return H0 - a / np.sqrt(np.pi) /\\\n P * ( H0 ** 2 * (4. * P**2 + 7. * P + 4. + Q) - Q - 1.0 )\n\n def addAbs(wl_mod, t, integer):\n C_a = np.sqrt(np.pi) * e**2 * f * lamb * 1E-8 / m_e / c / broad\n a = lamb * 1.E-8 * gamma / (4.*np.pi * broad)\n dl_D = broad/c * lamb\n x = (wl_mod/(z_abs[integer]+1.0) - lamb)/dl_D+0.01\n\n # Optical depth\n tau = C_a * t * H(a,x)\n return np.exp(-tau)\n # Setting the constants as given by Kasper Heinz\n\n c1 = -4.959\n c2 = 2.264\n c3 = 0.389\n c4 = 0.461\n c5 = 5.9\n gam = 1.\n rv = 2.74\n x0 = 4.6\n m_e = 9.1095e-28\n e = 4.8032e-10\n c = 2.998e10\n lamb = 1215.67\n f = 0.416\n gamma = 6.265e8\n broad = 1\n\n CIV = 1549\n CIII = 1900\n MgII = 2799 \n SIV = 1402\n\n\n z_qso = float(input('Insert the redshift of the quasar: '))\n n_abs = int(input('Insert the number of DLAs: '))\n z_abs = list()\n for number in range(n_abs):\n z_abs.append(float(input(f'Insert the redshift of DLA {number+1}: ')))\n\n\n # Loading the composite QSO model\n\n model_data = np.genfromtxt(\"compoM.data\")\n model_dict = {\"MODwave\": model_data[:,0]*(1+z_qso), \"MODflux\": model_data[:,1]}\n\n # Preparing the loaded data\n total_wave = wave.copy()\n total_flux = flux.copy()\n\n model_wave = model_dict[\"MODwave\"]\n model_flux = model_dict[\"MODflux\"]\n\n\n fit_wave = griddata(model_wave, model_wave, total_wave, fill_value = 0)\n fit_flux = griddata(model_wave, model_flux, total_wave, fill_value=0)\n\n\n # Removing the noisy flux\n selec_wave = (fit_wave !=0) & (fit_flux > 0)\n\n total_wave = total_wave[selec_wave]\n total_flux = total_flux [selec_wave]\n fit_flux = fit_flux[selec_wave]\n fit_wave = fit_wave[selec_wave]\n total_error = err[selec_wave]\n\n selec_t_flux = total_flux > 0\n\n total_wave = total_wave[selec_t_flux]\n fit_wave = fit_wave[selec_t_flux] \n fit_flux = fit_flux[selec_t_flux]\n total_flux = total_flux[selec_t_flux]\n total_error = total_error[selec_t_flux]\n\n ratio = total_flux/fit_flux\n\n\n\n\n # An area with the Lyman alpha absorbtion line\n Lya_abs_min = list()\n Ly_abs_max = list()\n\n for dla in range(len(z_abs)):\n Lya_abs_min.append((1+z_abs[dla]) * lamb - 50)\n Ly_abs_max.append((1+z_abs[dla]) * lamb +50)\n\n # An area, typically dominated by the continuum\n\n x_CIV = (1+z_qso) * CIV -100\n x_CIII = (1+z_qso) * CIII\n x_MgII = (1+z_qso) * MgII -100\n x_SIV = (1+z_qso) * SIV +100\n print(x_SIV, x_MgII)\n # Remove telluric lines\n\n tel_dict = {\n 'A' : [7600, 7630],\n 'B' : [6860, 6890],\n 'C' : [7170, 7350],\n 'D' : [5450, 5650],\n 'E' : [10000, 10500],\n 'F' : [12600, 12800],\n 'G': [13500, 14500],\n 'H': [18000, 19500],\n }\n\n #Selecting wanted area\n\n\n wanted = np.ones(len(fit_wave), dtype = bool)\n wanted[np.argwhere((fit_wave > x_MgII) | (fit_wave < x_SIV))] = False\n for k in tel_dict.keys():\n wanted[np.argwhere((tel_dict[f'{k}'][0] < fit_wave) | (np.argwhere(tel_dict[f'{k}'][1]) > fit_wave))] = False\n for m in range(len(z_abs)):\n wanted[np.argwhere((Lya_abs_min[m] < fit_wave) & (Ly_abs_max[m] > fit_wave))] = True\n wanted[np.argwhere(((1+z_qso)*lamb -50 < wave) & ((1+z_qso)*lamb + 50 > wave))] = True\n\n flux_for_fit = total_flux.copy()*10**(17)\n\n\n\n # Making it possible to fit up to three DLAs\n if len(z_abs) == 1:\n def fit_func(x, e, n: list):\n return fit_flux[wanted] * 10**(extinction_absorption(x,e)) * addAbs(x,n,0)\n popt, pcov = curve_fit(fit_func, fit_wave[wanted], flux_for_fit[wanted],sigma=total_error[wanted], bounds= (np.array([0,1e19]),np.array([3,3e21])), check_finite= False)\n elif len(z_abs) == 2:\n def fit_func(x, e, n1, n2):\n return fit_flux[wanted] * 10**(extinction_absorption(x,e)) * addAbs(x,n1,0) * addAbs(x,n2,1)\n popt, pcov = curve_fit(fit_func, fit_wave[wanted], flux_for_fit[wanted],sigma=total_error[wanted], bounds= (np.array([0,1e19, 1e19]),np.array([3,3e21, 3e21])), check_finite= False)\n elif len(z_abs) == 3:\n def fit_func(x, e, n1, n2, n3):\n return fit_flux[wanted] * 10**(extinction_absorption(x,e)) * addAbs(x,n1,0) * addAbs(x,n2,1) * addAbs(x,n3,2)\n popt, pcov = curve_fit(fit_func, fit_wave[wanted], flux_for_fit[wanted],sigma=total_error[wanted], bounds= (np.array([0,1e19, 1e19, 1e19]),np.array([3,3e21, 3e21, 3e21])), check_finite= False)\n\n\n perr = np.sqrt(np.diag(pcov))\n\n # Saving the constants from the fit\n ebv = popt[0]\n nion = list()\n for n in range(len(z_abs)):\n nion.append(popt[n+1] ) \n\n # Creating intervals around the Ly-alpha abs. lines\n xmin = list()\n xmax = list()\n for x in range(len(z_abs)):\n xmin.append((1+z_abs[x]) * lamb - 5)\n xmax.append((1+z_abs[x]) * lamb + 5)\n\n ext_comp = 10**(extinction_absorption(model_dict[\"MODwave\"], [ebv]))\n dla_mod = 1\n\n for another in range(len(z_abs)):\n dla_mod = dla_mod * addAbs(model_dict[\"MODwave\"], np.array([nion[another]], dtype=np.float64), another)\n\n \n # Adding the DLAs to the model\n\n red_mod = model_dict[\"MODflux\"] * ext_comp * dla_mod\n\n\n filters = ['UVB', 'VIS', 'NIR']\n\n # Creating plot\n figure = plt.figure(figsize = (10,10))\n axs = list()\n\n\n \n figure.suptitle(f'{pltname}')\n\n axs.append(\n figure.add_subplot(2, 1, 1, )\n )\n axs[0].plot(wave, flux, 'k-', lw=1)\n axs[0].plot(model_dict[\"MODwave\"],model_dict[\"MODflux\"]*3e-17,color= 'tab:blue', lw=0.5, label = f'E(B-V)=0')\n axs[0].plot(model_dict[\"MODwave\"],smooth(red_mod*3e-17,2),color='tab:red', lw=1, label = f'E(B-V)={ebv}')\n\n\n axs[0].set_xscale('log')\n axs[0].axhline(0.0,color='k',linestyle='--')\n\n\n # Set limits\n\n axs[0].set_ylim(-0.3e-17,1.75e-16)\n axs[0].set_xlim(3200,22200)\n\n # Insert the zero value of the flux\n\n axs[0].axhline(0.0,color='k',linestyle='--')\n\n # Mask bad regions of spectra\n\n for j in tel_dict.keys():\n axs[0].axvspan(float(tel_dict[f\"{j}\"][0]) , tel_dict[f\"{j}\"][1] , color=\"grey\", alpha = 0.3)\n\n # Labels\n\n axs[0].set_xlabel(r\"Observed wavelength [$\\mathrm{\\AA}$]\",fontsize=12)\n axs[0].set_ylabel(r'Flux [$\\mathrm{erg}\\,\\mathrm{s}^{-1}\\,\\mathrm{cm}^{-1}\\,\\mathrm{\\AA}^{-1}$]',fontsize=12)\n\n # Create a small subplot for the Lyman alpha absorption line from the DLA\n for y in np.arange(1,len(z_abs)+1,step = 1):\n axs.append(\n figure.add_subplot(2, len(z_abs), len(z_abs) + y)\n )\n axs[y].plot(wave,flux, 'k-', lw=1)\n axs[y].plot(model_dict[\"MODwave\"], smooth(red_mod*1e-17,2),color='tab:red', lw=1)\n axs[y].set_xbound( lower = xmin[y-1]-90, upper = xmax[y-1]+90)\n \n plot_flux = flux.copy()\n plot_flux = plot_flux[ (wave > xmin[y-1]-100) & (xmax[y-1]+100 > wave)]\n axs[y].set_ybound([0,np.amax(plot_flux)])\n # Save the figure as a pdf\n\n\n time_signature = datetime.now().strftime(\"%m%d-%H%M\")\n\n plt.savefig(f'{pltname}/{pltname}_{time_signature}.pdf')\n\n print(f'The extinction is {ebv} +/- {perr[0]} and the column density of hydrogen is {nion} +/- {perr[1]}')\n\n\n plt.show()","repo_name":"svejlgaard/pyzar","sub_path":"scripts/ColumnExtinction.py","file_name":"ColumnExtinction.py","file_ext":"py","file_size_in_byte":9850,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"14251264318","text":"#!/usr/bin/python3\n\"\"\"488#0 - Minimum Operations\"\"\"\n\n\ndef minOperations(n):\n \"\"\"In a text file, there is a single character 'H'.\n Your text editor can execute only two operations in this file:\n 'Copy All' and 'Paste'.\n Given a number n, write a method that calculates the fewest number\n of operations needed to result in exactly n 'H' characters in the file\"\"\"\n pichu, div = 0, 2\n while isinstance(n, int) and n > 1:\n while n % div:\n div += 1\n pichu += div\n n = int(n / div)\n return pichu\n","repo_name":"coding-max/holbertonschool-interview","sub_path":"0x03-minimum_operations/0-minoperations.py","file_name":"0-minoperations.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"10728709270","text":"import re\n\ntime_players_dict = dict()\nwith open('../ddnet-stats/race.csv', 'r', encoding='latin-1') as f:\n next(f) # skipping header\n for line in f:\n other_info = (re.findall(',\".*\",', line))[0].split(',')\n time = float(other_info[-3])\n nick = ','.join(other_info[1:-3])\n if nick not in time_players_dict.keys():\n time_players_dict[nick] = time\n else:\n time_players_dict[nick] += time\n\nsort_d = sorted(time_players_dict.items(), key=lambda x: x[1], reverse=True)\n\nfor rank, (player, time) in enumerate(sort_d[0:15]):\n print(rank + 1, player, round(time/3600, 2)) # in hours\n\nwith open('../output/sum_time_for_all.txt', 'w', encoding='latin-1') as f:\n f.write(\"Rank. Player: TotalTime(Hours)\\n\")\n for rank, (player, time) in enumerate(sort_d):\n f.write('%d. %s: %s\\n' % (rank + 1, player, round(time/3600, 2)))\n","repo_name":"ExP98/Teeworlds-DDNet-Statistics","sub_path":"total_time/summary_time_for_players.py","file_name":"summary_time_for_players.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"6381069328","text":"import os\nimport threeProjs\nimport kitty\n\nfrom flask import Flask\nfrom flask import render_template\nfrom flask import send_from_directory\n\napp = Flask(__name__)\nid = 774437\n\n@app.route(\"/favicon.ico\")\ndef favicon():\n return send_from_directory(os.path.join(app.root_path, 'static'),\n 'favicon.ico', mimetype='image/vnd.microsoft.icon')\n\n@app.route(\"/googlef34ca2b18ef9d5d0.html\")\ndef googleVerificationPage():\n return render_template('googlef34ca2b18ef9d5d0.html')\n\n@app.route(\"/\")\ndef hello():\n l = threeProjs.parse()\n img0 = l[0]['imageURL']\n img1 = l[1]['imageURL']\n img2 = l[2]['imageURL']\n url0 = l[0]['proposalURL']\n url1 = l[1]['proposalURL']\n url2 = l[2]['proposalURL']\n title0 = l[0]['title']\n title1 = l[1]['title']\n title2 = l[2]['title']\n\n kittyurl = kitty.getRandom()\n return render_template('index.html', title=\"Kitties for Kiddies!\", img0=img0, img1=img1, img2=img2,\n url0=url0, url1=url1, url2=url2,\n title0=title0, title1=title1, title2=title2,\n desc0 = l[0]['shortDescription'], desc1=l[1]['shortDescription'],\n desc2 = l[2]['shortDescription'],\n kittyURL = kittyurl)\n\nif __name__ == \"__main__\":\n port = int(os.environ.get(\"PORT\", 5000))\n app.run(host='0.0.0.0', port=port, debug=True)\n","repo_name":"dbieber/gamesfordonorschoose","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"444941536","text":"# SELECTION SORT\nn=int(input())\narr = []\n\nfor i in range(n):\n t = int( input())\n arr.append(t)\n\ndef selection_sort(arr):\n j = 0\n for j in range( len(arr)):\n iMax, Max = j, arr[j]\n for i, val in enumerate(arr[j:]):\n if Max > val:\n iMax, Max = i+j, val\n arr[j], arr[iMax] = arr[iMax], arr[j]\n\n\nselection_sort(arr)\nprint(arr)","repo_name":"vinmaxx99/ds-algo","sub_path":"Selection_Sort.py","file_name":"Selection_Sort.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"18532393885","text":"import os\n\nfrom loguru import logger\n\n\nclass Rclone:\n def move(self, source_path: str, destination_path: str) -> None:\n args = [\n \"gclone\",\n \"move\",\n \"-P\",\n \"--no-traverse\",\n \"--fast-list\",\n \"--max-backlog=999999\",\n \"--drive-chunk-size=512M\",\n \"--transfers=4\",\n \"--checkers=16\",\n \"--buffer-size=75M\",\n \"--exclude\",\n \"'_UNPACK_**'\",\n \"--ignore-existing\",\n source_path,\n destination_path,\n ]\n logger.debug(f\"Move operation: {' '.join(args)}\")\n os.system(\" \".join(args))\n\n def move_server_side(self, source_path: str, destination_path: str) -> None:\n args = [\n \"gclone\",\n \"move\",\n source_path,\n destination_path,\n \"-P\",\n \"--drive-server-side-across-configs\",\n \"--no-traverse\",\n \"--delete-empty-src-dirs\",\n ]\n logger.debug(f\"Move server side operation: {' '.join(args)}\")\n os.system(\" \".join(args))\n","repo_name":"Snaacky/cloudsync","sub_path":"cloudsync/rclone.py","file_name":"rclone.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"29115526434","text":"import sys\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\nimport cv2\r\nimport datetime\r\nimport numpy as np\r\n\r\nnow = datetime.datetime.now()\r\ndirname = 'test_{0:%Y%m%d}'.format(now)\r\n\r\nclass QtCapture(QtWidgets.QWidget):\r\n def __init__(self, *args):\r\n super(QtWidgets.QWidget, self).__init__()\r\n\r\n self.video_frame = QtWidgets.QLabel()\r\n lay = QtWidgets.QVBoxLayout()\r\n lay.setContentsMargins(0,0,0,0)\r\n lay.addWidget(self.video_frame)\r\n self.setLayout(lay)\r\n\r\n self.capture = None\r\n self.cap = cv2.VideoCapture('sample.mp4')\r\n \r\n self.fps = self.cap.get(cv2.CAP_PROP_FPS) \r\n self.video_len_sec = self.cap.get(cv2.CAP_PROP_FRAME_COUNT) // self.fps\r\n self.setFPS(1)\r\n \r\n self.start()\r\n \r\n # My webcam yields frames in BGR format\r\n# frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\r\n# self.frame = frame\r\n# self.img = QtGui.QImage(frame, frame.shape[1], frame.shape[0], QtGui.QImage.Format_RGB888)\r\n# pix = QtGui.QPixmap.fromImage(self.img)\r\n# self.video_frame.setPixmap(pix)\r\n\r\n\r\n # ------ Modification ------ #\r\n self.isCapturing = False\r\n self.ith_frame = 1\r\n # ------ Modification ------ #\r\n \r\n\r\n self.begin = QtCore.QPoint()\r\n self.end = QtCore.QPoint()\r\n \r\n self.setWindowTitle('Control Panel')\r\n self.setGeometry(100,100,200,200)\r\n self.show()\r\n \r\n\r\n def optical_flow(self):\r\n\r\n ret, frame2 = self.cap.read()\r\n next = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)\r\n\r\n flow = cv2.calcOpticalFlowFarneback(self.prev, next, None, 0.5, 3, 15, 3, 5, 1.2, 0)\r\n mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])\r\n\r\n# self.hsv[...,0] = ang*180/np.pi/2\r\n# self.hsv[...,2] = cv2.normalize(mag,None,0,255,cv2.NORM_MINMAX)\r\n# rgb = cv2.cvtColor(self.hsv,cv2.COLOR_HSV2BGR)\r\n \r\n res_show = mag / mag.max()\r\n res_show = np.floor(res_show * 255)\r\n res_show = res_show.astype(np.uint8)\r\n res_show = cv2.applyColorMap(res_show, cv2.COLORMAP_JET)\r\n\r\n alpha = 0.6\r\n return cv2.addWeighted(frame2, alpha, res_show, 1 - alpha, 0)\r\n\r\n\r\n def setFPS(self, fps):\r\n self.fps = fps\r\n\r\n\r\n def nextFrameSlot(self):\r\n ret, frame = self.cap.read() \r\n self.prev = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n self.hsv = np.zeros_like(frame)\r\n self.hsv[..., 1] = 255\r\n frame = self.optical_flow()\r\n# ret, frame = self.cap.read()\r\n # My webcam yields frames in BGR format\r\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\r\n img = QtGui.QImage(frame, frame.shape[1], frame.shape[0], QtGui.QImage.Format_RGB888)\r\n pix = QtGui.QPixmap.fromImage(img)\r\n self.video_frame.setPixmap(pix)\r\n\r\n def start(self):\r\n self.timer = QtCore.QTimer()\r\n self.timer.timeout.connect(self.nextFrameSlot)\r\n self.timer.start(self.video_len_sec)\r\n\r\n def stop(self):\r\n self.timer.stop()\r\n\r\n # ------ Modification ------ #\r\n def capture(self):\r\n if not self.isCapturing:\r\n self.isCapturing = True\r\n else:\r\n self.isCapturing = False\r\n # ------ Modification ------ #\r\n\r\n def deleteLater(self):\r\n self.cap.release()\r\n super(QtWidgets.QWidget, self).deleteLater()\r\n\r\n\r\n\r\n \r\n# def paintEvent(self, event):\r\n# \r\n# qp = QtGui.QPainter()\r\n## br = QtGui.QBrush(QtGui.QColor(100, 10, 10, 40)) \r\n## qp.setBrush(br)\r\n# frame = QtGui.QImage(self.frame, self.frame.shape[1], self.frame.shape[0], QtGui.QImage.Format_RGB888)\r\n# qp.begin(frame)\r\n# pen = QtGui.QPen(Qt.red, 2, Qt.SolidLine)\r\n# qp.setPen(pen) \r\n# \r\n# qp.drawRect(QtCore.QRect(self.begin, self.end))\r\n# \r\n# pix = QtGui.QPixmap.fromImage(frame)\r\n# self.video_frame.setPixmap(pix)\r\n# qp.end()\r\n#\r\n# \r\n# def mousePressEvent(self, event):\r\n# print('test')\r\n# self.begin = event.pos()\r\n# self.end = event.pos()\r\n# self.update()\r\n#\r\n# def mouseMoveEvent(self, event):\r\n# self.end = event.pos()\r\n# self.update()\r\n#\r\n# def mouseReleaseEvent(self, event):\r\n# self.end = event.pos()\r\n# self.update()\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n app = QtWidgets.QApplication(sys.argv)\r\n window = QtCapture()\r\n sys.exit(app.exec_())","repo_name":"tadasi12/dev","sub_path":"prj/movie.py","file_name":"movie.py","file_ext":"py","file_size_in_byte":4507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"9879083526","text":"from lxml import etree\n\ndef extract_file(root, f):\n # iterate thru all the elements\n for element in root.iter():\n # CAR labels\n if element.tag == 'Input' and len(element) > 0 and element[0].tag == 'Concrete':\n f.write(\"\\n \\n\")\n for i in element:\n f.write(f' <{i.tag}> {i.text} {i.tag}>\\n')\n \n f.write(\"\\n\\n\")\n \n # tap/decrement events\n if element.text == 'TapParentQuestionTypeEvent':\n action_element = element.getparent().find('Action')\n f.write(f' <{action_element.tag}> {action_element.text} {action_element.tag}>\\n')\n book_title_element = element.getparent().find('Context')[0].find('Book_Title')\n f.write(f' <{book_title_element.tag}> {book_title_element.text} {book_title_element.tag}>\\n\\n')\n \n # CAR labels with language separation\n if element.tag == 'QuestionTypeCounts':\n f.write(\"\\n\\n\")\n for i in element:\n f.write(f' <{i.tag}>\\n')\n for sub_i in i:\n f.write(f\" <{sub_i.tag}> {sub_i.text} {sub_i.tag}>\\n\")\n f.write(f'{i.tag}>\\n')\n f.write(\" \\n\\n\")\n\n\ndef extract_folder():\n pass\n\n\nif __name__=='__main__': \n xml_path = 'ASU_Data/par 007/h par007 g 08-25-2022T08_09.46.637.xml'\n folder_path = 'ASU_Data/par 007'\n\n tree = etree.parse(xml_path)\n # root for one single xml file\n root = tree.getroot()\n\n\n f = open('ASU_Data/functions/test.xml', \"w\")\n extract_file(root, f)\n f.close()","repo_name":"jordanbarriap/EMBRACE-data-analysis","sub_path":"ASU_Data/functions/extract_parts.py","file_name":"extract_parts.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"25192061903","text":"class Solution:\n def lengthOfLIS(self, nums: List[int]) -> int:\n # prob def : return the length of the longest strictly increasing subsequence.\n # f(i) = the length of the longest strictly increasing subsequence \n n = len(nums)\n dp = [1] * n\n \n for i in range(n): #\n for j in range(i): # 뒤의 숫자를 탐색\n if nums[i] > nums[j]: #뒤의 nums가 앞의 nums보다 클때\n dp[i] = max(dp[j] + 1, dp[i]) #이둘중에 하나는 이길수 없다면 합류하라\n return max(dp)\n\n\n\n # 이문제는 만약 i th 인덱스가 i + 1th(j) 인덱스 보다 작으면 (i < j) 이면 길이를 strictly 늘여서 요소들을 구하라.\n # 중요한건 여기에선 i\n # max를 쓰는 이유는 가장 긴 부분 수열을 구하는 것이므로 쓴다 \n # 여기서 for 루프를 쓴 이유는 가장 낮은 인덱스인 0 부터 n-1 까지 무차별적 대입하기 위해서 이구, 2번째 루프로 이전 인덱스와 비교하기위해 사용\n\n ","repo_name":"JunoLee1/Algorithm","sub_path":"Array/#300. Longest Increasing Subsequence.py","file_name":"#300. Longest Increasing Subsequence.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"19289187663","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport time\nfrom cheapmunk import search_products\nfrom telegrambotservice import setMessageList, sendMessageTo\nfrom usermanagement import getUsers\n\ndef callback_hour(bot, job):\n\t# Wenn Montag\n\tif time.strftime(\"%w\") == 1:\n\t\toutput = {}\n\t\tusers = getUsers()\n\n\t\tfor user_id_str in users.keys():\n\t\t\toutput[user_id_str] = []\n\t\t\tfor prod in users[user_id_str][\"subscribe_list\"]:\n\t\t\t\toutput[user_id_str]+=search_products([prod])\n\n\t\tfor user_id_str in output.keys():\n\t\t\tif output[user_id_str]:\n\t\t\t\tsetMessageList(output[user_id_str])\n\t\t\t\tsendMessageTo(bot, int(user_id_str))\n","repo_name":"Quving/cheapmunk","sub_path":"jobs.py","file_name":"jobs.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"25016474727","text":"arr = [int (line) for line in open('input.txt', 'r').readlines()]\n\n#part one\ninc = 0\ndeepest = 0\nfor i in arr:\n if i > deepest:\n inc += 1\n\n deepest = i\n\nprint(inc - 1)\n\n#part two\ninc = 0\ndeepest = 0\nfor i in range(0, len(arr)-2):\n if arr[i]+arr[i+1]+arr[i+2] > deepest:\n inc += 1\n\n deepest = arr[i]+arr[i+1]+arr[i+2]\n\nprint(inc - 1)\n\n","repo_name":"mbreithecker/adventofcode","sub_path":"2021/d01/day01.py","file_name":"day01.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"5035041818","text":"import re\n\nfrom scrapy import Selector\nfrom scrapy.spiders import Spider\nfrom selenium import webdriver\n\nfrom Consumers12315 import Utils\n\n\nclass Consumers12315_Detail(Spider):\n name = \"Consumers12315_Detail\"\n start_urls = [\n # 可以替换这个 ID,目前是健身服务:410b2db796184a6082317c3032b331d2\n \"http://www.12315.cn/knowledge/knowledgeView?zlcode=410b2db796184a6082317c3032b331d2\",\n # \"http://www.12315.cn/knowledge/knowledgeView?zlcode=9eaa794b186548c186ff5ae9ed5e71ae\",\n ]\n\n def __init__(self):\n super(Consumers12315_Detail, self).__init__()\n # self.start_urls = ['http://buluo.qq.com/p/barindex.html?bid=%s' % bid]\n # self.allowed_domain = 'buluo.qq.com'\n self.driver = webdriver.Chrome(\"/Applications/Google Chrome.app/Contents/MacOS/chromedriver\")\n self.driver.set_page_load_timeout(5) # throw a TimeoutException when thepage load time is more than 5 seconds.\n\n def parse(self, response):\n self.driver.get(response.url)\n # time.sleep(5)\n\n # content = self.driver.page_source\n # print(\"爬取的内容如下:\" + content)\n\n # selector = Selector(text=content)\n selector = Selector(response)\n\n # bigTitle = selector.xpath('//div[@class=\"hd\"]/h2/text()').extract()\n\n\n # self.getBigTitle(selector)\n # self.getSmallTitle(selector)\n\n\n\n myContent = selector.xpath('//div[@class=\"WordSection1\"]/p[@class=\"MsoNormal\"]/span//text()').extract()\n\n i = 0\n isTitle = False\n\n space = \"\\r\\n\\n\\t\"\n space1 = \"\\r\\n\"\n content1 = \"\"\n\n # self.singleText(content1, i, isTitle, myContent, space)\n\n for line in myContent:\n\n if isTitle:\n content1 += \"^^^^^^^^^^^^^^^^^^^^^^^^^^^^\" + space1\n content1 += \"当前的问题是:\" + line + space1\n content1 += \"^^^^^^^^^^^^^^^^^^^^^^^^^^^^\" + space\n\n isTitle = False\n continue\n\n if Utils.matchTitle(line):\n i += 1\n if i > 10:\n break\n\n content1 += \"______________________\" + space1\n content1 += line + \"---------------\" + space1\n content1 += \"______________________\" + space1\n\n isTitle = True\n continue\n\n if ~isTitle:\n l = line\n # for l in line:\n\n if Utils.matchTitle(l):\n # content1 += line\n content1 += space\n continue\n\n content1 += l\n endChar = l[len(l) - 1]\n\n if Utils.isEndChar(endChar):\n content1 += space\n print(content1)\n\n\n\n\n\n\n def singleText(self, content1, i, isTitle, myContent, space):\n for line in myContent:\n\n if isTitle:\n print(\"^^^^^^^^^^^^^^^^^^^^^^^^^^^^\")\n print(\"当前的问题是:\" + line)\n print(\"^^^^^^^^^^^^^^^^^^^^^^^^^^^^\")\n\n isTitle = False\n continue\n\n if Utils.matchTitle(line):\n i += 1\n if i > 1:\n break\n\n print(\"______________________\")\n print(line + \"---------------\")\n print(\"______________________\")\n\n isTitle = True\n continue\n\n if ~isTitle:\n l = line\n # for l in line:\n\n if Utils.matchTitle(l):\n # content1 += line\n content1 += space\n continue\n\n content1 += l\n endChar = l[len(l) - 1]\n\n if Utils.isEndChar(endChar):\n content1 += space\n print(content1)\n\n # 获取当前的大标题\n def getBigTitle(self, selector):\n bigTitle = selector.xpath('//div[@class=\"hd\"]/h2/text()').extract()\n print(\"当前的大标题是: \" + bigTitle[0])\n\n # 获取当前的 所有问题\n def getSmallTitle(self, selector):\n myTile = selector.xpath(\n '//div[@class=\"WordSection1\"]/p[@class=\"MsoNormal\"]/span[@style=\"font-size:16.0pt;font-family:仿宋_GB2312;color:black\"]/text()').extract()\n for t in myTile:\n print(\"___ \" + t)\n print(\"下面只获取标题:\")\n questList = []\n state = False\n for t in myTile:\n if state and not Utils.matchTitle(t) and not t.strip() == \"\":\n print(\"_A_ \" + t)\n questList.append(t)\n state = False\n continue\n\n if Utils.matchTitle(t):\n state = True\n continue\n print(\"当前的总共有:\" + len(questList).__str__())\n\n\n\n\n\n\n\n\n\n","repo_name":"gdky005/ScrapyPro","sub_path":"Consumers12315/Consumers12315/spiders/Consumers12315_Detail.py","file_name":"Consumers12315_Detail.py","file_ext":"py","file_size_in_byte":4835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"33551750651","text":"\nwith open(\"data.txt\") as file:\n school = [int(x) for x in file.readline().split(',')]\n\n#test data\n#school = [int(x) for x in \"3,4,3,1,2\".split(',')]\n\nfor day in range(80):\n for index, fish in enumerate(school):\n school[index] -= 1\n if school[index] < 0:\n school.append(9)\n school[index] = 6\n \n #print(day+1,\":\",school)\n\nprint(len(school))\n","repo_name":"zac112/adventOfCode","sub_path":"code2021/day6/p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"8583638641","text":"import pygame, sys, random, time\n\nfrom scripts.entity.entity import Entity\nfrom scripts.entity.player import Player, PlayerIndicator\nfrom scripts.map.map import Map\nfrom scripts.map.background import Background\nfrom scripts.text.customfont import CustomFont\nfrom networking.network import Network\n\nclass Game:\n def __init__(self): \n # pygame init\n # self.width, self.height = 960, 540\n self.width, self.height = 1920, 1080\n if self.width == 1920:\n self.display = pygame.display.set_mode((self.width, self.height), pygame.FULLSCREEN)\n else:\n self.display = pygame.display.set_mode((self.width, self.height))\n self.window = pygame.Surface((1920, 1080))\n pygame.display.set_caption('Smash')\n self.clock = pygame.time.Clock()\n \n self.run = True\n self.max_fps = 144 \n self.scroll = [0, 0]\n self.dt = 0\n self.frame_length = time.time()\n self.render_offset = [0, 0]\n self.screen_shake = 0\n self.camara_smoothing = 8\n \n # player, enemy, map and font init\n self.map = Map(25, (self.width, self.height), './assets/map/map_data/floating-islands.csv', './assets/map/tilesets/grass-tileset.png')\n self.map.load_csv_data()\n self.map.load_images()\n self.map_output = self.map.draw_map(self.scroll)\n self.tile_list = self.map_output[1]\n self.map_surface = self.map_output[0]\n \n self.player_spawn = self.map_output[2]\n self.enemy_spawn = self.map_output[3]\n \n self.player = Player(self.player_spawn, (25, 50))\n self.player.initialize()\n self.player_inicator = PlayerIndicator()\n self.enemy_pos = self.enemy_spawn\n self.enemy = Player(self.enemy_spawn, (25, 50))\n self.enemy.initialize()\n \n self.font = CustomFont()\n self.font.load_font()\n self.fps_text = self.font.write_text('FPS 60', 1)\n \n self.bg = Background()\n self.bg.move_lines = True\n \n def loop(self):\n \"\"\"game loop\"\"\"\n # self.n = Network('192.168.110.159', 5555)\n while self.run:\n self.frame_length = time.time()\n # pos = (int(self.player.x), int(self.player.y), int(self.n.id))\n # self.enemy_pos = self.n.send(self.n.make_pos(pos))\n # self.enemy_pos = self.n.read_pos(self.enemy_pos)\n if self.enemy_pos:\n self.enemy.x = int(self.enemy_pos[0])\n self.enemy.y = int(self.enemy_pos[1])\n \n if self.player.y > 900:\n self.player.x = self.player_spawn[0]\n self.player.y = self.player_spawn[1]\n self.player.position.x = self.player_spawn[0]\n self.player.position.y = self.player_spawn[1]\n \n self.clock.tick(self.max_fps)\n self.events()\n \n self.scroll[0] += int((self.player.rect.x - self.scroll[0] - (self.width / 2)) / self.camara_smoothing)\n self.scroll[1] += int((self.player.rect.y - self.scroll[1] - (self.height / 2)) / self.camara_smoothing)\n \n self.render()\n self.calculate_dt()\n \n def events(self):\n \"\"\"\"checks if window was quit using the x button\"\"\"\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n self.run = False\n sys.exit(0)\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_l:\n pygame.quit()\n self.run = False\n sys.exit(0)\n \n def render(self):\n self.window.fill((0, 0, 0))\n self.window.blit(self.bg.draw(), ((self.width, self.height), (0 - self.scroll[0], 0 - self.scroll[1])))\n self.window.blit(self.map_surface, (0 - self.scroll[0], 0 - self.scroll[1]))\n self.player.update(self.window, self.dt, self.tile_list, self.scroll)\n self.enemy.draw(self.window, self.scroll)\n self.player_inicator.animations()\n \n self.player_inicator.draw(self.player.rect, self.window, self.scroll)\n \n self.window.blit(self.fps_text, (5, 5))\n \n self.display.blit(self.window, self.render_offset)\n pygame.display.update()\n \n def calculate_dt(self):\n \"\"\"Calculates the deltatime between each frame\"\"\"\n self.dt = time.time() - self.frame_length\n self.dt *= 60\n self.camara_smoothing = 8 - int(self.dt)\n fps = str(int(self.clock.get_fps()))\n self.fps_text = self.font.write_text(f'{fps} FPS', 1)\n \ngame = Game()\ngame.loop()","repo_name":"eliaDr/engine-v0.1","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"37960542285","text":"# -*- coding: utf-8 -*-\n\nimport cv2\nimport numpy as np\n\nfrom skimage.morphology import remove_small_holes, remove_small_objects\nfrom skimage.measure import label, regionprops\n\n\ndef barsReconstruction(bars_part, water_surf, water_lines, logger):\n logger.message(\"bars reconstruction\")\n logger.message(\"...ac reconstruction\")\n act_channel = bars_part | water_surf\n strel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (50, 50))\n act_channel = cv2.morphologyEx(act_channel.astype(\"uint8\"), cv2.MORPH_CLOSE, strel)\n\n logger.message(\"...potential bars extraction\")\n bars = act_channel & ~water_surf.astype(\"bool\")\n bars = bars & ~water_lines.astype(\"bool\")\n del act_channel\n\n logger.message(\"...first cleaning\")\n bars = remove_small_objects(bars.astype(\"bool\"), 800)\n bars = remove_small_holes(bars.astype(\"bool\"), 500)\n\n logger.message(\"...objects selection\")\n logger.message(\"......label potential bars\")\n lbl, nregions = label(bars, connectivity=2, return_num=True)\n\n logger.message(\"......compute props\")\n regions = regionprops(lbl, intensity_image=bars_part)\n\n logger.message(\"......filter objects\")\n bars = np.zeros(bars.shape, dtype=\"bool\")\n for obj in regions:\n px_num = np.count_nonzero(obj.intensity_image)\n if px_num > 50:\n bars = bars | (lbl == obj.label)\n else:\n pass\n\n del lbl\n\n logger.message(\"...final cleaning\")\n strel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (10, 10))\n bars = cv2.morphologyEx(bars.astype(\"uint8\"), cv2.MORPH_OPEN, strel)\n bars = remove_small_objects(bars.astype(\"bool\"), 1000)\n bars = remove_small_holes(bars.astype(\"bool\"), 500)\n bars = bars & ~water_lines\n bars = bars & ~water_surf\n\n return bars\n","repo_name":"EVS-GIS/hmvt-cli","sub_path":"hmvt/algorithms/reconstruction/barsReconstruction.py","file_name":"barsReconstruction.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"35259300782","text":"def setup():\r\n size(800, 600) # 设定画面宽度、高度\r\n colorMode(HSB, 360, 100, 100) # 色相、饱和度、亮度 颜色模型\r\n\r\n\r\ndef draw():\r\n cClouds = color(330, 25, 100) # 云的颜色\r\n cSky = color(220, 50, 50) # 天空的颜色\r\n cFurther = color(230, 25, 90) # 远山的颜色\r\n cCloser = color(210, 70, 10) # 近山的颜色\r\n background(cFurther) # 背景为远山的颜色\r\n drawSky(cSky, cFurther) # 画出天空颜色渐变效果\r\n drawClouds(cClouds) # 画出彩色云朵效果\r\n drawMountains(cFurther, cCloser) # 画出山脉效果\r\n\r\n\r\ndef mousePressed(): # 鼠标按键时\r\n noiseSeed(frameCount * int(random(10))) # 用帧数初始化随机数种子\r\n\r\n\r\ndef drawSky(colSky, colFurther): # 画出天空颜色渐变效果\r\n for y in range(height / 2): # 从顶部开始绘制画面上半部分\r\n strokeWeight(1) # 线粗细为1\r\n # 颜色插值,从天空颜色逐渐变成远山颜色\r\n stroke(lerpColor(colSky, colFurther, float(y) / (height / 2)))\r\n line(0, y, width, y) # 横着的一条线\r\n\r\n\r\ndef drawClouds(colClouds): # 画出彩色云朵效果\r\n noStroke() # 不绘制线条\r\n for y in range(height / 3): # 在上面三分之一部分\r\n for x in range(0, width, 2): # 横向遍历\r\n noiseValue = noise(x * 0.004, y * 0.02) # 柏林噪声\r\n ration = map(y, 0, height / 3, 150, 5) # 越向下、云越透明\r\n fill(colClouds, ration * noiseValue) # 设置透明度\r\n circle(x, y, 2) # 画圆\r\n\r\n\r\ndef drawMountains(colFurther, colCloser): # 画出山脉效果\r\n mountainLayer = 8 # 一共画8层山\r\n for n in range(mountainLayer):\r\n # 每一层山的y坐标的最小值\r\n yMin = map(n, 0, mountainLayer, height * 0.2, height * 0.8)\r\n # 山的颜色由远向近渐变\r\n fill(lerpColor(colFurther, colCloser, \\\r\n float(n + 1) / mountainLayer))\r\n beginShape() # 开始画一些顶点组成的图形\r\n vertex(0, height) # 第一个点在左下角\r\n for x in range(0, width + 1, 2): # 从左到右遍历\r\n # 柏林噪声\r\n noiseValue = noise(x * 0.005, yMin * 0.02) \\\r\n + 0.03 * noise(x * 0.3, yMin * 0.2)\r\n # x横坐标对应的高度,越近的山,高度越向下\r\n yMountain = map(noiseValue, 0, 1, yMin, yMin + height / 2)\r\n vertex(x, yMountain) # 添加这个点\r\n vertex(width, height) # 最后一个点在右下角\r\n endShape(CLOSE) # 结束画一些顶点组成的封闭图形","repo_name":"CookLu/PythonTurtle","sub_path":"turtle_sample/山水画.py","file_name":"山水画.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"22175611465","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nopen, close = np.loadtxt('000001.csv', delimiter=',',\n skiprows=1, usecols=(1, 4), unpack=True)\n# dilimiter -> 界定符\n# open -> 开盘价,close -> 收盘价\nchange = open - close\n# 程序此处可以打开ipython,运行%run 文件名.py ,再用change.shape查看change有多少个数据\n\nyesterday = change[:-1]\ntoday = change[1:]\n\nplt.scatter(yesterday, today)\n\nplt.show()","repo_name":"Orion-Zheng/MyExperiment","sub_path":"python实验/Python实验课代码/matplotlibTest/上证指数.py","file_name":"上证指数.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"73270742647","text":" # coding=utf-8\nimport os.path\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport xgboost as xgb\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report, recall_score\nimport random\n\nscriptpath = os.path.dirname(__file__)\n\nCLASS = 'CLASS'\n\n#Lista de las categorías\ncategories_list = ['RESIDENTIAL', 'INDUSTRIAL', 'PUBLIC', 'OFFICE', 'OTHER', 'RETAIL', 'AGRICULTURE']\n\n# Diccionario para codificar los nombres de las clases\ncategorical_encoder_class = {'RESIDENTIAL': 0,\n 'INDUSTRIAL': 1,\n 'PUBLIC': 2,\n 'OFFICE': 3,\n 'OTHER': 4,\n 'RETAIL': 5,\n 'AGRICULTURE': 6\n}\n\n# Diccionario para codificar las variables no numéricas\ncategorical_encoder_catastral = {'A': -10,\n 'B': -20,\n 'C': -30,\n '\"\"': 50\n}\n\n# Diccionario para decodificar el nombre de las clases\ncategorical_decoder_class = {0: 'RESIDENTIAL',\n 1: 'INDUSTRIAL',\n 2: 'PUBLIC',\n 3: 'OFFICE',\n 4: 'OTHER',\n 5: 'RETAIL',\n 6: 'AGRICULTURE'}\n\n# Diccionario para codificar la variable categorica CADASTRALQUALITYID a un vector one-hot\ncategorical_encoder_catastral_onehot = {\n 'A': [1, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0 ,0],\n 'B': [0, 1, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0 ,0],\n 'C': [0, 0, 1, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0 ,0],\n '1': [0, 0, 0, 1, 0, 0, 0, 0, 0 ,0 ,0 ,0 ,0],\n '2': [0, 0, 0, 0, 1, 0, 0, 0, 0 ,0 ,0 ,0 ,0],\n '3': [0, 0, 0, 0, 0, 1, 0, 0, 0 ,0 ,0 ,0 ,0],\n '4': [0, 0, 0, 0, 0, 0, 1, 0, 0 ,0 ,0 ,0 ,0],\n '5': [0, 0, 0, 0, 0, 0, 0, 1, 0 ,0 ,0 ,0 ,0],\n '6': [0, 0, 0, 0, 0, 0, 0, 0, 1 ,0 ,0 ,0 ,0],\n '7': [0, 0, 0, 0, 0, 0, 0, 0, 0 ,1 ,0 ,0 ,0],\n '8': [0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,1 ,0 ,0],\n '9': [0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,1 ,0],\n '\"\"': [0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0 ,1]\n}\n\ndef get_categorical_encoder_class():\n return categorical_encoder_class\n\ndef get_categorical_encoder_catastral():\n return categorical_encoder_catastral\n\ndef get_categorical_decoder_class():\n return categorical_decoder_class\n\ndef get_categories_list():\n return categories_list\n\ndef get_categorical_encoder_catastral_onehot():\n return categorical_encoder_catastral_onehot\n \ndef get_modelar_data(missing_value = 0, one_hot = True):\n # Variable que contendrá las muestras\n data_list = []\n # with open(r'/home/asicoder/Documentos/Projects/Python/UniversityHack-2020/Data/Modelar_UH2020.txt') as read_file:\n with open(r'Data/Modelar_UH2020.txt') as read_file:\n # La primera linea del documento es el nombre de las variables, no nos interesa\n labels = read_file.readline().split('|')\n # Leemos línea por línea adaptando las muestras al formato deseado (codificar el valor catastral y la clase)\n for line in read_file.readlines():\n # Eliminamos el salto de línea final\n line = line.replace('\\n', '')\n # Separamos por el elemento delimitador\n line = line.split('|')\n # Cambiamos CONTRUCTIONYEAR a la antiguedad del terreno\n line[52] = 2020 - int(line[52])\n if line[53] is '':\n line[53] = missing_value\n line[55] = categorical_encoder_class[line[55]]\n # Codificamos CADASTRALQUALITYID y arreglamos la muestra\n if one_hot:\n data_list.append(line[1:54] + categorical_encoder_catastral_onehot[line[54]] + [line[55]])\n else:\n if line[54] in categorical_encoder_catastral:\n line[54] = categorical_encoder_catastral[line[54]]\n data_list.append(line[1:])\n\n # Finalmente convertimos las muestras preprocesadas a una matriz\n data_list = np.array(data_list).astype('float32')\n # Convertimos dicha matriz a un dataframe de pandas\n #df = pd.DataFrame(data = data_list).rename(columns={np.int64(66):'CLASS'})\n df = pd.DataFrame(data=data_list).rename(columns={66:'CLASS'})\n return df\n\n\ndef get_mod_data_original():\n # Variable que contendrá las muestras\n data = []\n\n with open(r'Data/Modelar_UH2020.txt') as read_file:\n # La primera linea del documento es el nombre de las variables, no nos interesa\n read_file.readline()\n # Leemos línea por línea adaptando las muestras al formato deseado (codificar el valor catastral y la clase)\n for line in read_file.readlines():\n # Eliminamos el salto de línea final\n line = line.replace('\\n', '')\n # Separamos por el elemento delimitador\n line = line.split('|')\n if line[54] in categorical_encoder_catastral:\n line[54] = categorical_encoder_catastral[line[54]]\n if line[54] is 50:\n line[53] = -1\n line[55] = categorical_encoder_class[line[55]]\n # No nos interesa el identificador de la muestra, lo descartamos\n data.append(line[1:])\n\n # Finalmente convertimos las muestras preprocesadas a una matriz\n data = np.array(data).astype('float32')\n df = pd.DataFrame(data=data).rename(columns={54:'CLASS'})\n return df\n\ndef get_modelar_data_ids(missing_value = 0, one_hot = True):\n # Variable que contendrá las muestras\n data_list = []\n # with open(r'/home/asicoder/Documentos/Projects/Python/UniversityHack-2020/Data/Modelar_UH2020.txt') as read_file:\n with open(r'Data/Modelar_UH2020.txt') as read_file:\n # La primera linea del documento es el nombre de las variables, no nos interesa\n labels = read_file.readline().split('|')\n # Leemos línea por línea adaptando las muestras al formato deseado (codificar el valor catastral y la clase)\n for line in read_file.readlines():\n # Eliminamos el salto de línea final\n line = line.replace('\\n', '')\n # Separamos por el elemento delimitador\n line = line.split('|')\n # Cambiamos CONTRUCTIONYEAR a la antiguedad del terreno\n line[52] = 2020 - int(line[52])\n if line[53] is '':\n line[53] = missing_value\n line[55] = categorical_encoder_class[line[55]]\n # Codificamos CADASTRALQUALITYID y arreglamos la muestra\n if one_hot:\n data_list.append(line[:54] + categorical_encoder_catastral_onehot[line[54]] + [line[55]])\n else:\n if line[54] in categorical_encoder_catastral:\n line[54] = categorical_encoder_catastral[line[54]]\n data_list.append(line[1:])\n\n # Finalmente convertimos las muestras preprocesadas a una matriz\n a = np.array(data_list)\n ids = a[:, 0]\n a = np.delete(a, 0, axis=1)\n a = a.astype('float32')\n dfids = pd.DataFrame(data=ids)\n dfa = pd.DataFrame(data=a).rename(columns={66:'CLASS'})\n dfa[0] = dfids\n return dfa\n\n\ndef getX(modelar_df):\n return modelar_df.loc[:, modelar_df.columns!=CLASS]\n\n\ndef getY(modelar_df):\n return modelar_df.loc[:, modelar_df.columns == CLASS]\n\n\ndef reduce_dimension_modelar(modelar_df, num=30):\n if num > 55:\n print('num no mayor a 55')\n else:\n importance_df = pd.read_csv('Importancia de parametros.csv')\n indexes_list = list(importance_df['Index'])\n indexes_list[::-1]\n indexes_quited = []\n i = 0\n j = 0\n while j < num:\n if not 53 <= indexes_list[i] <= 65 and indexes_list[i] != 1:\n indexes_quited.append(indexes_list[i])\n del modelar_df[indexes_list[i]]\n j += 1\n i+=1\n return modelar_df\n\n\ndef reduce_colors(df):\n #Quita los deciles 2,3,4,6,7 y 8 de cada color\n indices_start = [4, 5, 6, 8, 9, 10]\n for i in range(len(indices_start)):\n df.drop([indices_start[i], indices_start[i]+11, indices_start[i]+22, indices_start[i]+33],inplace=True,axis=1)\n return df\n\n\ndef reduce_geometry_average(df):\n avgs = []\n for i in range(df.shape[0]):\n avgs.append((df.loc[i, 48] + df.loc[i, 49] + df.loc[i, 50] + df.loc[i, 51]) / 4)\n del df[48]\n del df[49]\n del df[50]\n del df[51]\n df['GEOM_AVG'] = avgs\n \n return df\n\n\ndef get_estimar_data(missing_value = 0, one_hot = True):\n # Variable que contendrá las muestras a predecir\n data_predict = []\n # with open(r'/home/asicoder/Documentos/Projects/Python/UniversityHack-2020/Data/Estimar_UH2020.txt') as read_file:\n with open(r'Data/Estimar_UH2020.txt') as read_file:\n # La primera linea del documento es el nombre de las variables (al ser un Pandas Dataframe hay que añadirla)\n labels = np.array(read_file.readline())\n # Leemos línea por línea adaptando las muestras al formato deseado (codificar el valos catastral)\n for line in read_file.readlines():\n # Eliminamos el salto de línea final\n line = line.replace('\\n', '')\n # Separamos por el elemento delimitador\n line = line.split('|')\n # Cambiamos CONTRUCTIONYEAR a la antiguedad del terreno\n line[52] = 2020 - int(line[52])\n if line[53] is '':\n line[53] = missing_value\n if one_hot:\n data_predict.append(line[:54] + categorical_encoder_catastral_onehot[line[54]])\n else:\n data_predict.append(line)\n\n # Finalmente convertimos las muestras preprocesadas a una matriz\n data_predict = np.array(data_predict) \n ids = data_predict[:, 0]\n data_predict = np.delete(data_predict, 0, axis=1)\n data_predict = data_predict.astype('float32')\n dfids = pd.DataFrame(data=ids)\n dfa = pd.DataFrame(data=data_predict)\n dfa[0] = dfids\n return dfa\n\ndef get_estimar_ids():\n res = []\n with open(r'Data/Estimar_UH2020.txt') as read_file:\n read_file.readline()\n for sample in read_file.readlines():\n print(sample)\n sample = sample.split('|')\n print(sample)\n res.append(sample[0])\n\n return res","repo_name":"Polaryti/UniversityHack-2020","sub_path":"Fase II/datasets_get.py","file_name":"datasets_get.py","file_ext":"py","file_size_in_byte":10016,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"13727341042","text":"from pulumi import Config, export, get_project, get_stack, Output, ResourceOptions\n\n#import pulumi\nimport pulumi_gcp as gcp\n\n# from pulumi_gcp.config import project, zone, region\n# from pulumi_gcp.container import Cluster, ClusterNodeConfigArgs\n# from pulumi_kubernetes import Provider\n# from pulumi_kubernetes.apps.v1 import Deployment, DeploymentSpecArgs\n# from pulumi_kubernetes.core.v1 import ContainerArgs, PodSpecArgs, PodTemplateSpecArgs, Service, ServicePortArgs, ServiceSpecArgs\n# from pulumi_kubernetes.meta.v1 import LabelSelectorArgs, ObjectMetaArgs\n#from pulumi_random import RandomPassword\n\n\n\ndef test_cloud_run():\n '''Boilerplate from https://www.pulumi.com/registry/packages/gcp/api-docs/cloudrun/service/.\n '''\n # cloudrun_service = gcp.cloudrun.Service(\"default1\",\n # location=\"us-central1\",\n # template=gcp.cloudrun.ServiceTemplateArgs(\n # spec=gcp.cloudrun.ServiceTemplateSpecArgs(\n # containers=[gcp.cloudrun.ServiceTemplateSpecContainerArgs(\n # image=\"us-docker.pkg.dev/cloudrun/container/hello\",\n # )],\n # ),\n # ),\n # traffics=[gcp.cloudrun.ServiceTrafficArgs(\n # latest_revision=True,\n # percent=100,\n # )])\n cloudrun_service_noauth = gcp.cloudrun.Service(\"cloudrun-noauth2\",\n location=\"us-central1\",\n template=gcp.cloudrun.ServiceTemplateArgs(\n spec=gcp.cloudrun.ServiceTemplateSpecArgs(\n containers=[gcp.cloudrun.ServiceTemplateSpecContainerArgs(\n image=\"us-docker.pkg.dev/cloudrun/container/hello\",\n )],\n ),\n ))\n noauth_iam_policy = gcp.organizations.get_iam_policy(bindings=[gcp.organizations.GetIAMPolicyBindingArgs(\n role=\"roles/run.invoker\",\n members=[\"allUsers\"],\n )])\n noauth_iam_policy = gcp.cloudrun.IamPolicy(\"noauthIamPolicy\",\n location=cloudrun_service_noauth.location,\n project=cloudrun_service_noauth.project,\n service=cloudrun_service_noauth.name,\n policy_data=noauth_iam_policy.policy_data)\n export('riccardo_cloudrun_id', cloudrun_service_noauth.id)\n export('riccardo_cloudrun_statuses', cloudrun_service_noauth.statuses)\n ###############################################################################################################\n # ID => locations/us-central1/namespaces/cloud-build-ghent-tests/services/cloudrun-noauth2-d1d722d\n # URL => https://cloudrun-noauth2-d1d722d-om7xcvjybq-uc.a.run.app/\n ###############################################################################################################\n # Note that I cant infer that UC so I need to call gcloud.\n # URL: gcloud --project cloud-build-ghent-tests run services describe cloudrun-noauth2-d1d722d --region us-central1 --format json\n # gcloud --project cloud-build-ghent-tests run services describe cloudrun-noauth2-d1d722d --region us-central1 --format json | jq .status.address.url\n # export UTL\n ###############################################################################################################\n export('riccardo_cloudrun_url', cloudrun_service_noauth.statuses.apply(\n lambda status: status[0].url\n ))\n\ndef main():\n #puts(\"This is WIP to push carlessian apps..\")\n export('riccardo_notes', \"Riccardo was here\")\n export('riccardo_notes2', \"Riccardo was here 2️⃣\")\n test_cloud_run()\n\n","repo_name":"palladius/pulumi","sub_path":"examples/python-gcp-cloudbuild-auto-trigger/lib/setup_palladius_apps.py","file_name":"setup_palladius_apps.py","file_ext":"py","file_size_in_byte":3493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"74211588728","text":"from django.shortcuts import render\n\nfrom app.blog.models import Post\n\n\ndef school_list(request):\n posts = Post.objects.order_by(id=school_list)\n context = {\n 'schools': school_list,\n }\n\n return render(\n request=request,\n context=context,\n )\n\n\ndef school_detail(request, school_id):\n post = Post.objects.get(id=school_id)\n context = {\n 'student': student,\n }\n\n return render(request, 'blog/school_detail.html', context)\n","repo_name":"HyungtaeMoon/stopout","sub_path":"app/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"22556555881","text":"# !/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @author: SaltFish\n# @file: 103二叉树的锯齿形层次遍历.py\n# @date: 2020/07/29\n\"\"\"\n给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。\n\n例如:\n给定二叉树 [3,9,20,null,null,15,7],\n\n 3\n / \\\n 9 20\n / \\\n 15 7\n返回锯齿形层次遍历如下:\n\n[\n [3],\n [20,9],\n [15,7]\n]\n\n\"\"\"\nimport collections\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:\n if not root:\n return []\n queue = collections.deque()\n res, is_reverse = [], False\n queue.append(root)\n while queue:\n length = len(queue)\n temp = []\n for _ in range(length):\n node = queue.popleft()\n temp.append(node.val)\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n if is_reverse:\n temp.reverse()\n res.append(temp)\n is_reverse = not is_reverse\n return res\n","repo_name":"SaItFish/PySundries","sub_path":"algorithm_questions/LeetCode/树/103二叉树的锯齿形层次遍历.py","file_name":"103二叉树的锯齿形层次遍历.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"25427329306","text":"\nfrom __future__ import print_function\nimport re\nimport subprocess\nfrom simlib import output\nimport sys\n\ndef optimize(command):\n print('RUNNING: ' + command)\n output.log('RUNNING: ' + command)\n sim_proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)\n while True:\n try:\n line = sim_proc.stdout.readline()\n except KeyboardInterrupt:\n break \n if not line:\n break\n \n output.log(line, newline=False)\n\n if 'units:'.encode('UTF-8') in line:\n print('.', end='', sep='')\n sys.stdout.flush()\n if line.startswith('Optimized Deck:'.encode('UTF-8')):\n print('')\n line = re.sub('Optimized Deck: ', '', line.decode('UTF-8'))\n line = re.sub('\\n', '', line)\n deck_only = re.sub('.*:', '', line)\n\n return (line, deck_only)\n\ndef climb_command(member, deck, target, params, count):\n command = 'cd .. & tuo ' + '\"' + deck + '\"' + ' \"' + target + '\" -t 32 -o=\"data/' + member + '.txt\" ' + params + ' endgame 1 climb ' + str(count)\n return command\n\ndef reorder_command(member, deck, target, params, count):\n command = 'cd .. & tuo ' + '\"' + deck + '\"' + ' \"' + target + '\" -t 32 -o=\"data/' + member + '.txt\" ' + params + ' endgame 1 reorder ' + str(count)\n return command\n","repo_name":"BreakerFIT/sim-scripts","sub_path":"simlib/opt.py","file_name":"opt.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"42575492888","text":"import info\nimport matplotlib.pyplot as plt\n\n#X2.Peso dos atletas de a cada ano.\n\ndef pegar_dados_para_plotagem():\n genero = info.escolher_genero()\n\n anos = sorted(list(set([ano for (ano,tipo) in info.olimpiadas])))\n\n pesos = list(set([\n (int(line['id']), float(line['weight']), line['year'])\n for line in info.athletes\n if line['sex'] == genero\n and line['weight'] != 'NA' ]))\n\n dados = [ [peso for (_id, peso, ano_registrado) in pesos if ano_registrado == ano ] for ano in anos]\n\n return dados, anos, {'M': 'Masculino', 'F': 'Feminino'}[genero]\n\ndef plotar(dados,anos, genero):\n r = range(1, len(dados)+1)\n\n plt.boxplot(dados)\n plt.xticks(r, anos, rotation = 70)\n plt.title('Basic Plot')\n\n plt.show()\n plt.clf()\n\ndef main():\n plotar(*pegar_dados_para_plotagem())\n","repo_name":"CristianDG/trabalho-final-pi","sub_path":"x2.py","file_name":"x2.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"42265373427","text":"#Coded by Chris Parks\n#November 27, 2020. due December 3, 2020\n#For UNR CS 457\n\nimport sys;\nimport os;\nimport re;\n\nimport language.useful_functions;\n\noperation_sequence = [];\n\n\n#First, read input and turn it into a list to iterate upon\ncreate_set_mode = False;\ntoken_input = [];\nfor std_input in sys.stdin:\n if(std_input[0:2] == '--' or std_input == '\\n'): continue;\n if(std_input.strip().lower() == '.exit'): operation_sequence.append(['.exit']); break;\n \n #Tokenize the input line\n for i in re.split(' |,',std_input):\n i = i.lower();\n i = i.replace('\\t','').replace('\\n','').replace(';','').replace('\\'','');\n if(i[0:2] == '--'):\n language.useful_functions.execute_operation([a for a in token_input if a != '']);\n token_input = [];\n break;\n if(i != '\\n' and i != ''):\n if(not create_set_mode and i.find('(') != -1):\n j = i[i.index('(')+1:]\n i = i[:i.index('(')];\n create_set = [j];\n create_set_mode = True;\n elif(create_set_mode and i.find('(') != -1 and i.find(')') != -1):\n if(i.count(')') == 1):\n create_set.append(i);\n else:\n create_set.append(i[:i.index(')')+1]);\n create_set_mode = False;\n token_input.append(create_set);\n continue;\n elif(create_set_mode and i.find(')') == -1):\n create_set.append(i);\n continue;\n elif(create_set_mode and i.find(')') != -1):\n j = i[:i.index(')')];\n i = i[i.index(')')+1:]\n create_set.append(j);\n create_set_mode = False;\n token_input.append(create_set);\n \n token_input.append(i);\n if(std_input.replace('\\n','')[-1:] == ';'):\n language.useful_functions.execute_operation([a for a in token_input if a != '']);\n token_input = [];\n\n#Parse operation sequence and perform statements\n#for this_operation in operation_sequence:\n# language.useful_functions.execute_operation(this_operation);\n \n ","repo_name":"christopherparks-unr/cs457_pa4","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"29332273189","text":"#Aprobación de créditos\ndef aprobar_credito():\n ingreso = float(input(\"Ingrese su ingreso en pesos: \"))\n ano_nacimiento = int(input(\"Ingrese su año de nacimiento: \"))\n num_hijos = int(input(\"Ingrese el número de hijos que tiene: \"))\n anos_pertenencia = int(input(\"Ingrese los años de pertenencia al banco: \"))\n estado_civil = input(\"Ingrese su estado civil (S para soltero, C para casado): \")\n ubicacion = input(\"Ingrese su ubicación (U para urbano, R para rural): \")\n\n if anos_pertenencia > 10 and num_hijos >= 2:\n return True\n elif estado_civil == \"C\" and num_hijos > 3 and 45 <= (2023 - año_nacimiento) <= 55:\n return True\n elif ingreso > 2500000 and estado_civil == \"S\" and ubicacion == \"U\":\n return True\n elif ingreso > 3500000 and años_pertenencia > 5:\n return True\n elif ubicacion == \"R\" and estado_civil == \"C\" and num_hijos < 2:\n return True\n else:\n return False\n\nif aprobar_credito():\n print(\"APROBADO\")\nelse:\n print(\"RECHAZADO\") ","repo_name":"pabloschwarzenberg/grader","sub_path":"hito1_ej3/hito1_ej3_eb3212bb8ff362920d77ddc9686d0931.py","file_name":"hito1_ej3_eb3212bb8ff362920d77ddc9686d0931.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"8706528714","text":"import os\nfrom flask_autodoc import Autodoc\nfrom app import create_app\nfrom flask_script import Manager, Shell\n\nCOV = None\nif os.environ.get('FLASK_COVERAGE'):\n import coverage\n COV = coverage.coverage(branch=True, include='app/*')\n COV.start()\n\nif os.path.exists('.env'):\n print('Importing environment from .env...')\n for line in open('.env'):\n var = line.strip().split('=')\n if len(var) == 2:\n os.environ[var[0]] = var[1]\n\napp = create_app(os.getenv('FLASK_CONFIG') or 'default')\nauto = Autodoc(app)\n\nfrom app.api_1_0 import api as api_1_0_blueprint\napp.register_blueprint(api_1_0_blueprint, url_prefix='/api/v1')\n\nmanager = Manager(app)\n\ndef make_shell_context():\n return dict(app=app)\n\nmanager.add_command(\"shell\", Shell(make_context=make_shell_context))\n\n@manager.command\ndef deploy():\n \"\"\"Run deployment tasks.\"\"\"\n \nif __name__ == '__main__':\n manager.run()\n","repo_name":"frankjdelgado/wiki-history-extractor-api","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"18166257926","text":"import gsw\nimport numpy as np\nfrom scipy.interpolate import interp1d\nimport logging\n\n_log = logging.getLogger(__name__)\n\n\ndef interp(x, y, xi):\n _gg = np.isfinite(x + y)\n return interp1d(x[_gg], y[_gg], bounds_error=False, fill_value=np.NaN)(xi)\n\n\ndef salinity_pressure_correction(ds):\n \"\"\"correct salinity from pressure lag\"\"\"\n _log.info(\"performing RBR salinity pressure correction\")\n X2 = 1.8e-06\n X3 = -9.472e-10\n X4 = 2.112e-13\n Cmeas = ds['conductivity'].values\n Pmeas = ds['pressure'].values\n ds['conductivity'].values = Cmeas / (1 + X2 * Pmeas + X3 * Pmeas ** 2 + X4 * Pmeas ** 3)\n ds['conductivity'].attrs['comment'] += \"Pressure corrected in post-processing.\"\n ds['salinity'].values = gsw.SP_from_C(ds['conductivity'].values, ds['temperature'].values, Pmeas)\n ds['salinity'].attrs['comment'] += \"Pressure corrected in post-processing.\"\n return ds\n\n\ndef correct_rbr_lag(ds):\n \"\"\"\n Thermal lag from Thermal Inertia of Conductivity Cells: Observations with a Sea-Bird Cell\n Rolf G. Lueck and James J. Picklo https://doi.org/10.1175/1520-0426(1990)007<0756:TIOCCO>2.0.CO;2\n :param data: \n :return: \n \"\"\"\n\n vert_spd = np.gradient(\n -gsw.z_from_p(ds['pressure'].values, ds['latitude'].values),\n ds[\"time\"].values.astype('float')) * 1e9\n spd = np.abs(vert_spd / np.sin(np.deg2rad(ds['pitch'].values)))\n\n spd[spd < 0.01] = 0.01\n spd[spd > 1] = 1\n spd[~np.isfinite(spd)] = 0.01\n\n spd = spd * 100\n\n raw_seconds = ds['time'].values.astype('float') / 1e9\n raw_seconds = raw_seconds - np.nanmin(raw_seconds)\n\n raw_temp = ds['temperature'].values\n\n Fs = np.mean(1 / np.gradient(raw_seconds))\n _log.info('Performing thermal mass correction... Assuming a sampling frequency of ' + str(Fs) + ' Hz.')\n fn = Fs / 2\n\n corr_temp = raw_temp.copy()\n\n # Correct temperature probe's thermal lag to get real temperature\n alpha = 0.05 * spd ** (-0.83)\n tau = 375\n bias_temp = np.full_like(corr_temp, 0)\n a = 4 * fn * alpha * tau / (1 + 4 * fn * tau) # Lueck and Picklo (1990)\n b = 1 - 2 * a / alpha # Lueck and Picklo (1990)\n for sample in np.arange(1, len(bias_temp)):\n bias_temp[sample] = -b[sample] * bias_temp[sample - 1] + a[sample] * (corr_temp[sample] - corr_temp[sample - 1])\n\n corr_temp = interp(raw_seconds, raw_temp, raw_seconds + 0.9)\n\n # Estimate effective temperature of the conductivity measurement (long thermal lag)\n alpha = 0.18 * spd ** (-1.10)\n tau = 179\n bias_long = np.full_like(corr_temp, 0)\n a = 4 * fn * alpha * tau / (1 + 4 * fn * tau) # Lueck and Picklo (1990)\n b = 1 - 2 * a / alpha # Lueck and Picklo (1990)\n for sample in np.arange(1, len(bias_long)):\n bias_long[sample] = -b[sample] * bias_long[sample - 1] + a[sample] * (corr_temp[sample] - corr_temp[sample - 1])\n\n # Estimate effective temperature of the conductivity measurement (short thermal lag)\n alpha = 0.23 * spd ** (-0.82)\n tau = 27.15 * spd ** (-0.58)\n bias_short = np.full_like(corr_temp, 0)\n a = 4 * fn * alpha * tau / (1 + 4 * fn * tau) # Lueck and Picklo (1990)\n b = 1 - 2 * a / alpha # Lueck and Picklo (1990)\n for sample in np.arange(1, len(bias_short)):\n bias_short[sample] = -b[sample] * bias_short[sample - 1] + a[sample] * (\n corr_temp[sample] - corr_temp[sample - 1])\n\n corr_sal = gsw.SP_from_C(ds['conductivity'].values, corr_temp - bias_long - bias_short,\n ds['pressure'].values)\n\n ds['temperature'].values = corr_temp\n ds['salinity'].values = corr_sal\n\n sa = gsw.SA_from_SP(ds['salinity'], ds['pressure'], ds['longitude'], ds['latitude'])\n ct = gsw.CT_from_t(sa, ds['temperature'], ds['pressure'])\n ds['potential_density'].values = 1000 + gsw.density.sigma0(sa, ct)\n ds['density'] = gsw.density.rho(ds.salinity, ds.temperature, ds.pressure)\n rbr_str = (\"Corrected following Thermal lag from Thermal Inertia of Conductivity Cells: Observations with a \"\n \"Sea-Bird Cell Rolf G. Lueck and James J. Picklo\"\n \" https://doi.org/10.1175/1520-0426(1990)007<0756:TIOCCO>2.0.CO;2 as implemented by \"\n \"Dever M., Owens B., Richards C., Wijffels S., Wong A., Shkvorets I., Halverson M., and Jonhson G.\"\n \" (accepted). Static and dynamic performance of the RBRargo3 CTD.\"\n \" Journal of Atmospheric and Oceanic Technology.\")\n ds['temperature'].attrs['comment'] += rbr_str\n ds['salinity'].attrs['comment'] += rbr_str\n return ds\n\n\nif __name__ == '__main__':\n logf = f\"/data/log/new.log\"\n logging.basicConfig(filename=logf,\n filemode='w',\n format='%(asctime)s %(levelname)-8s %(message)s',\n level=logging.INFO,\n datefmt='%Y-%m-%d %H:%M:%S')\n import xarray as xr\n ds = xr.open_dataset(\"/home/callum/Downloads/new/M11/timeseries/mission_timeseries.nc\")\n dsnew = correct_rbr_lag(ds)\n dsnew.to_netcdf(\"/home/callum/Downloads/new/M11/timeseries/mission_timeseries_corrected.nc\")","repo_name":"voto-ocean-knowledge/utility_scripts","sub_path":"post_process_ctd.py","file_name":"post_process_ctd.py","file_ext":"py","file_size_in_byte":5107,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"26651368074","text":"import collections\n\ndef _sort(word):\n return(\"\".join(sorted(word)))\n\ndef groupAnagram(words):\n anagram_dict = collections.defaultdict(list)\n\n for word in words:\n anagram_dict[_sort(word)].append(word)\n\n return([v for sublist in anagram_dict.values() for v in sublist])\n\nif __name__==\"__main__\":\n test_input = ([\"abt\",\"cabe\",\"tab\",\"ebca\",\"t\",\"bat\"],[])\n test_output = ([\"abt\",\"tab\",\"bat\",\"cabe\",\"ebca\",\"t\"],[])\n\n for i,t in enumerate(test_input):\n x = groupAnagram(t)\n print(x)\n if x != test_output[i]:\n print(\"Doesn't match!!\", test_output[i])\n","repo_name":"michlee1337/practice","sub_path":"CTCI/c10_sortAndSearch/groupAnagram.py","file_name":"groupAnagram.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"24330452104","text":"\nclass Plant:\n\tdef __init__(self, plant_dict, x_loc, y_loc):\n\t\tself.name = plant_dict[\"Name\"]\n\t\tself.x_loc = x_loc\n\t\tself.y_loc = y_loc\n\t\tself.harvest_age = plant_dict[\"Harvest_Age\"]\n\t\tself.space_requirement = plant_dict[\"Space_Requirement\"]\n\t\tself.incident_light = 0\n\t\tself.stage_name = plant_dict[\"Filenames\"][0]\n\t\tself.light_requirement = plant_dict[\"Light_Requirement\"]\n\n\tdef plant_grow(self):\n\t\tprint(\"Incident Light:\",self.incident_light)\n\t\t# pass\n\n","repo_name":"oneebhkhan/CS596-Proj","sub_path":"Environment_Files/plant.py","file_name":"plant.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"40087180897","text":"#-*- codeing = utf-8 -*-\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import roc_curve\nfrom tools.data_process import draw_roc_auc,calc_target\n\n'''--------------------------------DecisionTree-------------------------------------'''\ndef test_DecisionTreeClassifier(*data):\n X_train,X_test,y_train,y_test=data\n clf = DecisionTreeClassifier()\n #clf=DecisionTreeClassifier(max_depth=None,min_samples_split=2)\n clf.fit(X_train,y_train)\n\n #.score——>平均准确度\n print(\"Training Score:%f\"%clf.score(X_train,y_train))\n print(\"Testing Score:%f\"%clf.score(X_test,y_test))\n print('---------------------------------------')\n\n # .predict(xtest)——>根据xtest,预测结果\n predict_array = clf.predict(X_test)\n\n # 画ROC图\n predictions_validation = clf.predict_proba(X_test)[:, 1]\n fpr, tpr, _ = roc_curve(y_test, predictions_validation)\n draw_roc_auc(fpr, tpr)\n\n #计算指标并输出\n calc_target(X_train,X_test,y_train,y_test,predict_array,fpr,tpr)\n print('---------------------------------------')","repo_name":"akanepink/malicious-url-detection","sub_path":"models/decision_tree.py","file_name":"decision_tree.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"6369827817","text":"\"\"\" this modulo create a table of the tournament \"\"\"\n\ndef tally(rows: list) -> list:\n \"\"\" receive the matchs and return a table \"\"\"\n header = [f\"{'Team': <31}|{'MP': ^4}|{'W ': >4}|{'D ': >4}|{'L ': >4}|{'P': >3}\"]\n list_of_results = create_list_results(rows)\n dict_of_results = create_dict_of_results(list_of_results)\n table = create_table(dict_of_results)\n return header + table\n\n\ndef compute_match(row: str):\n \"\"\" recive a string with the result and return a list with the each club points \"\"\"\n club_1, club_2, result = row.split(';')\n if result == 'win':\n return (club_1, [1, 1, 0, 0, 3]), (club_2, [1, 0, 0, 1, 0])\n if result == 'loss':\n return (club_1, [1, 0, 0, 1, 0]), (club_2, [1, 1, 0, 0, 3])\n if result == 'draw':\n return (club_1, [1, 0, 1, 0, 1]), (club_2, [1, 0, 1, 0, 1])\n return None\n\ndef create_list_results(rows: list):\n \"\"\" create a list with all matches results \"\"\"\n results = []\n for item in rows:\n club_1, club_2 = compute_match(item)\n results.append(club_1)\n results.append(club_2)\n return results\n\ndef create_dict_of_results(results: list) -> dict:\n \"\"\" with a list of results create a dictionary to compute the results \"\"\"\n table = {}\n for club, statics in results:\n if club in table:\n for index in range(5):\n table[club][index] += statics[index]\n else:\n table[club] = statics\n return table\n\ndef create_table(table: dict) -> list:\n \"\"\" create a list of string that implement the table \"\"\"\n list_2_sort = lambda table: [[item[0], item[1][4]] for item in list(table.items())]\n clubs = list_2_sort(table)\n sorted_clubs = sort_list(clubs)\n table_list = []\n for item in sorted_clubs:\n played, win, draw, lost, points = table[item]\n table_list.append(\n f\"{item: <31}|{played: >3} |{win: >3} |{draw: >3} |{lost: >3} |{points: >3}\"\n )\n return table_list\n\ndef sort_list(table_list: list) -> list:\n \"\"\" sort the clubs with the points \"\"\"\n work_list = table_list[:]\n for index, item in enumerate(work_list):\n current_element = item\n while index > 0 and work_list[index - 1][1] < current_element[1]:\n work_list[index] = work_list[index - 1]\n index -= 1\n work_list[index] = current_element\n for index, item in enumerate(work_list):\n if work_list[index][1]==work_list[index-1][1] and work_list[index][0] None:\n self.config = config\n self.aws_access_key_id = self.config['access_key']\n self.aws_secret_access_key = self.config['secret_key']\n self.region = self.config['region']\n self.bucket_name = self.config['bucket_name']\n\n self.s3 = boto3.resource('s3',\n region_name=self.region,\n aws_access_key_id=self.aws_access_key_id,\n aws_secret_access_key=self.aws_secret_access_key)\n self.client = boto3.client('s3',\n region_name=self.region,\n aws_access_key_id=self.aws_access_key_id,\n aws_secret_access_key=self.aws_secret_access_key)\n \n def create_bucket(self):\n buckets = self.s3.buckets.all()\n if self.s3.Bucket(self.bucket_name) in buckets:\n return\n try:\n response = self.s3.create_bucket(Bucket=self.bucket_name)\n except ClientError as e:\n response = e.response\n return response\n \n def upload_avatar(self, file_path, email_addr):\n \"\"\"\n :param file_path: path of the file\n :param email_addr: the email address of user\n \"\"\"\n s3_path = os.path.join(email_addr, \"avatar.png\")\n try:\n response = self.client.upload_file(file_path, self.bucket_name, s3_path)\n except ClientError as e:\n response = e.response\n return response\n \n def upload_chatlog(self, email_addr, text=''):\n binary_text = str.encode(text)\n s3_path = os.path.join(email_addr, \"chatlog.txt\")\n\n try:\n object = self.s3.Object(\n bucket_name=self.bucket_name, \n key=s3_path\n )\n response = object.put(Body=binary_text)\n except ClientError as e:\n response = e.response\n return response\n \n def download_avatar(self, email_addr, local_path):\n \"\"\"\n download the avatar locally\n\n :param email_addr: the name of the user\n :param local_path: path (folder/filename) of the file locally\n \"\"\"\n s3_path = os.path.join(email_addr, \"avatar.png\")\n try:\n response = self.client.download_file(self.bucket_name, s3_path, local_path)\n except ClientError as e:\n response = e.response\n return response\n \n def download_chatlog(self, email_addr, local_path):\n s3_path = os.path.join(email_addr, \"chatlog.txt\")\n try:\n response = self.client.download_file(self.bucket_name, s3_path, local_path)\n except ClientError as e:\n response = e.response\n return response\n \n def delete_avatar(self, email_addr):\n s3_path = os.path.join(email_addr, \"avatar.png\")\n try:\n response = self.client.delete_object(\n Bucket=self.bucket_name,\n Key=s3_path,\n )\n except ClientError as e:\n response = e.response\n return response\n \n def delete_chatlog(self, email_addr):\n s3_path = os.path.join(email_addr, \"chatlog.txt\")\n try:\n response = self.client.delete_object(\n Bucket=self.bucket_name,\n Key=s3_path,\n )\n except ClientError as e:\n response = e.response\n return response\n \n def delete_folder(self, email_addr):\n \"\"\" \n delete everything inside the folder, as well as folder itself\n \"\"\"\n if 'Contents' not in self.client.list_objects(Bucket=self.bucket_name):\n logging.info('The bucket is already empty')\n return False\n\n bucket = self.s3.Bucket(self.bucket_name)\n bucket.objects.filter(Prefix=\"{}/\".format(email_addr)).delete()\n logging.info('Delete the folder: {}'.format(email_addr))\n return True\n","repo_name":"chuiyunjun/Intelligent-Chat-Assistant","sub_path":"app/s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":4082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"8818981429","text":"from unittest import TestCase\nfrom pylamarck.algorithms.exhaustive_search import ExhaustiveSearchBasic\n\n\nclass TestExhaustiveSearchBasic(TestCase):\n def test(self):\n xs = [3, 2, 1]\n esb = ExhaustiveSearchBasic(xs)\n x_min = esb.solve(lambda x: x)\n self.assertEqual(x_min, 1)\n","repo_name":"mateuszbaran/pylamarck","sub_path":"pylamarck/tests/algorithms/test_exhaustiveSearchBasic.py","file_name":"test_exhaustiveSearchBasic.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"1153075856","text":"import sys\nsys.stdin = open(\"input.txt\", 'r')\ninput = sys.stdin.readline\n\nN = list(map(int, input().rstrip().split()))\nans = 0\n\ndef dfs(pos, pick, times, cnt):\n global ans\n if times == 3:\n #print('times out')\n return\n if N[pos] == pick:\n cnt += 1\n #print(pos, pick, times, cnt)\n if pos == len(N)-1:\n #print('end')\n if cnt >= 5:\n ans += 1\n #ans = max(ans, cnt)\n return\n for i in range(1, 6):\n if i == pick:\n dfs(pos+1, i, times+1, cnt)\n else:\n dfs(pos+1, i, 1, cnt)\n\nfor i in range(1, 6):\n dfs(0, i, 1, 0)\n\nprint(ans)","repo_name":"hjyoon/baekjoon-answers","sub_path":"_19000/19949.py","file_name":"19949.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"31964607655","text":"from conan import ConanFile\nfrom conan.tools.files import apply_conandata_patches, export_conandata_patches, get, copy, rmdir\nfrom conan.tools.build import check_min_cppstd\nfrom conan.tools.cmake import CMake, CMakeDeps, CMakeToolchain, cmake_layout\nfrom conan.tools.scm import Version\n\nimport os\n\nrequired_conan_version = \">=1.53.0\"\n\nclass SimdutfConan(ConanFile):\n name = \"simdutf\"\n description = \"Unicode routines (UTF8, UTF16): billions of characters per second.\"\n license = (\"Apache-2.0\", \"MIT\")\n url = \"https://github.com/conan-io/conan-center-index\"\n homepage = \"https://github.com/simdutf/simdutf\"\n topics = (\"unicode\", \"transcoding\", \"neon\", \"simd\", \"avx2\", \"sse2\", \"utf8\", \"utf16\", )\n package_type = \"library\"\n settings = \"os\", \"arch\", \"compiler\", \"build_type\"\n options = {\n \"shared\": [True, False],\n \"fPIC\": [True, False],\n }\n default_options = {\n \"shared\": False,\n \"fPIC\": True,\n }\n\n @property\n def _minimum_cpp_standard(self):\n return 11\n\n def export_sources(self):\n export_conandata_patches(self)\n\n def config_options(self):\n if self.settings.os == \"Windows\":\n del self.options.fPIC\n\n def configure(self):\n if self.options.shared:\n self.options.rm_safe(\"fPIC\")\n\n def layout(self):\n cmake_layout(self, src_folder=\"src\")\n\n def validate(self):\n if self.info.settings.compiler.cppstd:\n check_min_cppstd(self, self._minimum_cpp_standard)\n\n def source(self):\n get(self, **self.conan_data[\"sources\"][self.version], strip_root=True)\n\n def generate(self):\n tc = CMakeToolchain(self)\n tc.variables[\"SIMDUTF_BENCHMARKS\"] = False\n tc.variables[\"BUILD_TESTING\"] = False\n if self.settings.compiler == \"gcc\" and Version(self.settings.compiler.version) == \"8\":\n tc.variables[\"CMAKE_CXX_FLAGS\"] = \" -mavx512f\"\n if Version(self.version) >= \"2.0.3\":\n tc.variables[\"SIMDUTF_TOOLS\"] = False\n tc.generate()\n deps = CMakeDeps(self)\n deps.generate()\n\n def build(self):\n apply_conandata_patches(self)\n cmake = CMake(self)\n cmake.configure()\n cmake.build()\n\n def package(self):\n copy(self, pattern=\"LICENSE*\", dst=os.path.join(self.package_folder, \"licenses\"), src=self.source_folder)\n cmake = CMake(self)\n cmake.install()\n rmdir(self, os.path.join(self.package_folder, \"lib\", \"cmake\"))\n\n def package_info(self):\n self.cpp_info.libs = [\"simdutf\"]\n\n if self.settings.os in [\"Linux\", \"FreeBSD\"]:\n self.cpp_info.system_libs.append(\"m\")\n","repo_name":"conan-io/conan-center-index","sub_path":"recipes/simdutf/all/conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","stars":835,"dataset":"github-code","pt":"77"}
+{"seq_id":"24367167981","text":"\nimport utils.io.text\nfrom collections import OrderedDict\nfrom utils.random import int_uniform, bool_bernoulli\n\nclass VideoFrameList(object):\n def __init__(self,\n video_frame_list_file_name,\n frames_before=None,\n frames_after=None,\n border_mode='duplicate',\n random_start=False,\n random_skip_probability=0.0):\n self.video_frame_list_file_name = video_frame_list_file_name\n assert frames_before >= 0 and frames_after >= 0, 'number of frames must not be negative'\n self.frames_before = frames_before\n self.frames_after = frames_after\n assert border_mode in ['duplicate', 'repeat', 'mirror', 'valid'], 'invalid border mode'\n self.border_mode = border_mode\n self.random_start = random_start\n self.random_skip_probability = random_skip_probability\n self.video_id_frames = {}\n self.load()\n\n def load(self):\n self.video_id_frames = utils.io.text.load_dict_csv(self.video_frame_list_file_name)\n\n def get_frame_index_list(self, index, video_frames):\n num_frames = self.frames_before + self.frames_after + 1\n if self.random_start:\n start_index = index - int_uniform(0, num_frames)\n else:\n start_index = index - self.frames_before\n index_list = []\n current_index = start_index\n while len(index_list) < num_frames:\n if self.random_skip_probability > 0 and bool_bernoulli(self.random_skip_probability) is True:\n current_index += 1\n continue\n index_list.append(current_index)\n current_index += 1\n if self.border_mode == 'valid':\n if index_list[0] < 0:\n shift = -index_list[0]\n index_list = [i + shift for i in index_list]\n elif index_list[-1] >= len(video_frames):\n shift = -(index_list[-1] - len(video_frames) + 1)\n index_list = [i + shift for i in index_list]\n return index_list\n\n def get_video_frame_range_check(self, frame_index, video_frames):\n assert frame_index >= 0 and frame_index < len(video_frames), 'invalid frame index'\n return video_frames[frame_index]\n\n def get_video_frame_duplicate(self, frame_index, video_frames):\n if frame_index < 0:\n frame_index = 0\n elif frame_index >= len(video_frames):\n frame_index = len(video_frames) - 1\n return self.get_video_frame_range_check(frame_index, video_frames)\n\n def get_video_frame_repeat(self, frame_index, video_frames):\n while frame_index < 0:\n frame_index += len(video_frames)\n while frame_index >= len(video_frames):\n frame_index -= len(video_frames)\n return self.get_video_frame_range_check(frame_index, video_frames)\n\n def get_video_frame_mirror(self, frame_index, video_frames):\n if frame_index < 0:\n frame_index = -frame_index\n elif frame_index >= len(video_frames):\n frame_index = len(video_frames) - (frame_index - len(video_frames)) - 1\n return self.get_video_frame_range_check(frame_index, video_frames)\n\n def get_video_frame(self, frame_index, video_frames):\n if self.border_mode == 'duplicate':\n return self.get_video_frame_duplicate(frame_index, video_frames)\n elif self.border_mode == 'repeat':\n return self.get_video_frame_repeat(frame_index, video_frames)\n elif self.border_mode == 'mirror':\n return self.get_video_frame_mirror(frame_index, video_frames)\n else:\n return self.get_video_frame_range_check(frame_index, video_frames)\n\n def get_image_ids(self, video_id, frame_id):\n video_frames = self.video_id_frames[video_id]\n index = video_frames.index(frame_id)\n frame_index_list = self.get_frame_index_list(index, video_frames)\n\n frame_list = []\n for frame_index in frame_index_list:\n video_frame = self.get_video_frame(frame_index, video_frames)\n frame_list.append(video_frame)\n return frame_list\n\n def get_id_dict_list(self, video_id, frame_id):\n frame_ids = self.get_image_ids(video_id, frame_id)\n return [OrderedDict([('video_id', video_id), ('frame_id', current_frame_id)]) for current_frame_id in frame_ids]\n","repo_name":"Xavier-cvpr/MMWHS","sub_path":"utils/utils/io/video_frame_list.py","file_name":"video_frame_list.py","file_ext":"py","file_size_in_byte":4395,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"77"}
+{"seq_id":"30187149688","text":"import datetime\nfrom datetime import date, timedelta\nimport time\nimport indigo\nimport eps\n\nlibversion = \"1.2.1\"\n\n# Various date/time (or datetime) utilities\n\n\n#\n# Print library version - added optional return in 1.1.1\n#\ndef libVersion (returnval = False):\n\tif returnval: return libversion\n\t\n\tindigo.server.log (\"##### DT %s #####\" % libversion)\n\n#\n# Format total seconds into a HH:MM:SS type format\n#\ndef secondsToClock (value, format = \"HH:MM:SS\"):\n\tif int(value) < 0:\n\t\tindigo.server.log(\"secondsToClock value must be greater than zero\", isError=True)\n\t\treturn \"00:00\"\n\t\t\n\tformat = str(format).lower()\n\ts = timedelta(seconds=int(value))\n\t\n\td = datetime.datetime(1,1,1) + s\n\t\n\tld = d.day\n\tlh = d.hour\n\tlm = d.minute\n\tls = d.second\n\t\n\tif format == \"hh:mm:ss\": return \"%02d:%02d:%02d\" % (lh, lm, ls)\n\tif format == \"hh:mm\": return \"%02d:%02d\" % (lh, lm)\n\tif format == \"mm:ss\": \n\t\tif lh > 0: lm = lm + (lh * 60)\n\t\tif lm > 99: return \"%002dM\" % lm\n\t\treturn \"%02d:%02d\" % (lm, ls)\n\t\n\tif format == \"relative\":\n\t\tif ld > 1: return \"+%02dD\" % ld\n\t\tif lh > 1: return \"+%02dH\" % lh\n\t\tif lm > 1: return \"+%02dM\" % lm\n\t\tif ls > 1: return \"+%02dS\" % ls\n\t\t\n\tif format == \"relative-hour\":\n\t\tif ld > 1: return \"+%02dD\" % ld\n\t\tif lh > 1: return \"+%02dH\" % lh\n\t\treturn \"%02d:%02d\" % (lm, ls)\n\t\n\treturn \"00:00:00\" # failsafe\n\n#\n# Like .NET datediff, takes days, house, minutes or seconds as t\n# If dates are sent as string they must be Y-m-d H:M:S\n# If d1 is earlier than d2 then a negative is returned, else a postitive is returned\n#\ndef DateDiff (t, d1, d2):\n\ttry:\n\t\tif type(d1) is str:\n\t\t\tif d1 == \"\":\n\t\t\t\td1 = \"2000-01-01 00:00:00\"\n\t\t\td1 = datetime.datetime.strptime(d1, \"%Y-%m-%d %H:%M:%S\") \n\t\tif type(d2) is str:\n\t\t\tif d2 == \"\":\n\t\t\t\td2 = \"2000-01-01 00:00:00\"\n\t\t\td2 = datetime.datetime.strptime(d2, \"%Y-%m-%d %H:%M:%S\") \n\n\texcept:\n\t\tlog (\"DateDiff ERROR: Got an error converting strings to datetimes, make sure they are in the format of Y-m-d H:M:S!\")\n\t\traise\n\t\treturn\n\n\ttry:\n\t\tsum = time.mktime(d1.timetuple()) - time.mktime(d2.timetuple())\n\t\tif sum == 0:\n\t\t\treturn 0\n\n\t\tif t.lower() == \"days\":\n\t\t\tret = sum / 86400\n\n\t\tif t.lower() == \"hours\":\n\t\t\tret = (sum / 86400) * 24\n\n\t\tif t.lower() == \"minutes\":\n\t\t\tret = ((sum / 86400) * 24) * 60\n\n\t\tif t.lower() == \"seconds\":\n\t\t\tret = (((sum / 86400) * 24) * 60) * 60\n\n\t\treturn ret\n\t\n\texcept:\n\t\tlog (\"DateDiff ERROR: Got an error converting to \" + t)\n\t\traise\n\t\treturn\n\n#\n# Like .NET dateadd, takes days, house, minutes or seconds as t\n# If dates are sent as string they must be Y-m-d H:M:S\n#\t\t\ndef DateAdd (t, n, d):\n\ttry:\n\t\tif type(d) is str:\n\t\t\tif d == \"\":\n\t\t\t\td = \"2000-01-01 00:00:00\"\n\t\t\td = datetime.datetime.strptime(d, \"%Y-%m-%d %H:%M:%S\") \n\t\t\n\texcept:\n\t\tlog (\"DateDiff ERROR: Got an error converting strings to datetimes, make sure they are in the format of Y-m-d H:M:S!\")\n\t\traise\n\t\treturn\n\t\n\tif n > -1:\n\t\tif t.lower() == \"days\":\n\t\t\tret = d + datetime.timedelta(0,float( ((n * 60) * 60) * 24 ))\n\n\t\tif t.lower() == \"hours\":\n\t\t\tret = d + datetime.timedelta(0,float( (n * 60) * 60 ))\n\n\t\tif t.lower() == \"minutes\":\n\t\t\tret = d + datetime.timedelta(0,float(n * 60))\n\t\t\t\n\t\tif t.lower() == \"seconds\":\n\t\t\tret = d + datetime.timedelta(0,float(n))\n\telse:\n\t\tn = n * -1\n\t\t\n\t\tif t.lower() == \"days\": ret = d - timedelta(days=n)\n\t\tif t.lower() == \"hours\": ret = d - timedelta(hours=n)\n\t\tif t.lower() == \"minutes\": ret = d - timedelta(minutes=n)\n\t\tif t.lower() == \"seconds\": ret = d - timedelta(seconds=n)\n\t\t\t\t\n\treturn ret\n\t\n\t\n#\n# Convert seconds to HH:MM:SS/MM:SS - 1.1.1\n#\ndef SecondsToDurationString (n, format = \"HH:MM:SS\"):\n\tn = int(n)\n\tif n == 0: \n\t\tif format == \"HH:MM:SS\": return \"00:00:00\"\n\t\tif format == \"MM:SS\": return \"00:00\"\n\t\n\ts = timedelta(seconds=n)\n\td = datetime.datetime(1,1,1) + s\n\n\tif format == \"HH:MM:SS\": return \"%02d:%02d:%02d\" % (d.hour, d.minute, d.second)\n\tif format == \"MM:SS\": return \"%02d:%02d\" % (d.minute, d.second)\n\n\treturn \"00:00\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Colorado4Wheeler/Scene-Toggle","sub_path":"EPS Scene Toggle.indigoPlugin/Contents/Server Plugin/eps/dtutil.py","file_name":"dtutil.py","file_ext":"py","file_size_in_byte":3906,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"27866209686","text":"from linkedlist import List\n\n\nclass Solution(object):\n def merge_point(self, list1, list2):\n if not list1 or not list2:\n return None\n\n l1 = l2 = 0\n head1= list1\n head2 = list2\n while head1:\n l1 += 1\n head1 = head1.next\n while head2:\n l2 += 1\n head2 = head2.next\n\n diff = abs(l1-l2)\n if l1 > l2:\n head1 = list1\n head2 = list2\n else:\n head1 = list2\n head2 = list1\n\n while diff > 0:\n head1 = head1.next\n diff -= 1\n\n while head1 and head2:\n if head1 == head2:\n return head1\n head1 = head1.next\n head2 = head2.next\n\nl1 = List()\nl2 = List()\n\nfor i in range(7):\n l1.append(i)\n\nfor i in range(3, 5):\n l2.append(i)\n\nmerge_p = l1.search(5)\nl2_last_node = l2.search(4)\n\nl2_last_node.next = merge_p\n\nprint(\"============== l1\")\nl1.display()\n\nprint(\"=======l2\")\nl2.display()\n\nprint('------------')\ns = Solution()\nk = s.merge_point(l1.head, l2.head)\n\nif not k:\n print(\"============= not fouund\")\nelse:\n print(k.value)","repo_name":"Praveen935/ds_algo","sub_path":"linkedlist/merge_point.py","file_name":"merge_point.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"27361458022","text":"#!/usr/bin/python\n\nimport sys,os,glob,urlparse,urllib,subprocess\n\ndef setcwd():\n realpath = os.path.realpath(sys.argv[0])\n dname = os.path.dirname(realpath)\n os.chdir(dname)\n\n# sets working directory based on path to index.py\nsetcwd()\n\n# loads local python modules, relative to index.py\nsys.path.append(os.path.realpath('py'))\n\nfrom logx import Viewer,Editor,debug_trace\n\n'''\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QApplication\n'''\nfrom PyQt4 import uic\nfrom PyQt4.QtGui import QApplication\nfrom PyQt4.QtCore import QObject,pyqtSlot\n\nnotesdir = \"../notes\"\npdfdir = \"../papers\"\nstartquery = \"./xq/index.xq\"\n\nclass PdfAdaptor(QObject):\n\n @pyqtSlot(str)\n def loadid(self, pdfid):\n pdfid = str(pdfid)\n pdfpath = pdfdir + os.sep + pdfid + '.pdf'\n self.loadpdf(pdfpath)\n \n @pyqtSlot(str)\n def loadpdf(self, pdfpath):\n pdfpath = str(pdfpath)\n pdfpath = os.path.realpath(pdfpath)\n subprocess.Popen(['xdg-open', pdfpath])\n\ndef path2url(path):\n return urlparse.urljoin(\n 'file:', urllib.pathname2url(path))\n\ndef main(argv):\n \n querypath = os.path.realpath(startquery)\n \n sourcedir = os.path.realpath(notesdir)\n\n sourcepaths = glob.glob(sourcedir + \"/*.html\")\n \n # for PyQt4\n sourceurls = \",\".join([(\"file://\" + path) for path in sourcepaths]) \n # for PyQt5\n #sourceurls = \",\".join([path2url(path) for path in sourcepaths])\n\n xquerynames = [\n ['sourceurls', sourceurls,'http://cefn.com/logx']\n ]\n\n javascriptnames = dict()\n\n # create application context\n app = QApplication(sys.argv) \n ui = uic.loadUi('index.ui')\n \n editor = Editor(focuspath=None,view=ui.editView,javascriptnames=javascriptnames,xquerynames=xquerynames)\n viewer = Viewer(querypath=querypath,view=ui.navView,javascriptnames=javascriptnames,xquerynames=xquerynames)\n pdf = PdfAdaptor()\n \n javascriptnames['editor']=editor\n javascriptnames['viewer']=viewer\n javascriptnames['pdf']=pdf\n\n # subscribe viewer to refresh whenever source files refresh\n # implicitly bound through 'sourcepaths' xquery name\n for sourcepath in sourcepaths:\n viewer.registersource(sourcepath)\n \n ui.show()\n \n # edit a notes file, if specified\n if len(argv) > 0:\n editor.focuspath = os.path.realpath(argv[0])\n\n # load the view\n viewer.render()\n \n sys.exit(app.exec_())\n \nif __name__ == \"__main__\":\n main(sys.argv[1:])","repo_name":"cefn/firmware-codesign-readinglog","sub_path":"ui/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"34455483049","text":"# coding:utf-8\n\n\ndef save_npz(data, fname, data_dir_flg=True):\n import numpy as np\n import os.path\n if data_dir_flg:\n FNAME = './data_dir/' + fname + '.npz'\n else:\n FNAME = fname + '.npz'\n\n # 指定したファイル名のファイルが存在した時には、警告文を表示させるだけで保存しない。\n if os.path.exists(FNAME):\n raise Exception('the file exits! save is failured!')\n else:\n np.savez(FNAME, data=data)\n\n\ndef load_npz(fname, data_dir_flg=True):\n import numpy as np\n if data_dir_flg:\n FNAME = './data_dir/' + fname + '.npz'\n else:\n FNAME = fname + '.npz'\n\n a = np.load(FNAME)\n data = a['data']\n return data\n","repo_name":"AnchorBlues/data-assimilation-lorenz","sub_path":"subroutine.py","file_name":"subroutine.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"ja","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"42750286349","text":"from Classes.letter import Letter\nfrom Classes.letterbox import Letterbox\nfrom Classes.post_office import PostOffice\n\nclass Person:\n '''The person has a letterbox, and can write, receive, send, read, encrypt and decrypt letters.'''\n def __init__(self, name, letterbox=Letterbox, letter=Letter, letter_received=Letter):\n letterbox = Letterbox()\n\n self.name = name\n self.letterbox = letterbox\n self.letter = letter\n self.letter_received = letter_received\n\n def __str__(self):\n return f'{self.name}'\n\n\n def write_letter(self, content, addressee):\n '''The person writes a letter with a defined content and addressee.'''\n self.letter = Letter()\n self.letter.content = content\n self.letter.addressed_to = addressee\n return f\"{self.letter.content}\"\n\n def encrypt_letter(self):\n '''The person encrypts the letter.'''\n if self.letter != None:\n self.letter.encrypted = True\n return \"Letter has been encrypted.\"\n\n def drop_letter(self, post_office=PostOffice):\n '''The person drops the letter at the post office.'''\n if self.letter.encrypted is True:\n self.letter.dropped = True\n post_office.letter = self.letter\n return \"Sender has dropped a letter in the Post Office.\"\n\n def pick_up_letter(self):\n '''The person picks up a letter from their letterbox.'''\n if self.letterbox.letter is not None:\n self.letter_received = self.letterbox.letter\n self.letterbox.letter = None\n self.letterbox.flag_down()\n return \"Receiver has picked up a letter from their letterbox.\"\n\n def decrypt_letter(self):\n '''The person decrypts a received letter.'''\n if self.letter_received is not None:\n self.letter_received.decrypt()\n return \"Letter has been decrypted.\"\n\n def read_letter(self):\n '''The person reads a received letter.'''\n if self.letter_received is not None and self.letter_received.get_encryption_status() is not True:\n self.letter_received.has_been_read()\n return f'Receiver has read this letter: \"{self.letter_received}\"'\n","repo_name":"JoanneHelenMana/you-have-mail","sub_path":"Classes/person.py","file_name":"person.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"11144932973","text":"def prime(n:int)->bool:\n if n<=1:\n return False\n for i in range(2,n):\n if n%i==0:\n return False\n return True\n \nn=int(input())\nlst=list(map(int,input().split()))\nmini=min(lst.index(min(lst)),lst.index(max(lst)))\nmaxi=max(lst.index(min(lst)),lst.index(max(lst)))\nc=0\nfor i in range(mini,maxi+1):\n if prime(lst[i]):\n c+=1\nprint(c)","repo_name":"RenukaPulavarthi/codemind-python","sub_path":"Primes_between_min_and_max.py","file_name":"Primes_between_min_and_max.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"74993551609","text":"import boto3\nimport config\nimport json\n\ndef queue_repo(repo):\n \"\"\"\n Queue repo for Lambda function to download from Github and profile.\n \"\"\"\n aws_client = boto3.client('sqs', region_name=config.sqs['region'])\n\n response = aws_client.send_message(\n QueueUrl=config.sqs['repo_url'],\n MessageBody=json.dumps({'repo': repo}),\n )\n\n return response\n","repo_name":"jhtimmins/locode","sub_path":"services/queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"9020648040","text":"import numpy as np\n\nclass InvalidPositArgException (Exception):\n pass\n\nclass ValueException (Exception):\n pass\n\nclass Posit:\n def __init__(self,N=8,es=1):\n self.N=N\n self.exponentBits=es\n self.sign=0\n self.regimeBits=0\n self.binaryFormat=\"00000000\"\n self.decimalFormat=0\n self.regime=0\n self.exponent=0\n self.mantisa=0\n \n if N!=8 and N!=16 and N!=32:\n print(\"N (number of bit) should be a number between: 8, 16 and 32\")\n raise InvalidPositArgException\n\n if es > N or es<0:\n print(\"es (number of bits of exponent) should be positive number and smaller than the number of bits N\")\n raise InvalidPositArgException\n\n \n \n \n \n def binaryNum(self,positBinary):\n self.binaryFormat=positBinary\n if (self.binaryFormat[1::].count(\"0\")==self.N-1 and self.binaryFormat[0]==\"1\"):\n self.decimalFormat=np.inf\n print(\"It is an exception value of a posit number.\")\n raise ValueException\n\n if (self.binaryFormat[1::].count(\"0\")==self.N-1 and self.binaryFormat[0]==\"0\"):\n self.decimalFormat=0\n raise ValueException\n\n if len(self.binaryFormat)!=self.N:\n print(\"The lenght of the posit number in Binary Format is not correct.\")\n raise InvalidPositArgException\n \n\n\n\n\nclass BinaryOperations():\n def __init__(self) -> None:\n pass\n\n def twosComplement(binaryNumber):\n n=len(binaryNumber)\n i = n - 1\n while(i >= 0):\n if (binaryNumber[i] == '1'):\n break\n i -= 1\n if (i == -1):\n return '1'+ binaryNumber\n \n k = i - 1\n while(k >= 0):\n if (binaryNumber[k] == '1'):\n binaryNumber = list(binaryNumber)\n binaryNumber[k] = '0'\n binaryNumber = ''.join(binaryNumber)\n else:\n binaryNumber = list(binaryNumber)\n binaryNumber[k] = '1'\n binaryNumber = ''.join(binaryNumber)\n \n k -= 1\n\n return binaryNumber \n\n \n\nclass Conversions():\n def __init__(self) -> None:\n pass\n\n def float2bin(float_number,num_bits):\n cadena_final=\"\"\n value= str(float_number)\n for i in range(0,num_bits):\n\n el_punto=value.find(\".\")\n value_arr= float(\"0.\"+value[el_punto+1::])\n result= value_arr*2\n front_point = str(int(result))\n cadena_final=cadena_final+front_point\n\n el_punto2=(str(result)).find(\".\")\n value= str(\"0.\"+str(result)[el_punto2+1::])\n\n return cadena_final\n \n def binary_to_decimal(string_binary):\n posicion = 0\n decimal = 0\n string_binary = string_binary[::-1]\n for digito in string_binary:\n # Elevar 2 a la posición actual\n multiplicador = 2**posicion\n decimal += int(digito) * multiplicador\n posicion += 1\n return decimal\n \n def binary_to_significant(string_binary):\n posicion = 1\n significant = 0\n for digito in string_binary:\n # Elevar 2 a la posición actual\n multiplicador = 2**(-1*posicion)\n significant += int(digito) * multiplicador\n posicion += 1\n return significant\n \n\ndef sign(decimal):\n if decimal<0 :\n return 1\n else:\n return 0\n\ndef decimal_to_posit(decimal,N,es):\n try:\n posit=Posit(N,es)\n \n if decimal==0:\n posit.binaryFormat= \"0\"*N\n else:\n useed= 2**(2**es)\n maxpos= useed**(N-2)\n minpos= useed**(2-N)\n\n if abs(decimal)0:\n rb=k+2\n else:\n rb=-k+1\n \n\n m=N-1-rb-es\n f= np.clip(abs((decimal_cut/(2**(k* (2**es) +e)) )-1),0,((2**m)-1)/2**m)\n\n eb= min(N-1-rb,es)\n fb= max(N-1-rb-eb,0)\n pe=(np.floor(e*(2**(eb-es)))) * 2**(es-eb)\n pf=(round(f*(2**fb))) *(2**-fb)\n\n\n #Construction binary\n \n #signo is 's'\n\n #regimen\n regime=\"\"\n if(k<0):\n for i in range(0,abs(int(k))):\n regime= regime + \"0\"\n regime= regime +\"1\"\n else:\n for i in range(0,abs(int(k))+1):\n regime= regime + \"1\"\n regime= regime +\"0\"\n \n posit.regimeBits=len(regime)\n posit.regime=k\n\n #exponente\n exponente=str(bin(int(abs(pe))))[2::]\n if len(exponente) < es:\n diference=es-len(exponente)\n dif_reg_exp= N-1-len(regime)\n exponente=diference*\"0\"+exponente\n if (dif_reg_exp==1):\n exponente=exponente[0]\n\n \n if len(regime)==(N-1):\n exponente=0*exponente\n\n #mantissa\n mantissa_bits= N-1-es-len(regime)\n if pf==0:\n mantissa=mantissa_bits*\"0\"\n else:\n mantissa= str(Conversions.float2bin(pf,mantissa_bits))\n \n #posit number binary\n \n if s==1:\n posit.binaryFormat= str(s) + BinaryOperations.twosComplement(regime + exponente + mantissa)\n else:\n posit.binaryFormat= str(s) + regime + exponente + mantissa\n \n posit.mantisa= 1+ Conversions.binary_to_significant(mantissa)\n posit.exponent=Conversions.binary_to_decimal(exponente)\n posit.decimalFormat = ((-1)**int(s)) *useed**(k) * 2 **Conversions.binary_to_decimal(exponente) * (1+ Conversions.binary_to_significant(mantissa))\n \n #return posit\n\n except InvalidPositArgException:\n posit=Posit()\n print(\"There is an exception.\")\n finally:\n return posit\n\n\ndef posit_to_decimal(positnum,N,es):\n sum_zeros=0\n sum_ones=0\n posit_shift=0\n regime=0\n exponente=0\n try:\n posit=Posit(N,es)\n posit.binaryNum(positnum)\n\n #Get sign\n signo= (-1)**int(positnum[0])\n posit.sign=int(positnum[0])\n if (signo<0):\n positnum=BinaryOperations.twosComplement(positnum)\n \n #Get regime\n if(positnum[1]==\"0\"):\n for i in range(1,N):\n if (positnum[i]==\"1\"):\n posit_shift= positnum[i+1:N]\n posit.regimeBits=i\n break\n else:\n sum_zeros+=1\n regime=-1*sum_zeros\n else:\n for i in range(1,N):\n if (positnum[i]==\"0\"):\n posit_shift= positnum[i+1:N]\n posit.regimeBits=i\n break\n else:\n sum_ones+=1\n regime=sum_ones-1\n \n posit.regime=regime\n #Get exponent\n exponente = Conversions.binary_to_decimal(posit_shift[0:es])\n posit.exponent=exponente\n \n #Get mantissa\n mantissa_binary = posit_shift[es::]\n mantissa= 1+ Conversions.binary_to_significant(mantissa_binary)\n posit.mantisa=mantissa\n #Get useed\n useed= 2**(2**es)\n\n #Get decimal number\n posit.decimalFormat= signo * useed**regime * 2**exponente * mantissa\n\n\n \n except InvalidPositArgException or ValueException:\n posit=Posit()\n print(\"There is an exception.\")\n \n finally:\n return posit","repo_name":"svalarezo96/unumposit","sub_path":"unumposit/conversionposit.py","file_name":"conversionposit.py","file_ext":"py","file_size_in_byte":8306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"41294127477","text":"\"\"\"\nN x N 배열 안의 숫자는 해당 영역에 존재하는 파리의 개수를 의미한다.\n아래는 N=5 의 예이다.\n \nM x M 크기의 파리채를 한 번 내리쳐 최대한 많은 파리를 죽이고자 한다.\n죽은 파리의 개수를 구하라!\n예를 들어 M=2 일 경우 위 예제의 정답은 49마리가 된다.\n \n\n[제약 사항]\n1. N 은 5 이상 15 이하이다.\n2. M은 2 이상 N 이하이다.\n3. 각 영역의 파리 갯수는 30 이하 이다.\n\n[입력]\n가장 첫 줄에는 테스트 케이스의 개수 T가 주어지고, 그 아래로 각 테스트 케이스가 주어진다.\n각 테스트 케이스의 첫 번째 줄에 N 과 M 이 주어지고,\n다음 N 줄에 걸쳐 N x N 배열이 주어진다.\n10\n5 2\n1 3 3 6 7\n8 13 9 12 8\n4 16 11 12 6\n2 4 1 23 2\n9 13 4 7 3\n6 3\n29 21 26 9 5 8\n21 19 8 0 21 19\n9 24 2 11 4 24\n19 29 1 0 21 19\n10 29 6 18 4 3\n29 11 15 3 3 29\n\n[출력]\n출력의 각 줄은 '#t'로 시작하고, 공백을 한 칸 둔 다음 정답을 출력한다.\n(t는 테스트 케이스의 번호를 의미하며 1부터 시작한다.)\n#1 49\n#2 159\n...\n\"\"\"\nimport sys\nsys.stdin = open('input.txt', 'r')\n\nT = int(input())\n\nfor t in range(1, T+1):\n result = [] \n # N : 정사각형 N\n # M : 파리채\n N, M = map(int, input().split())\n N_Rectangle = []\n\n # 2차원 정사각형 생성\n for n in range(N):\n N_Rectangle.append(input().split()) \n \n # print(N_Rectangle)\n # print('==============================')\n\n for i in range(N-M+1):\n for j in range(N-M+1):\n count = 0\n for k in range(i, M+i):\n for kk in range(j, M+j):\n count += int(N_Rectangle[k][kk])\n result.append(count)\n\n print('#{} {}'.format(t, max(result)))\n\n\n\n\n\n\n\n\n print('#{} {}'.format(t, result))","repo_name":"renine94/codingTest","sub_path":"swea/D2/05_2001_파리퇴치.py","file_name":"05_2001_파리퇴치.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"19270403387","text":"from django.urls import path\nfrom .views import BlogListView, BlogDetailView,BlogApiView\n\n\nurlpatterns = [\n path('',BlogListView.as_view(),name='blog_list'),\n path('',BlogDetailView.as_view(),name='blog_detail'),\n path('api/',BlogApiView.as_view())\n\n]\n","repo_name":"alexdotis/DjangoRealEstate","sub_path":"RealEstate/blogs/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"14234217675","text":"from django import forms\nfrom ...product.models import (Product, ProductClass, PackageOfferImage)\nfrom ..product.widgets import ImagePreviewWidget\n\n\nclass PackageOfferForm2(forms.Form):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n coil_class_id = ProductClass.objects.filter(name='Coil')[0].id\n coils = Product.objects.filter(product_class_id=coil_class_id)\n\n battery_class_id = ProductClass.objects.filter(name='Battery')[0].id\n batteries = Product.objects.filter(product_class_id=battery_class_id)\n\n self.fields['device'] = forms.CharField(label='Device')\n self.fields['device'].widget.attrs['readonly'] = True\n self.fields['coils'] = forms.ChoiceField(\n choices=[(coil.id, coil.name) for coil in coils]\n )\n self.fields['batteries'] = forms.ChoiceField(\n choices=[(battery.id, battery.name) for battery in batteries]\n )\n self.fields['price'] = forms.DecimalField(label='Price', decimal_places=2)\n\n\nclass UploadImageForm(forms.ModelForm):\n class Meta:\n model = PackageOfferImage\n fields = ('image', )\n\n def __init__(self, *args, **kwargs):\n product = kwargs.pop('product')\n super().__init__(*args, **kwargs)\n self.instance.product = product\n\n\nclass ProductImageForm(forms.ModelForm):\n use_required_attribute = False\n # variants = forms.ModelMultipleChoiceField(\n # queryset=ProductVariant.objects.none(),\n # widget=forms.CheckboxSelectMultiple, required=False)\n\n class Meta:\n model = PackageOfferImage\n exclude = ('product', 'order')\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n if self.instance.image:\n self.fields['image'].widget = ImagePreviewWidget()\n","repo_name":"tanjibpa/alrawaa","sub_path":"saleor/dashboard/package_offers/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"33240364321","text":"\"\"\"\nThis program creates two generators\n* a prime number generator\n* a semi-prime number generator\n (Semi prime numbers are the product of two prime numbers).\nAdditionally, it provides several functions that use these iterators to\ngenerate information that might be of interest, e.g.\n1. A possibly infinite sequence of prime/sub-primes numbers.\n2. All prime/sub-prime numbers below a given threshold.\n3. The nth prime/sub-prime number.\n4. Prime factors of a given number\n\"\"\"\n\nfrom collections.abc import Callable, Iterator\n\nfrom typing import List\nimport math\n\n\ndef elements_under(sequence: Iterator[int], bound: int, predicate: Callable[[int], bool] = None) \\\n -> Iterator[int]:\n \"\"\"\n Yields a finite sequence of elements under a given bound, optionally matching a predicate.\n\n :param sequence: an infinite sequence of integers, e.g. primes()\n :param bound: an exclusive upper bound for the yielded sequence\n :param predicate: if present, the sequence includes only values for which this function\n returns True\n \"\"\"\n item = next(sequence)\n\n while item < bound:\n if predicate is not None:\n if predicate(item):\n yield item\n else:\n yield item\n item = next(sequence)\n\n\ndef is_prime(n: int) -> bool:\n \"\"\" Returns whether n is prime. \"\"\"\n for i in range(2, math.floor(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n\n return True\n\n\ndef nth_element(sequence: Iterator[int], n: int) -> int:\n \"\"\"\n Returns the nth element of a possibly infinite sequence of integers.\n\n :param sequence: a sequence of integers, e.g. primes()\n :param n: the sequence index desired\n :return: the value at index n of the sequence\n \"\"\"\n for _ in range(n):\n next(sequence)\n\n return next(sequence)\n\n\ndef primes() -> Iterator[int]:\n \"\"\" Yields an infinite sequence of prime numbers. \"\"\"\n yield 2\n n = 3\n\n while True:\n if is_prime(n):\n yield n\n n += 2\n\n\ndef prime_factors(n: int) -> List[int]:\n \"\"\" Returns a list of prime numbers with product n, in ascending order. \"\"\"\n p_gen = primes()\n p_num = next(p_gen)\n factors = []\n\n while n != 1:\n if n % p_num == 0:\n factors.append(p_num)\n n /= p_num\n else:\n p_num = next(p_gen)\n\n return factors\n\n\ndef semiprimes() -> Iterator[int]:\n \"\"\" Yields an infinite sequence of semiprimes. \"\"\"\n val = 1\n\n while True:\n if len(prime_factors(val)) == 2:\n yield val\n val += 1\n\n\nif __name__ == '__main__':\n assert all(is_prime(n) for n in (2, 3, 5, 7))\n assert all(not is_prime(n) for n in (4, 6, 8, 9))\n assert list(elements_under(primes(), 10)) == [2, 3, 5, 7]\n assert list(elements_under(semiprimes(), 10)) == [4, 6, 9]\n assert nth_element(primes(), 2) == 5\n assert nth_element(semiprimes(), 2) == 9\n assert list(elements_under(primes(), 1386, lambda p: not 1386 % p)) == [2, 3, 7, 11]\n assert prime_factors(1386) == [2, 3, 3, 7, 11]\n","repo_name":"PrakritGoel/PythonProjects","sub_path":"primes.py","file_name":"primes.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"36007986893","text":"# Freelancer (1.3) by Taragoth\r\n# Released 11 July 2011\r\n# Edits by Caba'drin 14 Dec 2011\r\n# Mod-Merger'd by Windyplains, Monnikje and Caba'drin\r\n\r\nfrom header_common import *\r\nfrom header_operations import *\r\nfrom header_triggers import *\r\n\r\nfrom module_constants import *\r\n\r\n####################################################################################################################\r\n# Each trigger contains the following fields:\r\n# 1) Check interval: How frequently this trigger will be checked\r\n# 2) Delay interval: Time to wait before applying the consequences of the trigger\r\n# After its conditions have been evaluated as true.\r\n# 3) Re-arm interval. How much time must pass after applying the consequences of the trigger for the trigger to become active again.\r\n# You can put the constant ti_once here to make sure that the trigger never becomes active again after it fires once.\r\n# 4) Conditions block (list). This must be a valid operation block. See header_operations.py for reference.\r\n# Every time the trigger is checked, the conditions block will be executed.\r\n# If the conditions block returns true, the consequences block will be executed.\r\n# If the conditions block is empty, it is assumed that it always evaluates to true.\r\n# 5) Consequences block (list). This must be a valid operation block. See header_operations.py for reference. \r\n####################################################################################################################\r\n\r\n\r\ntriggers = [\r\n#+freelancer start\r\n\r\n# CHECKS IF \"$enlisted_party\" IS DEFEATED\r\n\r\n (0.0, 0, 0, [\r\n (eq, \"$freelancer_state\", 1),\r\n (gt, \"$enlisted_party\", 0),\r\n (neg|party_is_active, \"$enlisted_party\"),\r\n ],\r\n [\r\n (assign, \"$freelancer_state\", 0),\r\n (call_script, \"script_freelancer_detach_party\"),\r\n\t\t\r\n\t\t#to prevent companions from being lost forever\r\n\t\t(call_script, \"script_party_restore\"), \r\n\t\t(party_get_num_companion_stacks, \":num_stacks\", \"p_main_party\"),\r\n (try_for_range_backwards, \":cur_stack\", 0, \":num_stacks\"),\r\n\t\t\t(party_stack_get_troop_id, \":return_troop\", \"p_main_party\", \":cur_stack\"),\r\n\t\t\t(neg|troop_is_hero, \":return_troop\"),\r\n\t\t\t(party_stack_get_size, \":stack_size\", \"p_main_party\", \":cur_stack\"),\r\n\t\t\t(party_remove_members, \"p_main_party\", \":return_troop\", \":stack_size\"),\r\n\t\t(try_end),\r\n\r\n #removes faction relation given at enlist\r\n ## CC-D begin: for caravan\r\n\t\t(store_troop_faction, \":commander_faction\", \"$enlisted_lord\"),\r\n\t\t(try_begin),\r\n\t\t\t(neq, \":commander_faction\", \"fac_commoners\"),\r\n\t\t\t(call_script, \"script_conclude_quest\", \"qst_freelancer_enlisted\"),\r\n\t\t\t\r\n\t\t\t(store_current_day, \":cur_day\"),\r\n\t\t\t(troop_get_slot, \":service_day_start\", \"trp_player\", slot_troop_freelancer_start_date),\r\n\t\t\t(store_sub, \":service_length\", \":cur_day\", \":service_day_start\"),\r\n\t\t\t(troop_set_slot, \"trp_player\", slot_troop_freelancer_start_date, \":service_length\"), ## to record last reward at slot_troop_freelancer_start_date\r\n\t\t\t\r\n\t\t\t## NMCml FL begin: keep banner\r\n\t\t\t(party_get_slot, \":banner\", \"p_freelancer_party_backup\", slot_freelancer_last_banner),\r\n\t\t\t(troop_set_slot, \"trp_player\", slot_troop_banner_scene_prop, \":banner\"),\r\n\t\t\t## NMCml FL end\r\n\t\t(try_end),\r\n\t\t## CC-D end\r\n\t\t## NMCml FL begin: keep relation\r\n #(try_for_range, \":cur_faction\", kingdoms_begin, kingdoms_end),\r\n # (neq, \":commander_faction\", \":cur_faction\"),\r\n\t\t#\t(faction_slot_eq, \":cur_faction\", slot_faction_state, sfs_active),\r\n # (call_script, \"script_set_player_relation_with_faction\", \":cur_faction\", 0),\r\n #(try_end),\r\n (call_script, \"script_fl_recover_faction_relation\", \":commander_faction\"),\r\n ## NMCml FL end\r\n\t\t## CC-D begin: local achievement\r\n\t\t(store_current_day, \":cur_day\"),\r\n\t\t(troop_get_slot, \":service_day_start\", \"trp_player\", slot_troop_freelancer_start_date),\r\n\t\t(store_sub, \":service_length\", \":cur_day\", \":service_day_start\"),\r\n\t\t(try_begin),\r\n\t\t (neg|troop_slot_ge, \"trp_ccd_treasure\", slot_troop_ccd_rec_max_fl_days, \":service_length\"),\r\n\t\t (troop_set_slot, \"trp_ccd_treasure\", slot_troop_ccd_rec_max_fl_days, \":service_length\"),\r\n\t\t(try_end),\r\n\t\t## CC-D end\r\n\r\n\t\t## NMCml FL begin: fix suddenly disappearance\r\n\t\t(try_begin),\r\n\t\t (party_is_active, \"$g_enemy_party\"),\r\n\t\t \r\n\t\t (assign, \"$g_encountered_party\", \"$g_enemy_party\"),\r\n\t\t (jump_to_menu, \"mnu_captivity_start_wilderness\"),\r\n\t\t(else_try),\r\n\t\t (display_message, \"@Suddenly your enlisted party was broken up, and you retired.\"),\r\n\t\t(try_end),\r\n\t\t## NMCml FL end\r\n ]),\r\n\r\n # CHECKS IF \"$enlisted_party\" HAS JOINED BATTLE\r\n\r\n (0.0, 0, 0, [\r\n (eq, \"$freelancer_state\", 1),\r\n\t\t\r\n\t\t#collected nearby enemies->detach (post-battle)\r\n\t\t(try_begin), \r\n\t\t\t(party_slot_ge, \"p_freelancer_party_backup\", slot_party_last_in_combat, 1),\r\n\t\t\t(map_free),\r\n\t\t\t(party_set_slot, \"p_freelancer_party_backup\", slot_party_last_in_combat, 0),\r\n\t\t\t(party_get_num_attached_parties, \":num_attached\", \"p_main_party\"),\r\n\t\t\t(try_for_range_backwards, \":i\", 0, \":num_attached\"),\r\n\t\t\t\t(party_get_attached_party_with_rank, \":party\", \"p_main_party\", \":i\"),\r\n\t\t\t\t(party_detach, \":party\"),\r\n\t\t\t(try_end),\r\n\t\t(try_end),\r\n\t\t\r\n\t\t#Is currently in battle\r\n (party_get_battle_opponent, \":commander_enemy\", \"$enlisted_party\"),\r\n (gt, \":commander_enemy\", 0),\r\n\t\t\r\n\t\t#checks that the player's health is high enough to join battle\r\n (store_troop_health, \":player_health\", \"trp_player\"),\r\n (ge, \":player_health\", 50),\r\n ## NMCml FL begin: stop when wounded and surrender: refer from TMP(Freelancer: Slack off (PBOD))\r\n (eq, \"$flag_slack_off\", 0),\r\n ## NMCml FL end\r\n ],\r\n [\r\n (jump_to_menu, \"mnu_world_map_soldier\"),\r\n ]),\r\n\r\n# CHECKS IF PLAYER WON THE REVOLT\r\n\r\n (1.0, 0, 0, [\r\n (eq, \"$freelancer_state\", 0),\r\n (gt, \"$enlisted_party\", 0),\r\n (neg|party_is_active, \"$enlisted_party\"),\r\n\r\n\t\t(store_troop_faction, \":commander_faction\", \"$enlisted_lord\"),\r\n (store_relation, \":relation\", \"fac_player_supporters_faction\", \":commander_faction\"),\r\n (lt, \":relation\", 0),\r\n\r\n (party_get_attached_party_with_rank, \":attached_party\", \"p_main_party\", 0),\r\n (eq, \"p_temp_party_2\", \":attached_party\"),\r\n ],\r\n [\r\n (assign, \"$enlisted_party\", -1),\r\n (party_detach, \"p_temp_party_2\"),\r\n (store_skill_level, \":cur_leadership\", \"skl_leadership\", \"trp_player\"),\r\n (store_skill_level, \":cur_persuasion\", \"skl_persuasion\", \"trp_player\"),\r\n (store_add, \":chance\", \":cur_persuasion\", \":cur_leadership\"),\r\n (val_add, \":chance\", 10),\r\n (store_random_in_range, \":prisoner_state\", 0, \":chance\"),\r\n\r\n (try_begin),\r\n (is_between, \":prisoner_state\", 0, 5),\r\n (call_script, \"script_party_calculate_strength\", \"p_main_party\", 0),\r\n (assign, \":main_strength\", reg0),\r\n (call_script, \"script_party_calculate_strength\", \"p_temp_party_2\", 0),\r\n (assign, \":temp_strength\", reg0),\r\n (ge, \":temp_strength\", \":main_strength\"),\r\n\r\n (party_get_num_prisoner_stacks, \":num_stacks\", \"p_temp_party_2\"),\r\n (try_for_range, \":cur_stack\", 0, \":num_stacks\"),\r\n (party_prisoner_stack_get_troop_id, \":cur_troops\", \"p_temp_party_2\", \":cur_stack\"),\r\n (party_prisoner_stack_get_size, \":cur_size\", \"p_temp_party_2\", \":cur_stack\"),\r\n (party_remove_prisoners, \"p_temp_party_2\", \":cur_troops\", \":cur_size\"),\r\n (try_end),\r\n\r\n (tutorial_box, \"@The released prisoners were not be trusted and they are preparing to attack you!\", \"@Warning!\"),\r\n (start_encounter, \"p_temp_party_2\"),\r\n (change_screen_map),\r\n (else_try),\r\n (is_between, \":prisoner_state\", 5, 10),\r\n (tutorial_box, \"@The released prisoners scattered as soon as the battle finished. You will not be seeing them again.\", \"@Notice!\"),\r\n (party_clear, \"p_temp_party_2\"),\r\n (else_try),\r\n (tutorial_box, \"@The released prisoners have remained loyal and will join your party\", \"@Notice!\"),\r\n (party_get_num_companion_stacks, \":num_stacks\", \"p_temp_party_2\"),\r\n (try_for_range, \":cur_stack\", 0, \":num_stacks\"),\r\n (party_stack_get_troop_id, \":cur_troops\", \"p_temp_party_2\", \":cur_stack\"),\r\n (party_stack_get_size, \":cur_size\", \"p_temp_party_2\", \":cur_stack\"),\r\n (party_add_members, \"p_main_party\", \":cur_troops\", \":cur_size\"),\r\n (try_end),\r\n (party_clear, \"p_temp_party_2\"),\r\n (try_end),\r\n ]),\r\n\r\n# IF LEFT MOUSE CLICK GO TO SOLDIER'S MENU\r\n\r\n (0.0, 0, 0, [\r\n (eq, \"$freelancer_state\", 1),\r\n (key_clicked, key_left_mouse_button),\r\n\r\n (set_fixed_point_multiplier, 1000),\r\n (mouse_get_position, pos0),\r\n (position_get_y, \":y\", pos0),\r\n (gt, \":y\", 50), #allows the camp, reports, quests, etc. buttons to be clicked\r\n ],\r\n [\r\n (jump_to_menu, \"mnu_world_map_soldier\"),\r\n (rest_for_hours_interactive, 9999, 4, 0),\r\n ]),\r\n\r\n(24.0, 0, 0, [\r\n (eq, \"$freelancer_state\", 2),\r\n ],\r\n [\r\n\t\t## NMCml FL begin: quest fix\r\n\t\t#(troop_get_slot, \":days_left\", \"trp_player\", slot_troop_days_on_mission),\r\n\t\t(quest_get_slot, \":days_left\", \"qst_freelancer_vacation\", slot_quest_expiration_days),\r\n\t\t(try_begin),\r\n\t\t# (gt, \":days_left\", 5),\r\n\t\t# (val_sub, \":days_left\", 1),\r\n\t\t# (troop_set_slot, \"trp_player\", slot_troop_days_on_mission, \":days_left\"),\r\n\t\t#(else_try),\t\t \r\n\t\t (is_between, \":days_left\", 1, 5),\r\n\t\t (check_quest_active, \"qst_freelancer_vacation\"),\r\n\t\t (assign, reg0, \":days_left\"),\r\n\t\t (display_message, \"@You have {reg0} days left till you are declared as a deserter!\"),\r\n\t\t# (val_sub, \":days_left\", 1),\r\n\t\t# (troop_set_slot, \"trp_player\", slot_troop_days_on_mission, \":days_left\"),\r\n\t\t(else_try), #declare deserter\r\n\t\t (eq, \":days_left\", 0),\r\n\t\t (call_script, \"script_event_player_deserts\"),\r\n\t\t (try_begin),\r\n\t\t\t(check_quest_active, \"qst_freelancer_vacation\"),\r\n\t\t\t(call_script, \"script_fail_quest\", \"qst_freelancer_vacation\"),\r\n\t\t\t(call_script, \"script_end_quest\", \"qst_freelancer_vacation\"),\r\n\t\t (try_end),\r\n (display_message, \"@You have now been declared as a deserter!\"),\r\n\t\t(try_end),\r\n\t\t\r\n\t\t(try_begin),\r\n\t\t (neg|check_quest_active, \"qst_freelancer_vacation\"),\r\n\t\t (le, \":days_left\", 1),\r\n\t\t (check_quest_active, \"qst_freelancer_enlisted\"),\r\n\t\t (call_script, \"script_event_player_deserts\"),\r\n\t\t (display_message, \"@You have now been declared as a deserter!\"),\r\n\t\t(try_end), \r\n\t\t## NMCml FL end\r\n ]),\r\n## CC-D begin :Freelancer pause in town from Tiny Mod Patcher\r\n(0.0, 0, 0, [\r\n (eq, \"$freelancer_state\", 1),\r\n (eq, \"$g_fl_pause_in_town\", 1),\r\n (party_is_active, \"$enlisted_party\"),\r\n (party_is_in_any_town, \"$enlisted_party\"),\r\n\r\n (party_get_cur_town, \":cur_town\", \"$enlisted_party\"),\r\n (is_between, \":cur_town\", towns_begin, towns_end),\r\n ],\r\n [\r\n (assign, \"$g_fl_pause_in_town\", 2),\r\n #(assign, \"$g_infinite_camping\", 0),\r\n (jump_to_menu, \"mnu_world_map_soldier\"),\r\n (rest_for_hours_interactive, 9999, 4, 0),\r\n ]),\r\n## CC-D end\r\n## CC-D begin\r\n(3.0, 0, 0, [\r\n (eq, \"$freelancer_state\", 1),\r\n (party_is_active, \"$enlisted_party\"),\r\n (party_slot_eq, \"$enlisted_party\", slot_party_type, spt_kingdom_caravan),\r\n ],\r\n [\r\n #(set_show_messages, 0),\r\n (call_script, \"script_ccd_fl_update_faction_relation\"),\r\n #(set_show_messages, 1),\r\n ]),\r\n#+freelancer end\r\n]\r\n\r\n\r\n# Used by modmerger framework version >= 200 to merge stuff\r\ndef modmerge(var_set):\r\n try:\r\n var_name_1 = \"triggers\"\r\n orig_triggers = var_set[var_name_1]\r\n orig_triggers.extend(triggers)\r\n except KeyError:\r\n errstring = \"Variable set does not contain expected variable: \\\"%s\\\".\" % var_name_1\r\n raise ValueError(errstring)","repo_name":"TokyoHuskarl/Ore-Custom-Conquest-Cave-Legacy","sub_path":"Append/source_occc/freelancer_triggers.py","file_name":"freelancer_triggers.py","file_ext":"py","file_size_in_byte":12018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"26931571809","text":"\"\"\"Test the parse package.\"\"\"\n\nimport csv\nimport os\nimport tempfile\nimport unittest\n\nfrom bs4 import BeautifulSoup\n\nfrom . import parse\n\n\nclass TestParseTables(unittest.TestCase):\n def assert_html_to_csv(self, testin, testout):\n \"\"\"Assert that an HTML input file becomes a CSV output file.\"\"\"\n with open(testin, \"r\") as htmlfile:\n tag = parse.get_tables_from_html(htmlfile.read())[0]\n got = parse.HtmlTable(tag).parse_rows()\n\n with open(testout, \"r\") as csvfile:\n want = list(csv.reader(csvfile))\n\n for g, w in zip(got, want):\n self.assertEqual(g, w)\n\n def test_parse_colspans(self):\n \"\"\"An HTML `` element becomes many CSV column cells.\"\"\"\n self.assert_html_to_csv(\n \"testdata/colspan/input.html\", \"testdata/colspan/output.csv\"\n )\n\n def test_parse_rowspans(self):\n \"\"\"An HTML ` ` element becomes many CSV row cells.\"\"\"\n self.assert_html_to_csv(\n \"testdata/rowspan/input.html\", \"testdata/rowspan/output.csv\"\n )\n\n def test_parse_linebreaks(self):\n \"\"\"HTML ` ` elements are parsed out and replaced with spaces.\"\"\"\n self.assert_html_to_csv(\n \"testdata/linebreaks/input.html\", \"testdata/linebreaks/output.csv\"\n )\n\n def test_quotes_and_smalls(self):\n \"\"\"HTML `` elements are included and `\"` quotes are escaped.\"\"\"\n self.assert_html_to_csv(\n \"testdata/mountains/input.html\", \"testdata/mountains/output.csv\"\n )\n\n def test_single_img_cells(self):\n \"\"\"HTML ` ` elements within cells become alt-text.\"\"\"\n self.assert_html_to_csv(\n \"testdata/imgcells/input.html\", \"testdata/imgcells/output.csv\"\n )\n\n def test_write_to_dir(self):\n \"\"\"An HTML page with many `` elements is written to many CSV files.\"\"\"\n with tempfile.TemporaryDirectory() as tmpdir:\n with open(\"testdata/wholepage/volcanoes.html\") as htmlfile:\n parser = parse.Parser(htmlfile.read())\n parser.write_to_dir(tmpdir)\n want = [\n \"table_1_6000_metres.csv\",\n \"table_2_5000_metres.csv\",\n \"table_3_4000_metres.csv\",\n \"table_4_3000_metres.csv\",\n \"table_5_2000_metres.csv\",\n \"table_6_1000_metres.csv\",\n \"table_7_from_its_base_on_the_ocean_floor.csv\",\n ]\n got = sorted(os.listdir(tmpdir))\n self.assertEqual(got, want)\n\n\nclass TestParseTableHeader(unittest.TestCase):\n def assert_header_from_table(self, header, html):\n \"\"\"Assert that a given header is returned from a given HTML string.\"\"\"\n tag = BeautifulSoup(html, \"lxml\").find(\"table\")\n got = parse.HtmlTable(tag).parse_header()\n self.assertEqual(got, header)\n\n def test_caption(self):\n \"\"\"A table with a `` will always use the caption.\"\"\"\n self.assert_header_from_table(\n \"Caption\",\n \"\"\"\n Header \n Subheader \n \n \"\"\",\n )\n\n def test_h2(self):\n \"\"\"A table without a caption returns the preceeding ``.\"\"\"\n self.assert_header_from_table(\n \"Header\",\n \"\"\"\n Header \n \n \"\"\",\n )\n\n def test_h2_and_h3(self):\n \"\"\"A table with an `` header will also check for `` subheaders.\"\"\"\n self.assert_header_from_table(\n \"Header - Subheader\",\n \"\"\"\n Header \n Subheader \n \n \"\"\",\n )\n\n def test_table_only(self):\n \"\"\"A table with no other information will return a default value.\"\"\"\n self.assert_header_from_table(None, \"\")\n\n\nclass TestFindTablesByHeader(unittest.TestCase):\n def assert_table_found(self, search, want, html):\n \"\"\"Assert that an HtmlTable can be identified by its header.\"\"\"\n parser = parse.Parser(html)\n table = parser.find_table_by_header(search)\n self.assertEqual(table.parse_header(), want)\n\n def test_formatting(self):\n \"\"\"A match can be made with one table despite formatting differences.\"\"\"\n pairs = (\n (\"caption\", \"CaptiON!\"),\n (\"CaptiON!\", \"caption\"),\n (\"underscores-hyphens\", \"UNDERSCORES_HYPHENS\"),\n )\n for p1, p2 in pairs:\n html = text_html_table(caption=p2)\n self.assert_table_found(p1, p2, html)\n\n def test_single_match(self):\n \"\"\"A single table can be loosely matched from many tables\"\"\"\n html = text_html_table(caption=\"1,000 Metres\")\n html += text_html_table(caption=\"2,000 Metres\")\n self.assert_table_found(\"1000\", \"1,000 Metres\", html)\n\n def test_no_header_table(self):\n \"\"\"A match can be made against many tables when one has no header.\"\"\"\n html = text_html_table()\n html += text_html_table(caption=\"Table 2\")\n self.assert_table_found(\"table\", \"Table 2\", html)\n\n def test_no_matches(self):\n \"\"\"An error is raised when no matches are found.\"\"\"\n html = text_html_table(caption=\"table 1\")\n html += text_html_table(caption=\"table 2\")\n with self.assertRaises(parse.Error):\n self.assert_table_found(\"n/a\", \"\", html)\n\n def test_many_matches(self):\n \"\"\"An error is raised when more than one match is found.\"\"\"\n html = text_html_table(caption=\"table 1\")\n html += text_html_table(caption=\"table 2\")\n with self.assertRaises(parse.Error):\n self.assert_table_found(\"table\", \"\", html)\n\n\nclass TestCsvFilename(unittest.TestCase):\n def test_expected_filenames(self):\n \"\"\"Table headers are translated to OS-friendly filenames.\"\"\"\n testcases = [\n (\"General\", \"general.csv\"),\n (\"API / editor features\", \"api_editor_features.csv\"),\n ]\n for header, expected in testcases:\n self.assertEqual(expected, parse.csv_filename(header))\n\n def test_filename_too_long(self):\n header = \"List of Super Bowl television ratings in the United States with average viewers, total viewers, average households, household rating and share, 18–49 rating and share and average cost of 30-second ad, showing the period they were measured between, Super Bowl, date and network aired on\" # noqa: E501\n want = \"list_of_super_bowl_television_ratings_in_the_united_states_with_average_viewers_total_viewers_average_households_household_rating_and_share_18–49_rating_and_share_and_average_cost_of_30_second_ad_showing_the_period_they_were_measured_between_super.csv\" # noqa: E501\n self.assertEqual(want, parse.csv_filename(header))\n\n\ndef text_html_table(caption=None):\n \"\"\"Return a text HtmlTable with a given caption for testing.\"\"\"\n if caption:\n caption = f\"{caption} \"\n\n return f\"\"\"\n \n \"\"\"\n","repo_name":"rocheio/wiki-table-scrape","sub_path":"wikitablescrape/test_parse.py","file_name":"test_parse.py","file_ext":"py","file_size_in_byte":7248,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"77"}
+{"seq_id":"22111371574","text":"import traceback\n\nfrom flask import Blueprint, request\nfrom loguru import logger\n\nfrom autotest.exc import codes\nfrom autotest.services.api_services.test_suites import TestSuitesService\nfrom autotest.utils.api import partner_success, json_required, login_verification\n\nbp = Blueprint('suites', __name__, url_prefix='/api/testSuites')\n\n\n@bp.route('/list', methods=['POST'])\n@login_verification\n@json_required\ndef suites_list():\n \"\"\"\n 套件列表\n :return:\n \"\"\"\n try:\n data = TestSuitesService.list(**request.json)\n except Exception as err:\n logger.error(traceback.format_exc())\n return partner_success(code=codes.PARTNER_CODE_FAIL, msg=str(err))\n return partner_success(data=data)\n\n\n@bp.route('/saveOrUpdate', methods=['POST'])\n@login_verification\n@json_required\ndef save_or_update():\n \"\"\"\n 更新保存套件\n :return:\n \"\"\"\n try:\n data = TestSuitesService.save_or_update(**request.json)\n except Exception as err:\n logger.error(traceback.format_exc())\n return partner_success(code=codes.PARTNER_CODE_FAIL, msg=str(err))\n return partner_success(data=data.id)\n\n\n@bp.route('/deleted', methods=['POST'])\n@login_verification\n@json_required\ndef deleted():\n \"\"\"\n 删除套件\n :return:\n \"\"\"\n parsed_data = request.json\n s_id = parsed_data.get('id', None)\n try:\n TestSuitesService.deleted(s_id)\n except Exception as err:\n logger.error(traceback.format_exc())\n return partner_success()\n return partner_success()\n\n\n@bp.route('/getSuiteInfo', methods=['POST'])\n@login_verification\n@json_required\ndef suite_info():\n \"\"\"\n 套件信息\n :return:\n \"\"\"\n try:\n data = TestSuitesService.get_suite_info(**request.json)\n except Exception as err:\n logger.error(traceback.format_exc())\n return partner_success(code=codes.PARTNER_CODE_FAIL, msg=str(err))\n return partner_success(data=data)\n","repo_name":"AHUsers/HTB","sub_path":"autotest/views/api/test_suites.py","file_name":"test_suites.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"8407887563","text":"import argparse\nimport socket\nimport subprocess\nimport time\n\nimport pyroute2\nfrom cryptography.hazmat.primitives import cmac\nfrom cryptography.hazmat.primitives.ciphers import algorithms\nfrom pr2modules.netlink.exceptions import NetlinkError\nfrom pr2modules.netns import popns, pushns\nfrom scapy.fields import IntField, SecondsIntField, XStrLenField\nfrom scapy.layers.inet import UDP\nfrom scapy.main import interact as scapy_interact\nfrom scapy.packet import Packet, bind_layers\n\n\nTEST_PORT = 6500\n\nclass AESCMAC(Packet):\n name = \"AES-CMAC\"\n\n fields_desc = [\n XStrLenField(\"cmac\", default=16*b\"\\x00\", length_from=lambda pkt: 16),\n SecondsIntField(\"time\", default=0, use_nano=True),\n IntField(\"seq\", default=0),\n XStrLenField(\"data\", default=16*b\"\\x00\", length_from=lambda pkt: 16)\n ]\n\n def calc_cmac(self, key: bytes) -> bytes:\n c = cmac.CMAC(algorithms.AES(key))\n c.update(self.data)\n return c.finalize()\n\nbind_layers(UDP, AESCMAC, dport=TEST_PORT)\n\n\nclass Fixture:\n def __init__(self):\n self.ns = None\n self.veth0 = self.veth1 = None\n\n self.ns_name = \"xdp_test\"\n self.veth0_name = \"veth0\"\n self.veth0_ip = \"10.1.0.1\"\n self.veth0_mask = 24\n self.veth1_name = \"veth1\"\n self.veth1_ip = \"10.1.0.2\"\n self.veth1_mask = 24\n\n def create(self):\n ipr = pyroute2.IPRoute()\n self.ns = pyroute2.NetNS(\"xdp_test\")\n\n reuse_veth = False\n try:\n ipr.link(\"add\", ifname=self.veth0_name, kind=\"veth\", peer=self.veth1_name)\n except NetlinkError as e:\n if e.code == 17:\n print(\"Using existing veth pair\")\n reuse_veth = True\n else:\n raise\n\n if reuse_veth:\n self.veth0 = ipr.link_lookup(ifname=self.veth0_name)[0]\n self.veth1 = self.ns.link_lookup(ifname=self.veth1_name)[0]\n\n else:\n self.veth0 = ipr.link_lookup(ifname=self.veth0_name)[0]\n self.veth1 = ipr.link_lookup(ifname=self.veth1_name)[0]\n\n ipr.addr(\"add\", index=self.veth0, address=self.veth0_ip, mask=self.veth0_mask)\n ipr.link(\"set\", index=self.veth0, state=\"up\")\n\n ipr.link(\"set\", index=self.veth1, net_ns_fd=self.ns_name)\n self.ns.addr(\"add\", index=self.veth1, address=self.veth1_ip, mask=self.veth1_mask)\n self.ns.link(\"set\", index=self.veth1, state=\"up\")\n\n # Disable protocol offload\n subprocess.run([\n \"ethtool\", \"--offload\", self.veth0_name, \"rx\", \"off\", \"tx\", \"off\"\n ], check=True, capture_output=True)\n subprocess.run([\n \"ip\", \"netns\", \"exec\", self.ns_name,\n \"ethtool\", \"--offload\", self.veth1_name, \"rx\", \"off\", \"tx\", \"off\"\n ], check=True, capture_output=True)\n\n def destroy(self):\n if self.ns:\n self.ns.close()\n self.ns.remove()\n self.ns = self.veth0 = self.veth1 = None\n\n\ndef test(fixture, receiver, sender):\n dest = (fixture.veth0_ip, TEST_PORT)\n src = None\n sent_msg = recv_msg = None\n\n aes_key = b\"\\x2b\\x7e\\x15\\x16\\x28\\xae\\xd2\\xa6\\xab\\xf7\\x15\\x88\\x09\\xcf\\x4f\\x3c\"\n test_cases = [\n b\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\",\n b\"\\x6b\\xc1\\xbe\\xe2\\x2e\\x40\\x9f\\x96\\xe9\\x3d\\x7e\\x11\\x73\\x93\\x17\\x2a\",\n b\"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\",\n ]\n\n failed = 0\n for seq, data in enumerate(test_cases):\n print(f\"\\n### TEST CASE {seq} ###\")\n\n err = False\n p1 = AESCMAC(seq=seq, data=data)\n\n # Send packet on one interface\n print(\"Sent:\")\n p1.show()\n sent_msg = bytes(p1)\n sender.sendto(sent_msg, dest)\n\n # Receive on the other interface\n while True:\n recv_msg, src = receiver.recvfrom(4096)\n if src[0] == fixture.veth1_ip:\n break\n if len(recv_msg) != len(sent_msg):\n print(\"Received massage has incorrect length!\")\n err = True\n p2 = AESCMAC(recv_msg)\n print(\"Received :\")\n p2.show()\n\n # Check CMAC\n expected = p2.calc_cmac(aes_key)\n if p2.cmac != expected:\n print(f\"Incorrect MAC! Should be 0x{expected.hex()}\")\n err = True\n\n if err:\n failed += 1\n\n if failed > 0:\n print(f\"\\nFAILED: {failed} test cases failed\")\n else:\n print(\"\\nPASSED\")\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Test the XDP program\")\n parser.add_argument(\"-i\", \"--interactive\", action='store_true',\n help=\"Drop into an interactive scapy shell\")\n parser.add_argument(\"-k\", \"--keep\", action='store_true',\n help=\"Do not delete the network namespaces and virtual interfaces after running the tests\")\n args = parser.parse_args()\n\n # Create veth pair\n fixture = Fixture()\n fixture.create()\n\n xdp = receiver = sender = None\n try:\n # Load XDP program\n xdp = subprocess.Popen(\n [\"build/xdp_loader\", \"build/xdp_combined.o\", fixture.veth0_name],\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding=\"utf-8\")\n time.sleep(0.1) # FIXME: Proper synchronization\n if xdp.poll():\n print(\"XDP Loader has failed:\")\n print(xdp.communicate()[0])\n\n # Open UDP sockets\n receiver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n receiver.bind((fixture.veth0_ip, TEST_PORT))\n pushns(fixture.ns_name)\n sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n popns()\n\n if args.interactive:\n scapy_interact(argv=[], mydict=dict(globals(), **locals()))\n else:\n test(fixture, receiver, sender)\n\n finally:\n if receiver:\n receiver.close()\n if sender:\n sender.close()\n if xdp:\n xdp.terminate()\n print(\"XDP Loader returned:\", xdp.wait())\n if not args.keep:\n fixture.destroy()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"netsys-lab/scion-xdp-br","sub_path":"aes/test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":6137,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"1612062596","text":"from pytrends.request import TrendReq\r\n\r\npytrend = TrendReq()\r\nimport pandas as pd\r\n\r\ndata = pd.read_csv('enter path', delimiter=',')\r\ndata = data.drop(data[(data.year < 2004)].index) #cleaning dataset from unnecessary data\r\n\r\ncol = data.columns.tolist()\r\n# d_a_s = data[[col[6],col[1]]]\r\nauthor = data[col[7]].to_list()\r\nsong = data[col[2]].to_list()\r\n\r\npytrends = TrendReq(hl='en-US', tz=360, timeout=(10, 25), proxies=['https://46.151.145.4', ], retries=2,\r\n backoff_factor=0.1)\r\nfor name in author:\r\n l = []\r\n for j in name:\r\n if j == \"\\\\\" or j == \"/\":\r\n name = name.replace(j, \",\")\r\n l.append(name)\r\n kw_list = l\r\n\r\n pytrend.build_payload(kw_list, cat=0, timeframe='2004-12-14 2010-12-25', geo='', gprop='')\r\n\r\n interest_over_time_df = pytrend.interest_over_time()\r\n\r\n interest_over_time_df.to_csv('enter path' % (name)) #extracting data of authors from needed period and saving it to csv file\r\n #then use the same loop just for songs","repo_name":"juliia5m/course_work","sub_path":"extracting_data_from_gt.py","file_name":"extracting_data_from_gt.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"22517631507","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nfrom typing import List\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution1:\n def preorderTraversal(self, root: TreeNode) -> List[int]:\n if root is None:\n return []\n\n res = [root.val, ]\n res.extend(self.preorderTraversal(root.left))\n res.extend(self.preorderTraversal(root.right))\n\n return res\n\n\nclass Solution2:\n def preorderTraversal(self, root: TreeNode) -> List[int]:\n\n if root is None:\n return []\n\n stack = []\n stack.append(root)\n res = []\n while len(stack) > 0:\n # 只要栈还没空就继续处理\n node = stack.pop()\n res.append(node.val)\n if node.right:\n stack.append(node.right)\n if node.left:\n stack.append(node.left)\n\n return res\n\n\nclass Solution3:\n def preorderTraversal(self, root: TreeNode) -> List[int]:\n\n # 特殊情况处理\n if root is None:\n return []\n\n res = []\n p1 = root\n while p1:\n if p1.left is None:\n # 左子树为空,直接记录val并开始右子树处理\n res.append(p1.val)\n p1 = p1.right # 当有回溯连接时,这里穿越的起点!!!\n else:\n p2 = p1.left\n while p2.right and p2.right != p1:\n p2 = p2.right\n # 此时p2为左子树右下叶节点。\n # 在这个算法里,这种右下叶节点p2的右子树只有两种状态的可能\n # 1. None,说明当前处理的树的root节点即p1可以被收割并且开始处理其左子树。同时,为了让左子树处理完成后能够下一步继续处理右子树,把p2的右子连接连到p1上。相当于留一个回溯的路径。这页标志着p1左子树处理的开始。\n # 2. p1,如可能1中所说,当遍历到p2且其右子连接连在p1,标志着p1左子树处理的结束。那么就可以把当时新增的回溯连接拆掉,同时开始处理p1的右子树。\n # 整个算法还是用迭代模拟递归的味道\n\n if p2.right is None: # 上面循环因为 p2.right is None 而跳出\n p2.right = p1\n res.append(p1.val)\n p1 = p1.left\n\n else: # 上面循环因为 p2.right == p1 而跳出\n p2.right = None\n p1 = p1.right\n\n return res\n","repo_name":"ftakanashi/JobProjects","sub_path":"LeetCode/144.二叉树的前序遍历/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"9315859333","text":"import cv2\r\nfrom datetime import datetime\r\n\r\n\r\n\"\"\" capture the smiles \"\"\"\r\ndef smile_detector(frame, gray_frame, face_cascade, smile_cascade, smile_flag, smiles_list, smiles_time):\r\n '''\r\n using haarcascade, this function search for faces in frame \r\n then search for beautiful smiles in faces\r\n and finally take a picture for that frame \r\n and save the time of the happy momment to be a good memory\r\n '''\r\n\r\n faces = face_cascade.detectMultiScale(gray_frame, 1.1, 4)\r\n \r\n for (x, y, w, h) in faces:\r\n cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)\r\n roi_gray = gray_frame[y:y+h, x:x+w]\r\n roi_color = frame[y:y+h, x:x+w]\r\n smiles = smile_cascade.detectMultiScale(roi_gray, 1.2, 15)\r\n\r\n for (xs, ys, ws, hs) in smiles:\r\n smile_flag = 1\r\n cv2.rectangle(roi_color, (xs, ys), (xs+ws, ys+hs), (0, 0, 255), 2)\r\n\r\n smiles_list.append(smile_flag)\r\n\r\n # to save memory\r\n smiles_list = smiles_list[-2:]\r\n\r\n # to save images of each smile when it starts, and save the when\r\n if smiles_list[-1] == 1 and smiles_list[-2] == 0:\r\n cv2.imwrite(f\"out\\\\imgs\\\\smile{datetime.now().strftime(r'%d%m%Y%H%M%S')}.jpg\", frame)\r\n smiles_time.append(datetime.now().strftime(r'%A %d %B %Y %I:%M:%S %p'))\r\n\r\n return smiles_list","repo_name":"tarek0m/Big-Brother-Is-Watching-You","sub_path":"smile_detection.py","file_name":"smile_detection.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"9655219037","text":"def main():\n plate = input(\"Plate: \")\n if is_valid(plate):\n print(\"Valid\")\n else:\n print(\"Invalid\")\n\n\ndef is_valid(s):\n if start_with_2_letters(s) and contain_2_to_6_letters(s) and numbers_at_end(s) and no_symbol(s):\n return True\n else:\n return False\n\n\ndef start_with_2_letters(s):\n if s[0:2].isalpha():\n return True\n else:\n return False\n\n\ndef contain_2_to_6_letters(s):\n if 2 <= len(s) <= 6:\n return True\n else:\n return False\n\n\ndef numbers_at_end(s):\n if s.isalpha():\n return True\n else:\n for i in range(len(s)):\n if s[i].isnumeric():\n if s[i] == \"0\":\n return False\n elif not s[i:len(s)].isnumeric():\n return False\n else:\n return True\n\n\ndef no_symbol(s):\n for char in s:\n if not char.isalnum():\n return False\n return True\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"khaos10/cs50p","sub_path":"2_loops/pset2/plates/plates.py","file_name":"plates.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"45595224965","text":"import sys\nsys.setrecursionlimit(200000)\n\nn,m=map(int,input().split())\n\nparent=[i for i in range(n)]\n\ndef find(x):\n if parent[x] != x:\n parent[x] = find(parent[x])\n return parent[x]\n\ndef union(x,y):\n a=find(x)\n b=find(y)\n\n parent[max(a,b)]=min(a,b)\n\n\nfor turn in range(1,m+1):\n a,b=map(int,sys.stdin.readline().split())\n\n if find(a)==find(b):\n print(turn)\n exit(0)\n else:\n union(a,b)\n\nprint(0)","repo_name":"SeongjinLee00/Baekjoon","sub_path":"백준/Gold/20040. 사이클 게임/사이클 게임.py","file_name":"사이클 게임.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"24695148856","text":"import rtconfig\nfrom building import *\n\ncwd = GetCurrentDir()\nCPPPATH = [cwd, str(Dir('#'))]\nsrc = Split(\"\"\"\nmain.c\n\"\"\")\n\nif GetDepend(['RT_USING_DFS']):\n src += ['mnt.c']\n\ngroup = DefineGroup('Applications', src, depend = [''], CPPPATH = CPPPATH)\n\nReturn('group')\n","repo_name":"vvhh2002/lv7_rtthread_f1c100s","sub_path":"rt-thread/bsp/stm32/stm32f429-atk-apollo/applications/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"77"}
+{"seq_id":"38210922042","text":"#!/usr/bin/env python3\n\nfrom secret import flag\nimport socketserver\nimport hashlib\nimport signal\nimport random\nimport string\nimport os\n\np=20973268502876719886012765513713011996343752519737224550553652605696573094756255499211333096502971357908939298357512380813773140436677393056575164230564778609423872301899323721040416852230597466288892977839300189625522429038289083381035647126860128821615664730513694930502000903655609105029016636999073477487851081722316115785141\nenc=lambda x:pow(17,x,p)\nm=int(flag.encode().hex(),16)\n\ndef gcd(a,b,f=enc):\n if b:\n return gcd(b,a%b,f)\n else:\n return f(a)\n\nclass Task(socketserver.BaseRequestHandler):\n def __init__(self, *args, **kargs):\n super().__init__(*args, **kargs)\n\n def timeout_handler(self, signum, frame):\n self.request.close()\n\n def proof_of_work(self):\n random.seed(os.urandom(8))\n proof = ''.join([random.choice(string.ascii_letters+string.digits) for _ in range(20)])\n _hexdigest = hashlib.sha256(proof.encode()).hexdigest()\n self.request.send(f\"sha256(XXXX+{proof[4:]}) == {_hexdigest}\\n\".encode()+b'Give me XXXX: ')\n x = self.request.recv(1024).strip(b'\\n')\n if len(x) != 4 or hashlib.sha256(x+proof[4:].encode()).hexdigest() != _hexdigest:\n return False\n return True\n\n def handle(self):\n signal.alarm(60)\n\n if not self.proof_of_work():\n return\n\n while True:\n try:\n self.request.send(b'type:')\n t=int(self.request.recv(1024).strip(b'\\n'))\n self.request.send(b'a:')\n a=int(self.request.recv(1024).strip(b'\\n'))\n self.request.send(b'b:')\n b=int(self.request.recv(1024).strip(b'\\n'))\n assert a>0 and b>0\n if t==1:#enc test\n self.request.send(b'%d\\n'%gcd(a,b))\n elif t==2:#leak try1\n self.request.send(b'%d\\n'%gcd(a,m))\n elif t==3:#leak try2\n self.request.send(b'%d\\n'%gcd(a,b,f=lambda x:gcd(x,m)))\n elif t==4:#leak try3\n self.request.send(b'%d\\n'%gcd(a,m,f=lambda x:gcd(x,b)))\n else:\n self.request.close()\n break\n except BrokenPipeError:\n break\n except:\n self.request.send(b'Bad input!\\n')\n\n\nclass ThreadedServer(socketserver.ForkingMixIn, socketserver.TCPServer):\n pass\n\nif __name__ == \"__main__\":\n HOST, PORT = '0.0.0.0', 23333\n server = ThreadedServer((HOST, PORT), Task)\n server.allow_reuse_address = True\n server.serve_forever()","repo_name":"sajjadium/ctf-archives","sub_path":"ctfs/StarCTF/2023/crypto/gcccd/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","stars":490,"dataset":"github-code","pt":"77"}
+{"seq_id":"32809289063","text":"# https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/582/week-4-january-22nd-january-28th/3612/\n\nclass Solution:\n def isOneEditDistance(self, s: str, t: str) -> bool:\n if abs(len(s) - len(t)) > 1 or s == t:\n return False\n if len(s) == len(t):\n c = 0\n for i in range(len(s)):\n c += int(s[i] != t[i])\n if c > 1:\n return False\n return True\n if len(t) > len(s):\n s, t = t, s\n i, j, c = 0, 0, 0\n while i < len(s) and j < len(t):\n if s[i] != t[j]:\n c += 1\n if c > 1:\n return False\n i += 1\n else:\n i += 1\n j += 1\n return True\n","repo_name":"rmodi6/scripts","sub_path":"practice/Leetcode/3612_one_edit_distance.py","file_name":"3612_one_edit_distance.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"29299105489","text":"pt=input(\"PT:\")\npi=input(\"PI:\")\nne=input(\"NE:\")\npp=input(\"PP:\")\npt=float(pt)\npi=float(pi)\nne=float(ne)\npp=float(pp)\npf=round(0.3*pt+0.3*pi+0.3*ne+0.1*pp,1)\nprint()\nprint(\"El promedio final es\",pf)","repo_name":"pabloschwarzenberg/grader","sub_path":"hito1_ej1/hito1_ej1_e74c99a15878aef5b5fdddd8f394f1f1.py","file_name":"hito1_ej1_e74c99a15878aef5b5fdddd8f394f1f1.py","file_ext":"py","file_size_in_byte":196,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"8514707504","text":"from django.shortcuts import get_object_or_404\nfrom django import forms\nfrom django.forms import ModelForm\n\nfrom Loans.models import Loan, Sector, Record, SalesRecord, Requirement\n\n\nclass CreateLoanForm(ModelForm):\n sectors = forms.ModelMultipleChoiceField(\n queryset=Sector.objects.all(),\n widget=forms.CheckboxSelectMultiple\n\n )\n requirements = forms.ModelMultipleChoiceField(\n queryset=Requirement.objects.all(),\n widget=forms.CheckboxSelectMultiple\n\n )\n\n class Meta:\n model = Loan\n fields = [\"program_title\", \"size\", \"sectors\", \"amount\", \"amount\",\n \"paying_days\", \"grace_period\",\n \"collateral\", \"requirements\"]\n\n\nclass AddRecordForm(ModelForm):\n class Meta:\n model = Record\n fields = ['amount', 'category']\n\n def __init__(self, *args, **kwargs):\n super(AddRecordForm, self).__init__(*args, **kwargs)\n self.fields['amount'].widget.attrs['class'] = 'form-input'\n self.fields['category'].widget.attrs['class'] = 'form-input'\n\n def clean_amount(self):\n if self.cleaned_data['amount'] <= 0:\n self.add_error('amount', 'The field \"Amount\" should be greater than 0.')\n else:\n return self.cleaned_data['amount']\n\n\nclass AddSalesRecordForm(ModelForm):\n class Meta:\n model = SalesRecord\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(AddSalesRecordForm, self).__init__(*args, **kwargs)\n self.fields[\"item_name\"].widget.attrs['class'] = 'form-input'\n self.fields[\"quantity\"].widget.attrs['class'] = 'form-input'\n self.fields[\"cost_price_per_item\"].widget.attrs['class'] = 'form-input'\n self.fields[\"selling_price_per_item\"].widget.attrs['class'] = 'form-input'\n\n def clean_amount(self):\n if self.cleaned_data['cost_price_per_item'] <= 0:\n self.add_error('cost_price_per_item', 'The field \"Cost Price\" should be greater than 0.')\n else:\n return self.cleaned_data['cost_price_per_item']\n\n if self.cleaned_data['selling_price_per_item'] <= 0:\n self.add_error('selling_price_per_item', 'The field \"Selling Price\" should be greater than 0.')\n else:\n return self.cleaned_data['selling_price_per_item']\n\n\nclass ApplyLoanForm(forms.Form):\n def __init__(self, user, loan_id, *args, **kwargs):\n print(\"the_uuser\", user)\n print(\"loan_id\", loan_id)\n super(ApplyLoanForm, self).__init__(*args, **kwargs)\n self.fields['address'].widget.attrs['class'] = 'address'\n self.fields['bvn'].widget.attrs['bvn'] = 'form-input'\n self.fields['nin'].widget.attrs['nin'] = 'form-input'\n self.fields['business_certificate'].widget.attrs['business_certificate'] = 'form-input'\n self.fields['financial_record'].widget.attrs['financial_record'] = 'form-input'\n self.fields['number_of_employee'].widget.attrs['number_of_employee'] = 'form-input'\n\n loan = get_object_or_404(Loan, id=int(loan_id))\n counter = 0\n # print(loan.requirements.all())\n for requirement in loan.requirements.all():\n print(getattr(user, requirement.requirement), requirement.requirement)\n if getattr(user, requirement.requirement):\n del self.fields[requirement.requirement]\n # print(self.fields)\n counter += 1\n copy_fields = self.fields.copy().keys()\n for key in copy_fields:\n if key not in [n.requirement for n in loan.requirements.all()]:\n del self.fields[key]\n print(\"nazo nan\")\n if counter >= 7:\n print('none')\n return None\n\n address = forms.CharField(max_length=11)\n bvn = forms.IntegerField(help_text=\"input your bvn\")\n nin = forms.CharField(max_length=11)\n business_certificate = forms.FileField()\n financial_record = forms.FileField()\n time_in_business = forms.IntegerField()\n number_of_employee = forms.IntegerField()\n","repo_name":"Bukharee/Lamuni","sub_path":"Loans/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4037,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"31834481545","text":"#!/usr/bin/env python3\nfrom pwn import *\n\ncontext.log_level = 'debug'\ncontext.terminal = ['tmux', 'split', '-h']\n\nelf = ELF('./pwn_patched')\nlibc = ELF('./libc-2.31.so')\nld = ELF('./ld-2.31.so')\n\ncontext.binary = elf\n\nENCODING = 'ISO-8859-1'\ns = lambda senddata : p.send(senddata.encode(ENCODING))\nsa = lambda recvdata, senddata : p.sendafter(recvdata.encode(ENCODING), senddata.encode(ENCODING))\nsl = lambda senddata : p.sendline(senddata.encode(ENCODING))\nsla = lambda recvdata, senddata : p.sendlineafter(recvdata.encode(ENCODING), senddata.encode(ENCODING))\nr = lambda numb=0x3f3f3f3f, timeout=0x3f3f3f3f : p.recv(numb, timeout=timeout).decode(ENCODING)\nru = lambda recvdata, timeout=0x3f3f3f3f : p.recvuntil(recvdata.encode(ENCODING), timeout=timeout).decode(ENCODING)\nuu32 = lambda data : u32(data.encode(ENCODING), signed='unsigned')\nuu64 = lambda data : u64(data.encode(ENCODING), signed='unsigned')\niu32 = lambda data : u32(data.encode(ENCODING), signed='signed')\niu64 = lambda data : u64(data.encode(ENCODING), signed='signed')\nup32 = lambda data : p32(data, signed='unsigned').decode(ENCODING)\nup64 = lambda data : p64(data, signed='unsigned').decode(ENCODING)\nip32 = lambda data : p32(data, signed='signed').decode(ENCODING)\nip64 = lambda data : p64(data, signed='signed').decode(ENCODING)\n\nlocal = 1\nif local:\n p = process([elf.path])\nelse:\n p = remote('localhost', 8888)\n\nbss_buf = 0x404050\n# 0x0000000000401111 : pop rdx ; pop rcx ; add rcx, 0x3ef2 ; bextr rbx, rcx, rdx ; ret\nbextr_ret = 0x0000000000401111\n# 0x00000000004010a5 : xlatb ; ret\nxlatb_ret = 0x00000000004010a5\n# 0x00000000004010d1 : stosb byte ptr [rdi], al ; ret\nstosb_ret = 0x00000000004010d1\ncall_orw = 0x0000000000401165\npop_rdi_ret = 0x00000000004011f3\n\ndef set_rbx_to_addr(target_addr):\n payload = ''\n rdx = (0x40 << 8) | 0x0 # rcx: len 0x40 | len 0x0\n rcx = target_addr\n payload += up64(bextr_ret)\n payload += up64(rdx)\n payload += up64(rcx - 0x3ef2) # add rcx, 0x3ef2\n return payload\n\ndef set_al_to_byte(target, real_time_al):\n target_byte_addr = next(elf.search(target.encode(ENCODING)))\n target_rbx = target_byte_addr - real_time_al\n payload = set_rbx_to_addr(target_rbx)\n payload += up64(xlatb_ret) # xlatb ; --> al = [rbx+al]\n return payload\n\ntarget = '\\x0b' + 'flag.txt'\npayload = ''\npayload += up64(pop_rdi_ret) + up64(bss_buf)\nfor i in range(len(target) - 1):\n payload += set_al_to_byte(target[i + 1], ord(target[i])) + up64(stosb_ret)\npayload += up64(pop_rdi_ret) + up64(bss_buf) + up64(call_orw)\nassert len(payload) <= 0x200 - 0x32\ngdb.attach(p)\nsa('> ', 'A' * 0x20 + 'B' * 8 + payload)\n\np.interactive()\n\n","repo_name":"r4b3rt/writeups","sub_path":"ZJUCTF-2022/easy_overflow/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"8577239136","text":"from django.urls import path\nfrom .views import register, login,logout_view\nfrom .views import GlossaryRetrieveUpdateDeleteView, GlossaryListCreateView\n\nurlpatterns = [\n path('register/', register, name='register'),\n path('login/', login, name='login'),\n path('logout/', logout_view, name='logout'),\n path('glossaries/', GlossaryListCreateView.as_view(), name='glossary-list-create'),\n path('glossary//', GlossaryRetrieveUpdateDeleteView.as_view(), name='glossary-retrieve'),\n]\n","repo_name":"PhannCheat/Django-learning","sub_path":"Api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"39401435455","text":"\"\"\"\nItems within the game include pellets (coins) and powerups \n\n pydoc -w item\n\n\"\"\"\n\nimport pygame\nfrom settings import Settings\nfrom enemy_class import Enemy\n\n\nclass Item:\n \"\"\"\n Provides attributes and methods for all item objects within Pacman game.\n These items include pellets (coins) for points and powerups for killing ghost enemies\n\n \"\"\"\n def __init__(self, app, item_type, location):\n self.setting = Settings()\n self.app = app\n self.type = item_type\n self.location = location\n\n \n def draw(self):\n \"\"\"\n Depending on which type of item this function draws the relevent circle item using Pygame function draw.circle()\n \"\"\"\n if self.type == \"coin\":\n pygame.draw.circle(self.app.screen, self.setting.GREY,\n (int(self.location.x*self.app.cell_width)+self.app.cell_width//2+self.setting.TOP_BOTTOM_BUFFER//2,\n int(self.location.y*self.app.cell_height)+self.app.cell_height//2+self.setting.TOP_BOTTOM_BUFFER//2), 2)\n elif self.type == \"power\":\n pygame.draw.circle(self.app.screen, self.setting.WHITE,\n (int(self.location.x*self.app.cell_width)+self.app.cell_width//2+self.setting.TOP_BOTTOM_BUFFER//2,\n int(self.location.y*self.app.cell_height)+self.app.cell_height//2+self.setting.TOP_BOTTOM_BUFFER//2), 4)\n\n \n def eat_coin(self, index):\n \"\"\"\n Function controls events after pellet (coin) is collided with by player\n \"\"\"\n self.app.coins.pop(index)\n self.app.current_score += 10\n\n\n def absorb_powerup(self, index):\n \"\"\"\n Function controls the changes made upon a player colliding with a powerup\n \"\"\"\n self.app.powerups.pop(index)\n self.app.current_score += 50\n for enemy in self.app.enemies:\n enemy.change_state(\"scatter\")","repo_name":"cburrowsXXIII/PacmanEmulator","sub_path":"item_class.py","file_name":"item_class.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"27449528621","text":"N = int(input())\nXY = [tuple([int(_) for _ in input().split()]) for i in range(N)]\n\nif N == 1:\n\n result = 1\n\nelse:\n\n XY.sort()\n\n dxy = [\n (XY[i][0] - XY[j][0], XY[i][1] - XY[j][1])\n for i in range(N)\n for j in range(i + 1, N)\n ]\n\n from collections import Counter\n\n cdxy = Counter(dxy)\n\n m = max(cdxy.values())\n\n #print(XY)\n #print(dxy)\n #print(cdxy)\n\n result = N - m\n\nprint(result)\n","repo_name":"hirosuzuki/procon","sub_path":"atcoder/diverta2019-2/diverta2019_2_b.py","file_name":"diverta2019_2_b.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"11738814960","text":"import csv\nimport os\n\nfrom unidecode import unidecode\n\nos.chdir('scripts')\nfrom .new_corpus import Data\n\n\nclass TSV_Writer:\n\n @staticmethod\n def _normalize(k, s):\n line = str(s)\n line = unidecode(line)\n return line\n\n @staticmethod\n def write_tsv(json_data, file):\n keys = list(sorted({k for row in json_data for k in row}))\n with open(file, 'w+', encoding='utf8', newline='') as f:\n tsv_writer = csv.writer(f, delimiter='\\t')\n tsv_writer.writerow([k for k in keys])\n for j, row in enumerate(json_data):\n tsv_writer.writerow([TSV_Writer._normalize(k, row[k]) if k in row else '' for k in keys])\n\n\ndef main():\n\n data = Data(save_sent=True, save_ptok=True, missing_ss_error=True, missing_con_error=True, missing_adp_error=True, missing_us_error=True)\n\n output_dir = f'{data.corpus_name}{data.corpus_version}_files'\n\n data.load_data(data.data_file)\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n # output CorpusSentences\n print('corpus_sentences.json', len(data.corpus_sentences))\n file = os.path.join(output_dir, 'corpus_sentences.tsv')\n TSV_Writer.write_tsv(data.corpus_sentences, file)\n\n # output PTokenAnnotations\n # split ptokens json into multiple files of a particular size\n PER_FILE = 1500\n if data.ptoken_annotations:\n for i in range(int(len(data.ptoken_annotations) / PER_FILE)):\n file = os.path.join(output_dir, f'ptoken_annotations{i}.tsv')\n print(file, i * PER_FILE, '-', (i + 1) * PER_FILE - 1)\n TSV_Writer.write_tsv(data.ptoken_annotations[i * PER_FILE:(i + 1) * PER_FILE], file)\n\n i = int(len(data.ptoken_annotations) / PER_FILE)\n file = os.path.join(output_dir, f'ptoken_annotations{i}.tsv')\n print(file, i * PER_FILE, '-', len(data.ptoken_annotations) - 1)\n TSV_Writer.write_tsv(data.ptoken_annotations[i * PER_FILE:], file)\n\n else:\n raise Exception('No PTokenAnnotations found. Please make sure all Usages and CorpusSentences have been imported or exist.')\n\n\n unique_sent_and_tokens = set()\n for p in data.ptoken_annotations:\n sent_and_tokens = p['sent_id']+' '+str(p['token_indices'])\n if sent_and_tokens in unique_sent_and_tokens:\n sent_id = p['sent_id']\n token_indices = str(p['token_indices'])\n raise Exception(f'Unique Constraint Failure: sent_id \"{sent_id}\" and token_indices \"{token_indices}\"')\n else:\n unique_sent_and_tokens.add(sent_and_tokens)\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"nert-nlp/Xposition","sub_path":"xposition/scripts/generate_corpus_files.py","file_name":"generate_corpus_files.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"4533749563","text":"import habitat_sim\nimport habitat\nfrom habitat.config.default import get_config\nfrom PIL import Image\nfrom habitat_sim.utils.common import d3_40_colors_rgb\n\nimport cv2\n\nimport random\n#%matplotlib inline\nimport matplotlib.pyplot as plt\nplt.figure(figsize=(12 ,8))\nimport time\nimport numpy as np\nimport ipdb\nst = ipdb.set_trace\nimport os \nimport sys\nimport pickle\nimport json\n\n\nclass AutomatedMultiview():\n def __init__(self):\n mapname = \"apartment_0/\"\n self.test_scene = \"/hdd/replica/Replica-Dataset/out/{}/habitat/mesh_semantic.ply\".format(mapname)\n self.object_json = \"/hdd/replica/Replica-Dataset/out/{}/habitat/info_semantic.json\".format(mapname)\n self.sim_settings = {\n \"width\": 256, # Spatial resolution of the observations\n \"height\": 256,\n \"scene\": self.test_scene, # Scene path\n \"default_agent\": 0,\n \"sensor_height\": 1.5, # Height of sensors in meters\n \"color_sensor\": True, # RGB sensor\n \"semantic_sensor\": True, # Semantic sensor\n \"depth_sensor\": True, # Depth sensor\n \"seed\": 1,\n }\n self.DONOTHING_KEY=\"r\"\n self.FORWARD_KEY=\"w\"\n self.LEFT_KEY=\"a\"\n self.RIGHT_KEY=\"d\"\n self.FINISH=\"f\"\n self.SAVE = \"o\"\n self.UP = \"u\"\n self.DOWN = \"l\"\n self.QUIT = \"q\"\n\n self.basepath = \"/hdd/habitat_scenes_data_automated\"\n self.ignore_classes = ['book','base-cabinet','beam','blanket','blinds','cloth','clothing','coaster','comforter','curtain','ceiling','countertop','floor','handrail','mat','paper-towel','picture','pillar','pipe','scarf','shower-stall','switch','tissue-paper','towel','vent','wall','wall-plug','window','rug','logo','set-of-clothing']\n self.rot_interval = 20.\n self.distance_thresh = 2.0\n self.num_flat_views = 3\n self.num_any_views = 7\n # self.env = habitat.Env(config=config, dataset=None)\n cfg = self.make_cfg(self.sim_settings)\n self.sim = habitat_sim.Simulator(cfg)\n random.seed(self.sim_settings[\"seed\"])\n self.sim.seed(self.sim_settings[\"seed\"])\n self.set_agent(self.sim_settings)\n self.nav_pts = self.get_navigable_points()\n \n # self.test_navigable_points()\n self.run()\n\n def set_agent(self, sim_settings):\n agent = self.sim.initialize_agent(sim_settings[\"default_agent\"])\n agent_state = habitat_sim.AgentState()\n agent_state.position = np.array([1.5, 1.072447, 0.0])\n #agent_state.position = np.array([1.0, 3.0, 1.0])\n agent.set_state(agent_state)\n agent_state = agent.get_state()\n print(\"agent_state: position\", agent_state.position, \"rotation\", agent_state.rotation)\n self.agent = agent\n\n def make_cfg(self, settings):\n sim_cfg = habitat_sim.SimulatorConfiguration()\n sim_cfg.gpu_device_id = 0\n sim_cfg.scene.id = settings[\"scene\"]\n\n # Note: all sensors must have the same resolution\n sensors = {\n \"color_sensor\": {\n \"sensor_type\": habitat_sim.SensorType.COLOR,\n \"resolution\": [settings[\"height\"], settings[\"width\"]],\n \"position\": [0.0, settings[\"sensor_height\"], 0.0],\n },\n \"depth_sensor\": {\n \"sensor_type\": habitat_sim.SensorType.DEPTH,\n \"resolution\": [settings[\"height\"], settings[\"width\"]],\n \"position\": [0.0, settings[\"sensor_height\"], 0.0],\n },\n \"semantic_sensor\": {\n \"sensor_type\": habitat_sim.SensorType.SEMANTIC,\n \"resolution\": [settings[\"height\"], settings[\"width\"]],\n \"position\": [0.0, settings[\"sensor_height\"], 0.0],\n },\n }\n\n sensor_specs = []\n for sensor_uuid, sensor_params in sensors.items():\n if settings[sensor_uuid]:\n sensor_spec = habitat_sim.SensorSpec()\n sensor_spec.uuid = sensor_uuid\n sensor_spec.sensor_type = sensor_params[\"sensor_type\"]\n sensor_spec.resolution = sensor_params[\"resolution\"]\n sensor_spec.position = sensor_params[\"position\"]\n\n sensor_specs.append(sensor_spec)\n\n # Here you can specify the amount of displacement in a forward action and the turn angle\n agent_cfg = habitat_sim.agent.AgentConfiguration()\n agent_cfg.sensor_specifications = sensor_specs\n agent_cfg.action_space = {\n \"do_nothing\": habitat_sim.agent.ActionSpec(\n \"move_forward\", habitat_sim.agent.ActuationSpec(amount=0.)\n ),\n \"move_forward\": habitat_sim.agent.ActionSpec(\n \"move_forward\", habitat_sim.agent.ActuationSpec(amount=0.25)\n ),\n \"turn_left\": habitat_sim.agent.ActionSpec(\n \"turn_left\", habitat_sim.agent.ActuationSpec(amount=self.rot_interval)\n ),\n \"turn_right\": habitat_sim.agent.ActionSpec(\n \"turn_right\", habitat_sim.agent.ActuationSpec(amount=self.rot_interval)\n ),\n \"look_up\":habitat_sim.ActionSpec(\n \"look_up\", habitat_sim.ActuationSpec(amount=self.rot_interval)\n ),\n \"look_down\":habitat_sim.ActionSpec(\n \"look_down\", habitat_sim.ActuationSpec(amount=self.rot_interval)\n ),\n \"look_down_init\":habitat_sim.ActionSpec(\n \"look_down\", habitat_sim.ActuationSpec(amount=100.0)\n )\n }\n\n return habitat_sim.Configuration(sim_cfg, [agent_cfg])\n \n\n def display_sample(self, rgb_obs, semantic_obs, depth_obs, visualize=False):\n rgb_img = Image.fromarray(rgb_obs, mode=\"RGBA\")\n\n semantic_img = Image.new(\"P\", (semantic_obs.shape[1], semantic_obs.shape[0]))\n semantic_img.putpalette(d3_40_colors_rgb.flatten())\n semantic_img.putdata((semantic_obs.flatten() % 40).astype(np.uint8))\n semantic_img = semantic_img.convert(\"RGBA\")\n # st()\n \n \n depth_img = Image.fromarray((depth_obs / 10 * 255).astype(np.uint8), mode=\"L\")\n\n display_img = cv2.cvtColor(np.asarray(rgb_img), cv2.COLOR_RGB2BGR)\n\n #display_img = cv2.\n cv2.imshow('img',display_img)\n if visualize:\n arr = [rgb_img, semantic_img, depth_img]\n titles = ['rgb', 'semantic', 'depth']\n plt.figure(figsize=(12 ,8))\n for i, data in enumerate(arr):\n ax = plt.subplot(1, 3, i+1)\n ax.axis('off')\n ax.set_title(titles[i])\n plt.imshow(data)\n # plt.pause()\n plt.show()\n plt.pause(0.5)\n # cv2.imshow()\n plt.close()\n\n\n def save_datapoint(self, agent, observations, data_path, viewnum, mainobj_id, flat_view):\n \n print(\"Print Sensor States.\", self.agent.state.sensor_states)\n rgb = observations[\"color_sensor\"]\n semantic = observations[\"semantic_sensor\"]\n \n # Extract objects from instance segmentation\n object_list = []\n obj_ids = np.unique(semantic[30:230, 30:230])\n print(\"Unique semantic ids: \", obj_ids)\n\n # st()\n for obj_id in obj_ids:\n if obj_id < 1 or obj_id > len(self.sim.semantic_scene.objects):\n continue\n if self.sim.semantic_scene.objects[obj_id] == None:\n continue\n if self.sim.semantic_scene.objects[obj_id].category == None:\n continue\n try:\n class_name = self.sim.semantic_scene.objects[obj_id].category.name()\n print(\"Class name is : \", class_name)\n except Exception as e:\n print(e)\n st()\n print(\"done\")\n if class_name not in self.ignore_classes:\n obj_instance = self.sim.semantic_scene.objects[obj_id]\n # print(\"Object name {}, Object category id {}, Object instance id {}\".format(class_name, obj_instance['id'], obj_instance['class_id']))\n\n obj_data = {'instance_id': obj_id, 'category_id': obj_instance.category.index(), 'category_name': obj_instance.category.name(), 'bbox_center': obj_instance.obb.to_aabb().center, 'bbox_size': obj_instance.obb.to_aabb().sizes}\n # object_list.append(obj_instance)\n object_list.append(obj_data)\n\n # st()\n depth = observations[\"depth_sensor\"]\n # self.display_sample(rgb, semantic, depth, visualize=True)\n agent_pos = agent.state.position\n agent_rot = agent.state.rotation\n # Assuming all sensors have same extrinsics\n color_sensor_pos = agent.state.sensor_states['color_sensor'].position\n color_sensor_rot = agent.state.sensor_states['color_sensor'].rotation\n save_data = {'flat_view': flat_view, 'mainobj_id': mainobj_id, 'objects_info': object_list,'rgb_camX':rgb, 'depth_camX': depth, 'semantic_camX': semantic, 'agent_pos':agent_pos, 'agent_rot': agent_rot, 'sensor_pos': color_sensor_pos, 'sensor_rot': color_sensor_rot}\n \n with open(os.path.join(data_path, str(viewnum) + \".p\"), 'wb') as f:\n pickle.dump(save_data, f)\n\n\n def is_valid_datapoint(self, observations, mainobj):\n main_id = int(mainobj.id[1:])\n semantic = observations[\"semantic_sensor\"]\n # st()\n num_occ_pixels = np.where(semantic == main_id)[0].shape[0]\n if num_occ_pixels > 1000:\n return True\n return False\n\n def run(self):\n\n scene = self.sim.semantic_scene\n objects = scene.objects\n for obj in objects:\n if obj == None or obj.category == None or obj.category.name() in self.ignore_classes:\n continue\n # st()\n print(f\"Object name is: {obj.category.name()}\")\n obj_center = obj.obb.to_aabb().center\n obj_center = np.expand_dims(obj_center, axis=0)\n distances = np.sqrt(np.sum((self.nav_pts - obj_center)**2, axis=1))\n # st()\n\n closest_navpts = self.nav_pts[np.where(distances= self.num_flat_views and len(any_views) >= self.num_any_views:\n data_folder = obj.category.name() + '_' + obj.id\n data_path = os.path.join(self.basepath, data_folder)\n os.mkdir(data_path)\n flat_obs = np.random.choice(flat_views, self.num_flat_views, replace=False)\n any_obs = np.random.choice(any_views, self.num_any_views, replace=False)\n viewnum = 0\n for obs in flat_obs:\n self.save_datapoint(self.agent, obs, data_path, viewnum, obj.id, True)\n viewnum += 1\n \n for obs in any_obs:\n self.save_datapoint(self.agent, obs, data_path, viewnum, obj.id, False)\n viewnum += 1\n\n def get_navigable_points(self):\n navigable_points = np.array([0,0,0])\n for i in range(20000):\n navigable_points = np.vstack((navigable_points,self.sim.pathfinder.get_random_navigable_point()))\n return navigable_points\n \n def plot_navigable_points(self, points):\n # print(points)\n x_sample = points[:,0]\n z_sample = points[:,2]\n plt.plot(z_sample, x_sample, 'o', color = 'red')\n plt.show()\n\n # # Just visualize the scene from different navigable points\n # def test_navigable_points(self):\n \n # action = \"move_forward\"\n # for pts in self.nav_pts:\n # keystroke = cv2.waitKey(0)\n # print(\"keystroke: \", keystroke)\n # print(\"Launch position is: \", pts)\n # agent_state = habitat_sim.AgentState()\n # agent_state.position = pts\n # self.agent.set_state(agent_state)\n # observations = self.sim.step(action)\n # rgb = observations[\"color_sensor\"]\n # semantic = observations[\"semantic_sensor\"]\n # depth = observations[\"depth_sensor\"]\n # self.display_sample(rgb, semantic, depth)\n\n # # Test whether we actually spawn near given object when we select navigable point near it.\n # def test_navigable_point_for_single_obj(self):\n # scene = self.sim.semantic_scene\n # objects = scene.objects\n # for obj in objects:\n # if obj == None or obj.category == None:\n # continue\n # print(f\"Object name is: {obj.category.name()}\")\n\n # if obj.category.name() == \"bathtub\":\n # obj_center = obj.obb.to_aabb().center\n # obj_center = np.expand_dims(obj_center, axis=0)\n # distances = np.sqrt(np.sum((self.nav_pts - obj_center)**2, axis=1))\n # closest_navpt = self.nav_pts[distances.argmin()]\n # action = \"move_forward\"\n # print(\"Launch position is: \", closest_navpt)\n # agent_state = habitat_sim.AgentState()\n # agent_state.position = closest_navpt\n # self.agent.set_state(agent_state)\n # while True:\n \n # observations = self.sim.step(action)\n # rgb = observations[\"color_sensor\"]\n # semantic = observations[\"semantic_sensor\"]\n # depth = observations[\"depth_sensor\"]\n # self.display_sample(rgb, semantic, depth)\n # keystroke = cv2.waitKey(0)\n # print(\"keystroke: \", keystroke)\n\n # if( 255!=keystroke and keystroke!=(-1) ): \n \n # if keystroke == ord(self.DONOTHING_KEY):\n # action = \"do_nothing\"\n # print(\"action: DONOTHING\")\n # elif keystroke == ord(self.FORWARD_KEY):\n # action = \"move_forward\"\n # print(\"action: FORWARD\")\n # elif keystroke == ord(self.LEFT_KEY):\n # action = \"turn_left\"\n # print(\"action: LEFT\")\n # elif keystroke == ord(self.RIGHT_KEY):\n # action = \"turn_right\"\n # print(\"action: RIGHT\")\n # elif keystroke == ord(self.FINISH):\n # action = \"turn_right\"\n # print(\"action: FINISH\")\n # exit(1)\n # elif keystroke == ord(self.SAVE):\n # action = \"save_data\"\n # print(\"action: SAVE\")\n # elif keystroke == ord(self.UP):\n # action = \"look_up\"\n # print(\"action: look up\")\n # elif keystroke == ord(self.DOWN):\n # action = \"look_down\"\n # print(\"action: look down\")\n # else:\n # print(\"INVALID KEY\")\n # continue\n\n\n\nif __name__ == '__main__':\n AutomatedMultiview()\n","repo_name":"shamitlal/HabitatScripts","sub_path":"sim_automated_multiview.py","file_name":"sim_automated_multiview.py","file_ext":"py","file_size_in_byte":17120,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"72628363768","text":"import sys\nimport math\nfrom collections import defaultdict\nfrom random import random\n\n\nclass Entity(object):\n def __init__(self, eid, owner):\n self.eid = eid\n self.owner = owner\n\n\nclass Factory(Entity):\n def __init__(self, eid, owner, cyborgs, production, arg4, arg5):\n super().__init__(eid, owner)\n self.cyborgs = cyborgs\n self.production = production\n\n\nclass Troop(Entity):\n def __init__(self, eid, owner, factory_from, factory_to, size, eta):\n super().__init__(eid, owner)\n self.factory_from = factory_from\n self.factory_to = factory_to\n self.size = size\n self.eta = eta\n\n\ndef assess_factory_1(f1):\n f1_troops_delta = sum([t.size for t in troops if t.owner != 1 and t.factory_to == f1.eid]) - \\\n sum([t.size for t in troops if t.owner == 1 and t.factory_to == f1.eid])\n for f2 in sorted(factor, key=lambda k: k.production * 10 / distances[f1.eid][k.eid]):\n f2_troops_delta = sum([t.size for t in troops if t.owner != 1 and t.factory_to == f2.eid]) - \\\n sum([t.size for t in troops if t.owner == 1 and t.factory_to == f2.eid])\n if f1 != f2 and f2.owner != 1:\n if (f2.cyborgs + f2_troops_delta < f1.cyborgs - f1_troops_delta\n and f2.production > 0\n and f1.cyborgs > 10\n and f2.cyborgs > f2_troops_delta\n and f1.cyborgs > f1_troops_delta):\n print(f1.cyborgs, f2.cyborgs, file=sys.stderr)\n f1_cyborgs_send = f1.cyborgs - f1_troops_delta - 1\n f1.cyborgs -= f1_cyborgs_send\n return ' '.join([\"MOVE\", str(f1.eid), str(f2.eid), str(f1_cyborgs_send)])\n elif f2.owner == 1 and f2_troops_delta < 0 < f1_troops_delta:\n f1_cyborgs_send = -f2_troops_delta + 1\n f1.cyborgs -= f1_cyborgs_send\n return ' '.join([\"MOVE\", str(f1.eid), str(f2.eid), str(f1_cyborgs_send)])\n return None\n\n\ndef get_dests(f1, factor):\n dests = []\n for f in factor:\n if f == f1 or f.eid not in distances[f1.eid]:\n continue\n for _ in range((f.production * f.production * (3 - f.owner)) +\n int(len(distances[f.eid]) / 4) + int(3 / distances[f1.eid][f.eid])):\n dests.append(f.eid)\n return dests\n\n\ndef assess_factory_2(f1):\n dests = get_dests(f1, factor)\n if not dests:\n return None\n send_to = dests[int(random()*len(dests))]\n f2 = [f for f in factor if f.eid == send_to][0]\n if f2.owner == -1 and f2.production > 1 and f2.cyborgs > 10 and bomb_count[0] < 2:\n bomb_count[0] += 1\n return ' '.join(str(s) for s in [\"BOMB\", f1.eid, send_to])\n if f2.owner == 0 and f1.cyborgs > f2.cyborgs + 1:\n return ' '.join(str(s) for s in [\"MOVE\", f1.eid, send_to, f2.cyborgs + 1])\n if f1.production > 0 and f1.cyborgs > f2.production:\n # send out all produced cyborgs to random target\n return ' '.join(str(s) for s in [\"MOVE\", f1.eid, send_to, f2.production + int(f1.cyborgs/10)])\n if f1.production == 0:\n return ' '.join(str(s) for s in [\"MOVE\", f1.eid, send_to, f1.cyborgs])\n return None\n\n# Auto-generated code below aims at helping you parse\n# the standard input according to the problem statement.\n\n\nfactory_count = int(input()) # the number of factories\nlink_count = int(input()) # the number of links between factories\ndistances = defaultdict(dict)\nfor _ in range(link_count):\n factory_1, factory_2, distance = [int(j) for j in input().split()]\n distances[factory_1][factory_2] = distance\n distances[factory_2][factory_1] = distance\n print(factory_1, factory_2, distance, file=sys.stderr)\n\n# game loop\nbomb_count = [0]\nwhile True:\n factor = []\n troops = []\n entity_count = int(input()) # the number of entities (e.g. factories and troops)\n for _ in range(entity_count):\n eid, etype, arg_1, arg_2, arg_3, arg_4, arg_5 = input().split()\n if etype == 'FACTORY':\n factor.append(Factory(int(eid), int(arg_1), int(arg_2), int(arg_3), int(arg_4), int(arg_5)))\n if etype == 'TROOP':\n troops.append(Troop(int(eid), int(arg_1), int(arg_2), int(arg_3), int(arg_4), int(arg_5)))\n\n orders = []\n for f1 in factor:\n if f1.owner == 1:\n order = assess_factory_2(f1)\n if order:\n orders.append(order)\n # osort = sorted(order, key=lambda k: order[k]['value'] + order[k]['cost'])\n # print([(fid, order[fid]) for fid in osort], file=sys.stderr)\n # print(\"MOVE\", f1.eid, osort[0], f1.cyborgs + order[osort[0]]['cost'])\n if orders:\n print('; '.join(orders))\n else:\n print('WAIT')\n","repo_name":"adlerpriit/Codingame","sub_path":"GhostInCell/GiC.py","file_name":"GiC.py","file_ext":"py","file_size_in_byte":4741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"23257491913","text":"#!/usr/bin/env python\nfrom __future__ import print_function, division, unicode_literals\nimport os\nimport errno\nfrom astropy.io import fits\nimport sys\n\n\ndef force_link(file1, file2):\n try:\n os.link(file1, file2)\n except OSError as e:\n if e.errno == errno.EEXIST:\n os.remove(file2)\n os.link(file1, file2)\n\n\ndef main(args=None):\n if args is None:\n args = sys.argv\n if args is None:\n sys.exit(\"copy_spectra input_file.ext outroot\")\n fname = args[1]\n outroot = args[2]\n\n dirname, basename = os.path.split(fname)\n\n paths_to_modify = ['BACKFILE', 'RESPFILE', 'ANCRFILE']\n suffixes = {'BACKFILE': '_back', 'RESPFILE': '', 'ANCRFILE': ''}\n\n hdulist = fits.open(fname)\n\n for p in paths_to_modify:\n name = hdulist[1].header[p]\n complete_name = os.path.join(dirname, name)\n\n base, extension = os.path.splitext(name)\n\n newname = outroot + suffixes[p] + extension\n force_link(complete_name, newname)\n\n hdulist[1].header[p] = newname\n\n base, extension = os.path.splitext(basename)\n hdulist.writeto(outroot + extension, clobber=True)\n","repo_name":"matteobachetti/fits_utils","sub_path":"fits_utils/copy_spectra.py","file_name":"copy_spectra.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"44709050244","text":"# ____ _____\n# ________ _________ ____ / __ \\/ ___/\n# / ___/ _ \\/ ___/ __ \\/ __ \\/ / / /\\__ \\\n# / / / __/ /__/ /_/ / / / / /_/ /___/ /\n# /_/ \\___/\\___/\\____/_/ /_/\\____//____/\n# \n# ======================================================================\n# \n# project: ReconOS - Toolchain\n# author: Christoph Rüthing, University of Paderborn\n# description: Representation of a ReconOS project.\n# \n# ======================================================================\n\nimport reconos.utils.shutil2 as shutil2\nimport reconos.utils.template as template\n\nimport logging\nimport configparser\nimport re\n\nlog = logging.getLogger(__name__)\n\n#\n# Class representing a clock in the project.\n#\nclass Clock:\n\t_id = 0\n\n\tdef __init__(self, name, source, freq):\n\t\tself.id = Clock._id\n\t\tClock._id += 1\n\t\tself.name = name\n\t\tself.source = source\n\t\tself.freq = freq\n\n\tdef get_pllparam(self, vcomin, vcomax, infreq):\n\t\tdfmin = 1000000000\n\t\tfor m in range(vcomin // infreq, vcomax // infreq + 1):\n\t\t\tfor o in range(1, 101):\n\t\t\t\tif dfmin > abs(self.freq - infreq * m // o):\n\t\t\t\t\tdfmin = abs(self.freq - infreq * m // o)\n\t\t\t\t\tmopt = m\n\t\t\t\t\toopt = o\n\n\t\treturn (mopt, oopt, infreq * mopt // oopt)\n\n\tdef get_periodns(self):\n\t\treturn 1000000000 / self.freq\n\n\tdef __str__(self):\n\t\treturn \"Clock '\" + self.name + \"'\"\n\n\tdef __repr__(self):\n\t\treturn \"'\" + self.name + \"' (\" + str(self.id) + \")\"\n\n#\n# Class representing a resource in the project.\n#\nclass Resource:\n\t_id = 128\n\n\tdef __init__(self, name, type_, args, group):\n\t\tself.id = Resource._id\n\t\tResource._id += 1\n\t\tself.name = name\n\t\tself.type = type_\n\t\tself.args = args\n\t\tself.group = group\n\n\tdef __str__(self):\n\t\treturn \"Resource '\" + self.name + \"'\"\n\n\tdef __repr__(self):\n\t\treturn \"'\" + self.name + \"' (\" + str(self.id) + \")\"\n\n#\n# Class representing a slot in the project.\n#\nclass Slot:\n\tdef __init__(self, name, id_, clock, ports):\n\t\tself.name = name\n\t\tself.id = id_\n\t\tself.clock = clock\n\t\tself.threads = []\n\t\tself.ports = ports\n\n\tdef __str__(self):\n\t\treturn \"Slot '\" + self.name + \"' (\" + str(self.id) + \")\"\n\n\tdef __repr__(self):\n\t\treturn \"'\" + self.name + \"' (\" + str(self.id) + \")\"\n\n#\n# Class representing a thread in the project.\n#\nclass Thread:\n\t_id = 0\n\n\tdef __init__(self, name, slots, hw, sw, res, mem, ports):\n\t\tself.id = Thread._id\n\t\tThread._id += 1\n\t\tself.name = name\n\t\tself.slots = slots\n\t\tself.resources = res\n\t\tself.mem = mem\n\t\tself.ports = ports\n\t\tif hw is not None:\n\t\t\thw = hw.split(\",\")\n\t\t\tself.hwsource = hw[0]\n\t\t\tself.hwoptions = hw[1:]\n\t\telse:\n\t\t\tself.hwsource = None\n\t\t\tself.hwoptions = []\n\t\tif sw is not None:\n\t\t\tsw = sw.split(\",\")\n\t\t\tself.swsource = sw[0]\n\t\t\tself.swoptions = sw[1:]\n\t\telse:\n\t\t\tself.swsource = None\n\t\t\tself.swoptions = []\n\n\tdef get_corename(self):\n\t\treturn \"rt_\" + self.name.lower()\n\n\tdef get_coreversion(self):\n\t\treturn \"1.00.a\"\n\n\tdef get_swentry(self):\n\t\tif self.swsource is None or self.swsource == \"\":\n\t\t\treturn \"swt_idle\"\n\n\t\treg = r\"(?P[a-zA-Z0-9_]*)_(?Pv[0-9]+_[0-9]{2}_[a-z])\"\n\t\treturn re.search(reg, self.swsource).group(\"name\")\n\n\tdef __str__(self):\n\t\treturn \"Thread '\" + self.name + \"' (\" + str(self.id) + \")\"\n\n\tdef __repr__(self):\n\t\treturn \"'\" + self.name + \"' (\" + str(self.id) + \")\"\n\n#\n# Class representing implementation related information.\n#\nclass ImpInfo:\n\t#\n\t# Initialization of a new ImpInfo\n\t#\n\tdef __init__(self):\n\t\tself.repo = \"\"\n\n\t\tself.board = \"\"\n\t\tself.part = \"\"\n\t\tself.design = \"\"\n\t\tself.xil = \"\"\n\t\tself.xil_path = \"\"\n\t\tself.hls = \"\"\n\n\t\tself.os = \"\"\n\t\tself.cflags = \"\"\n\t\tself.ldflags = \"\"\n\n#\n# Class representing a project and providing different functionality\n# for performing all relevant tasks.\n#\nclass Project:\n\n\t#\n\t# Initialization of a new project.\n\t#\n\tdef __init__(self, repo=None):\n\t\tself.clocks = []\n\t\tself.resources = []\n\t\tself.slots = []\n\t\tself.threads = []\n\n\t\tself.impinfo = ImpInfo()\n\n\t\tself.dir = \"\"\n\t\tself.name = \"\"\n\t\tself.clock = None\n\n\t\tif repo is not None and shutil2.isdir(repo):\n\t\t\tself.impinfo.repo = repo\n\t\telif shutil2.environ(\"RECONOS\"):\n\t\t\tself.impinfo.repo = shutil2.environ(\"RECONOS\")\n\t\telse:\n\t\t\tlog.error(\"ReconOS repository not found\")\n\n\tdef get_template(self, name):\n\t\tif shutil2.exists(shutil2.join(self.dir, \"templates\", name)):\n\t\t\treturn shutil2.join(self.dir, \"templates\", name)\n\t\telse:\n\t\t\treturn shutil2.join(self.impinfo.repo, \"templates\", name)\n\n\tdef apply_template(self, name, dictionary, output, link = False):\n\t\tshutil2.mkdir(output)\n\t\tshutil2.copytree(self.get_template(name), output, followlinks=True)\n\t\ttemplate.generate(output, dictionary, \"overwrite\", link)\n\n\n\tdef get_hwtref(self, thread):\n\t\treturn shutil2.join(self.impinfo.repo, \"templates\", \"export_hw\", self.impinfo.xil[0], \"thread_\" + thread.hwsource)\n\n\tdef get_swtref(self, thread):\n\t\treturn shutil2.join(self.impinfo.repo, \"templates\", \"export_sw\", \"thread_\" + thread.swsource)\n\n\n\t#\n\t# Opens a project by parsing the project file.\n\t#\n\t# filepath - path to the project file (*.cfg)\n\t#\n\tdef open(self, filepath):\n\t\tClock._id = 0\n\t\tResource._id = 128\n\t\tThread._id = 0\n\n\t\tself.clocks = []\n\t\tself.resources = []\n\t\tself.slots = []\n\t\tself.threads = []\n\t\tself.file = shutil2.abspath(filepath)\n\t\tself.dir = shutil2.dirname(self.file)\n\t\tself.basedir = shutil2.trimext(self.file)\n\t\t#self.hwdir = shutil2.trimext(self.file) + \".hw\"\n\t\t#self.swdir = shutil2.trimext(self.file) + \".sw\"\n\n\t\tcfg = configparser.RawConfigParser()\n\t\tcfg.optionxform = str\n\t\tret = cfg.read(filepath)\n\t\tif not ret:\n\t\t\tlog.error(\"Config file '\" + filepath + \"' not found\")\n\t\t\treturn\n\n\t\tself._parse_project(cfg)\n\t\tself._check_project()\n\n\t#\n\t# Internal method parsing the project from the project file.\n\t#\n\t# cfg - configparser referencing the project file\n\t#\n\tdef _parse_project(self, cfg):\n\t\tself.name = cfg.get(\"General\", \"Name\")\n\t\tself.impinfo.board = re.split(r\"[, ]+\", cfg.get(\"General\", \"TargetBoard\"))\n\t\tself.impinfo.part = cfg.get(\"General\", \"TargetPart\")\n\t\tif cfg.has_option(\"General\", \"TargetConstraints\"):\n\t\t\tself.impinfo.constraints = cfg.get(\"General\", \"TargetConstraints\")\n\t\tself.impinfo.design = cfg.get(\"General\", \"ReferenceDesign\")\n\t\tself.impinfo.os = cfg.get(\"General\", \"TargetOS\")\n\t\tself.impinfo.xil = cfg.get(\"General\", \"TargetXil\").split(\",\")\n\t\tif cfg.has_option(\"General\", \"TargetHls\"):\n\t\t\tself.impinfo.hls = cfg.get(\"General\", \"TargetHls\").split(\",\")\n\t\telse:\n\t\t\tself.impinfo.hls = self.impinfo.xil\n\t\tif cfg.has_option(\"General\", \"CFlags\"):\n\t\t\tself.impinfo.cflags = cfg.get(\"General\", \"CFlags\")\n\t\telse:\n\t\t\tself.impinfo.cflags = \"\"\n\t\tif cfg.has_option(\"General\", \"LdFlags\"):\n\t\t\tself.impinfo.ldflags = cfg.get(\"General\", \"LdFlags\")\n\t\telse:\n\t\t\tself.impinfo.ldflags = \"\"\n\t\tif cfg.has_option(\"General\", \"XilinxPath\"):\n\t\t\tself.impinfo.xil_path = cfg.get(\"General\", \"XilinxPath\")\n\t\telse:\n\t\t\tself.impinfo.xil_path = \"/opt/Xilinx\"\n\n\t\tlog.debug(\"Found project '\" + str(self.name) + \"' (\" + str(self.impinfo.board) + \",\" + str(self.impinfo.os) + \")\")\n\n\t\tself._parse_clocks(cfg)\n\t\tself._parse_resources(cfg)\n\t\tself._parse_slots(cfg)\n\t\tself._parse_threads(cfg)\n\n\t\tclock = [_ for _ in self.clocks if _.name == cfg.get(\"General\", \"SystemClock\")]\n\t\tif not clock:\n\t\t\tlog.error(\"Clock not found\")\n\t\tself.clock = clock[0]\n\n\t#\n\t# Internal method parsing the clocks from the project file.\n\t#\n\t# cfg - configparser referencing the project file\n\t#\n\tdef _parse_clocks(self, cfg):\n\t\tfor c in [_ for _ in cfg.sections() if _.startswith(\"Clock\")]:\n\t\t\tmatch = re.search(r\"^.*@(?P.+)\", c)\n\t\t\tif match is None:\n\t\t\t\tlog.error(\"Clock must have a name\")\n\n\t\t\tname = match.group(\"name\")\n\t\t\tsource = cfg.get(c, \"ClockSource\")\n\t\t\tfreq = cfg.getint(c, \"ClockFreq\")\n\n\t\t\tlog.debug(\"Found clock '\" + str(name) + \"' (\" + str(source) + \",\" + str(freq / 1000000) + \" MHz)\")\n\n\t\t\tclock = Clock(name, source, freq)\n\t\t\tself.clocks.append(clock)\n\n\t#\n\t# Internal method parsing the resources from the project file.\n\t#\n\t# cfg - configparser referencing the project file\n\t#\n\tdef _parse_resources(self, cfg):\n\t\tfor c in [_ for _ in cfg.sections() if _.startswith(\"ResourceGroup\")]:\n\t\t\tmatch = re.search(r\"^.*@(?P.+)\", c)\n\t\t\tif match is None:\n\t\t\t\tlog.error(\"Resources must have a name\")\n\n\t\t\tgroup = match.group(\"name\")\n\n\t\t\tfor r in cfg.options(c):\n\t\t\t\tmatch = re.split(r\"[, ]+\", cfg.get(c, r))\n\n\t\t\t\tlog.debug(\"Found resource '\" + str(r) + \"' (\" + str(match[0]) + \",\" + str(match[1:]) + \",\" + str(group) + \")\")\n\t\t\t\n\t\t\t\tresource = Resource(r, match[0], match[1:], group)\n\t\t\t\tself.resources.append(resource)\n\n\t#\n\t# Internal method parsing the slots from the project file.\n\t#\n\t# cfg - configparser referencing the project file\n\t#\n\tdef _parse_slots(self, cfg):\n\t\tfor s in [_ for _ in cfg.sections() if _.startswith(\"HwSlot\")]:\n\t\t\tmatch = re.search(r\"^.*@(?P.*)\\((?P[0-9]*):(?P[0-9]*)\\)\", s)\n\t\t\tif match is None:\n\t\t\t\tr = range(0)\n\t\t\telse:\n\t\t\t\tr = range(int(match.group(\"start\")), int(match.group(\"end\")) + 1)\n\n\t\t\tname = match.group(\"name\")\n\t\t\tid_ = cfg.getint(s, \"Id\")\n\t\t\tclock = [_ for _ in self.clocks if _.name == cfg.get(s, \"Clock\")]\n\t\t\tif not clock:\n\t\t\t\tlog.error(\"Clock not found\")\n\n\t\t\tif cfg.has_option(s, \"Ports\"):\n\t\t\t\tports = [re.match(r\"(?P.*)\\((?P.*)\\)\", _).groupdict() for _ in re.findall(\"[a-zA-Z0-9_]*?\\(.*?\\)\", cfg.get(s, \"Ports\"))]\n\t\t\telse:\n\t\t\t\tports = []\n\n\t\t\tfor i in r:\n\t\t\t\tlog.debug(\"Found slot '\" + str(name) + \"(\" + str(i) + \")\" + \"' (\" + str(id_) + \",\" + str(clock[0]) + \")\")\n\n\t\t\t\tslot = Slot(name + \"(\" + str(i) + \")\", id_ + i, clock[0], ports)\n\t\t\t\tself.slots.append(slot)\n\n\t#\n\t# Internal method parsing the threads from the project file.\n\t#\n\t# cfg - configparser referencing the project file\n\t#\n\tdef _parse_threads(self, cfg):\n\t\tfor t in [_ for _ in cfg.sections() if _.startswith(\"ReconosThread\")]:\n\t\t\tmatch = re.search(r\"^.*@(?P.+)\", t)\n\t\t\tif match is None:\n\t\t\t\tlog.error(\"Thread must have a name\")\n\n\t\t\tname = match.group(\"name\")\n\t\t\tif cfg.has_option(t, \"Slot\"):\n\t\t\t\tslots = cfg.get(t, \"Slot\")\n\t\t\t\tslots = slots.replace(\"(\", \"\\\\(\")\n\t\t\t\tslots = slots.replace(\")\", \"\\\\)\")\n\t\t\t\tslots = slots.replace(\",\", \"|\")\n\t\t\t\tslots = slots.replace(\"*\", \".*\")\n\t\t\t\tslots = [_ for _ in self.slots if re.match(slots, _.name) is not None]\n\t\t\telse:\n\t\t\t\tslots = []\n\t\t\tif cfg.has_option(t, \"HwSource\"):\n\t\t\t\thw = cfg.get(t, \"HwSource\")\n\t\t\telse:\n\t\t\t\thw = None\n\t\t\t\tlog.info(\"No HwSource found\")\n\t\t\tif cfg.has_option(t, \"SwSource\"):\n\t\t\t\tsw = cfg.get(t, \"SwSource\")\n\t\t\telse:\n\t\t\t\tsw = None\n\t\t\tif cfg.has_option(t, \"ResourceGroup\"):\n\t\t\t\tres = re.split(r\"[, ]+\", cfg.get(t, \"ResourceGroup\"))\n\t\t\t\tres = [_ for _ in self.resources if _.group in res]\n\t\t\t\tif not res:\n\t\t\t\t\tlog.error(\"ResourceGroup not found\")\n\t\t\telse:\n\t\t\t\tres = []\n\t\t\tif cfg.has_option(t, \"UseMem\"):\n\t\t\t\tmem = cfg.get(t, \"UseMem\") in [\"True\", \"true\"]\n\t\t\telse:\n\t\t\t\tmem = True\n\t\t\tif cfg.has_option(t, \"Ports\"):\n\t\t\t\tports = [re.match(r\"(?P.*)\\((?P.*)\\)\", _).groupdict() for _ in re.findall(\"[a-zA-Z0-9_]*?\\(.*?\\)\", cfg.get(t, \"Ports\"))]\n\t\t\telse:\n\t\t\t\tports = []\n\n\t\t\tlog.debug(\"Found thread '\" + str(name) + \"' (\" + str(slots) + \",\" + str(hw) + \",\" + str(sw) + \",\" + str(res) + \")\")\n\n\t\t\tthread = Thread(name, slots, hw, sw, res, mem, ports)\n\t\t\tfor s in slots: s.threads.append(thread)\n\t\t\tself.threads.append(thread)\n\t\t\t\n\t#\n\t# Internal method checking the configuration for validity.\n\t#\n\t# cfg - configparser referencing the project file\n\t#\t\t\n\tdef _check_project(self):\n\t\t#\n\t\t# Check if HLS tool is specified when a thread has HLS sources\n\t\t#\n\t\thlsNeeded = False\n\t\tfor t in self.threads:\n\t\t\tif t.hwsource==\"hls\":\n\t\t\t\thlsNeeded = True\n\t\tif (hlsNeeded == True) and (self.impinfo.hls==\"\"):\n\t\t\tlog.error(\"Thread has HLS sources, but no HLS tool is specified. Please specify TargetHls variable in General section in build.cfg\")\n\t\t\texit(1)\n","repo_name":"Lien182/ReconOS_Zephyr_RISCV","sub_path":"reconos-neorv32/tools/_pypack/reconos/runtime/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":11775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"10130184205","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n\turl(r'^$', views.index, name='index'),\n\turl(r'^register/$', views.register, name='register'),\n\turl(r'^login/$', views.user_login, name='login'),\n\turl(r'^logout/$', views.user_logout, name='logout'),\n\turl(r'^customer/$', views.customer, name='customer'),\n\turl(r'^add/$', views.add, name='add'),\n\turl(r'^report/$', views.report, name='report'),\n]\n","repo_name":"xIDLxSAVAGE/DatabaseFrontEnd","sub_path":"cages/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"72419497850","text":"import cx_Freeze\nimport sys\nimport os\n\nbase = None\nif sys.platform =='win64':\n base = \"Win64GUI\"\n\nos.environ['TCL_LIBRARY'] = r\"C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38\\tcl\\tcl8.6\"\nos.environ['TK_LIBRARY'] = r\"C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38\\tcl\\tk8.6\"\n\nexecutables = [cx_Freeze.Executable(\"FilesOrganizer.py\", base=base, icon=\"folder.ico\")]\n\n\ncx_Freeze.setup(\n name =\"Files Organizer\",\n options = {\"build_exe\": {\"packages\":[\"tkinter\",\"os\", \"sys\", \"shutil\"], \"include_files\":['tcl86t.dll','tk86t.dll', 'folder.ico', 'images']}},\n version=\"1.0\",\n description =\"Files Organizer | Developed by Amar and Piyush\",\n executables = executables\n)","repo_name":"AmarKGupta/Files_Organizer","sub_path":"exe.py","file_name":"exe.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"10130644195","text":"\"\"\"\nhttps://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/\n\"\"\"\n\nif __name__ == '__main__':\n n = int(input())\n arr = list(map(int, input().split()))\n\n high_score = max(arr)\n value = None\n for score in sorted(arr, reverse=True):\n if score < high_score:\n value = score\n break\n print(value)\n","repo_name":"JJStoker/HackerRank","sub_path":"python/basic/find_second_maximum_number_in_a_list.py","file_name":"find_second_maximum_number_in_a_list.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"40600723533","text":"\"\"\"\ninfoml.binf\n-----------\n\nThis sub-package contains functions for bioinformatics.\n\"\"\"\n\nfrom . import data\n\n\nif __name__ == \"__main__\":\n print(\"This module is not intended to be run directly.\")\nelse:\n # Define module I/O\n __all__ = [\n \"data\",\n ]\n __all__ += [m for m in dir() if m.startswith(\"__\")]\n\n def __dir__():\n \"\"\"Override dir() to only show public attributes.\"\"\"\n return __all__\n\n def __getattr__(name):\n \"\"\"Override getattr() to only show public attributes.\"\"\"\n if name in __all__:\n return globals()[name]\n raise AttributeError(f\"module {__name__!r} has no attribute {name!r}\")\n","repo_name":"Kabilan108/infoml","sub_path":"src/infoml/binf/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"44253961375","text":"import os\nimport cv2\n\n# 数据集根目录\nroot_dir = r'F:\\Datasets\\obj_det\\vidrone\\visdrone2020\\VisDrone2019-DET-val'\nannotations_dir = root_dir + \"/annotations/\"\nimage_dir = root_dir + \"/images/\"\n# 新的目录\nanno_yolov3_dir = root_dir + \"/Annotations_yolov5/\"\n\n'''\n#参考visdrone的所有类别\nclass_name: ['ignored regions', 'pedestrian', 'people', 'bicycle', 'car', 'van', 'truck', 'tricycle',\n 'awning-tricycle', 'bus', 'motor', 'others']\n'''\n\ntotal_num = len(os.listdir(annotations_dir))\nnum = 0\n\nif not os.path.exists(anno_yolov3_dir):\n os.mkdir(anno_yolov3_dir)\n\nfor filename in os.listdir(annotations_dir):\n image_name = filename.split('.')[0]\n img_array = cv2.imread(image_dir + image_name + '.jpg')[:, :, ::-1]\n h, w = img_array.shape[0], img_array.shape[1]\n new_txt_path = os.path.join(anno_yolov3_dir, filename)\n fin = open(annotations_dir + filename, 'r')\n with open(new_txt_path, 'w') as fout:\n for line in fin.readlines():\n line = line.split(',')\n # 指定类别\n if line[5] in [\"4\", \"5\", \"6\", \"9\"]: # 选择类别\n line[5] = \"0\" # 重置类别序号\n fout.write(str(int(line[5])) + ' ')\n fout.write(str((int(line[0]) + int(line[2]) / 2) / w) + ' ')\n fout.write(str((int(line[1]) + int(line[3]) / 2) / h) + ' ')\n fout.write(str(int(line[2]) / w) + ' ')\n fout.write(str(int(line[3]) / h))\n fout.write('\\n')\n\n num += 1\n print(\"%s - > %s\" % (num, total_num))\n\nprint(\"It is finished.\")\n","repo_name":"cllanjim/Drone_Object_Detection_Android","sub_path":"visdrone2yolov5.py","file_name":"visdrone2yolov5.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"69920656250","text":"from tkinter import *\nimport tkinter.messagebox as msgbox\nfrom tkinter import ttk, scrolledtext\nfrom app import app\nfrom tkmacosx import Button\n\n\nclass RepairManagementPage():\n def __init__(self, app: app, master=None):\n self.__info_list = None\n self.__root = master\n self.__repairID = StringVar()\n self.__overRepairBike = StringVar()\n self.__overRepairID = StringVar()\n self.__info_list = StringVar()\n self.__info_list_2 = StringVar()\n self.__app = app\n\n def CreatePage(self):\n\n self.page = Toplevel(self.__root)\n self.page.attributes('-topmost', 1)\n self.page.geometry(\"1000x600\")\n\n top_bar = Label(self.page, bg=\"lightcyan\", height=3, width=800)\n top_bar.place(x=0, y=0)\n\n # Top title\n title_label = Label(top_bar, text=\"🔍 Repair Management\", bg=\"lightcyan\", font=(\"Arial\", 12, \"bold\"))\n title_label.place(x=10, y=5)\n\n # Buttons\n refresh_btn = Button(top_bar, command=self.refresh, text=\"Refresh\", bg='#4CAF50', fg='white',\n font=(\"Arial\", 10))\n refresh_btn.place(x=230, y=5)\n\n back_btn = Button(top_bar, command=self.quit, text=\"Back\", bg='#4CAF50', fg='white', font=(\"Arial\", 10))\n back_btn.place(x=320, y=5)\n\n b1 = Label(self.page, text=\"Report Information: \", font=(\"Arial\", 10))\n b1.place(x=40, y=50)\n\n b2 = Label(self.page, text=\"Vehicle Informationn: \", font=(\"Arial\", 10))\n b2.place(x=40, y=400)\n\n # Huge display box (Text widget)\n self.__info_list = scrolledtext.ScrolledText(self.page, width=130, height=15)\n self.__info_list.place(x=50, y=80)\n\n # Start Fix\n del_lbl = Label(self.page, text=\"Start repair:\", bg=\"#add8e6\", font=(\"Arial\", 12))\n del_lbl.place(x=50, y=320)\n del_entry_lbl = Label(self.page, text=\"bikeID\", font=(\"Arial\", 10))\n del_entry_lbl.place(x=50, y=360)\n self.__repairID = Entry(self.page, width=10)\n self.__repairID.place(x=90, y=360)\n del_enter_btn = Button(self.page, command=self.startRepair, text=\"Enter\", bg='#4CAF50', fg='white',\n font=(\"Arial\", 10))\n del_enter_btn.place(x=180, y=360)\n del_clear_btn = Button(self.page, command=self.clear_1, text=\"Clear\", bg='#4CAF50', fg='white',\n font=(\"Arial\", 10))\n del_clear_btn.place(x=250, y=360)\n\n # Move vehicle operation\n move_lbl = Label(self.page, text=\"Over repair:\", bg=\"#add8e6\", font=(\"Arial\", 12))\n move_lbl.place(x=470, y=320)\n move_entry_lbl = Label(self.page, text=\"bikeID\", font=(\"Arial\", 10))\n move_entry_lbl.place(x=462, y=360)\n self.__overRepairBike = Entry(self.page, width=10)\n self.__overRepairBike.place(x=515, y=360)\n move_entry_lbl = Label(self.page, text=\"reportID\", font=(\"Arial\", 10))\n move_entry_lbl.place(x=462, y=390)\n self.__overRepairID = Entry(self.page, width=10)\n self.__overRepairID.place(x=515, y=390)\n\n move_enter_btn = Button(self.page, command=self.overRepair, text=\"Enter\", bg='#4CAF50', fg='white',\n font=(\"Arial\", 10))\n move_enter_btn.place(x=600, y=360)\n move_clear_btn = Button(self.page, command=self.clear_2, text=\"Clear\", bg='#4CAF50', fg='white',\n font=(\"Arial\", 10))\n move_clear_btn.place(x=670, y=360)\n\n self.__info_list_2 = scrolledtext.ScrolledText(self.page, width=130, height=10)\n self.__info_list_2.place(x=50, y=430)\n\n res_1 = self.__app.getALLReportOP()\n for i in res_1:\n self.__info_list.insert(END, i + \"\\n\")\n res_2 = self.__app.getAllVehicleOP()\n for i in res_2:\n self.__info_list_2.insert(END, i + \"\\n\")\n\n def quit(self):\n self.page.destroy()\n\n def refresh(self):\n content = self.__info_list.get('1.0', END)\n if content.strip():\n self.__info_list.delete('1.0', END)\n list = self.__app.getALLReportOP()\n for i in list:\n self.__info_list.insert(END, i + \"\\n\")\n\n content_2 = self.__info_list_2.get('1.0', END)\n if content_2.strip():\n self.__info_list_2.delete('1.0', END)\n res = self.__app.getAllVehicleOP()\n for i in res:\n self.__info_list_2.insert(END, i + \"\\n\")\n\n def startRepair(self):\n id = self.__repairID.get()\n flag = self.__app.fixBikeOP(int(id))\n print(flag)\n if flag:\n msgbox.showinfo(\"Success\", \"Successfully change!\", parent=self.page)\n else:\n msgbox.showwarning(\"Warning\", \"Please Check!\", parent=self.page)\n\n def overRepair(self):\n bike = self.__overRepairBike.get()\n id = self.__overRepairID.get()\n flag = self.__app.endFixBikeOP(int(bike), int(id))\n if flag:\n msgbox.showinfo(\"Success\", \"Successfully change!\", parent=self.page)\n else:\n msgbox.showwarning(\"Warning\", \"Please Check!\", parent=self.page)\n\n def clear_1(self):\n self.__repairID.delete(0, END)\n\n def clear_2(self):\n self.__overRepairID.delete(0, END)\n self.__overRepairBike.delete(0, END)\n","repo_name":"CreateMiracle0523/ProgSD_TeamProject","sub_path":"GUI/RepairManagement.py","file_name":"RepairManagement.py","file_ext":"py","file_size_in_byte":5267,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"41609634820","text":"\"\"\"\nTHIS IS A PRACTICE FOR MICRO-KINETIC MODELING OF A BIMOLECULAR REACTION:\n a/ PLOT RATE VS TEMPERATURE\n b/ PLOT COVERAGE VS TEMPERATURE \n\"\"\"\n\nimport numpy as np\nfrom scipy.integrate import ode\nimport matplotlib.pyplot as plt\nfrom rate_constant_func import calc_kads \nfrom rate_constant_func import calc_kdes \nfrom rate_constant_func import calc_k_arr\n\nma = 28 * 1.66054e-27\nmb = 32 * 1.66054e-27\nmc = 80 * 1.66054e-27\n\n# print(\"What is your temperature?\")\n#Temperature = float(input())\n \n# =============================================================================\n# 1/ define the function\n# =============================================================================\ndef dydt(t, y, params):\n \n T, pa, pb, pc= params \n \n dydt = np.zeros(4)\n \n # calculate all reaction rate constants \n k_ads_1 = calc_kads(T, pa, 1e-20, ma)\n k_des_1 = calc_kdes(T, 1e-20, ma, 1, 2.8, 80e3)\n k_ads_2 = calc_kads(T, pb, 1e-20, mb)\n k_des_2 = calc_kdes(T, 1e-20, mb, 2, 2.08, 40e3) \n kf = calc_k_arr(T, 1e13, 120e3)\n kb = calc_k_arr(T, 1e13, 80e3) \n k_ads_4 = calc_kads(T, pc, 1e-20, mc)\n k_des_4 = calc_kdes(T, 1e-20, mc, 1, 0.561, 10e3)\n\n # collect similar terms in new variables \n r1f = k_ads_1 * y[3]\n r1b = k_des_1 * y[0]\n r2f = k_ads_2 * y[3]\n r2b = k_des_2 * y[1]**2 \n r3f = kf * y[0] * y[1]\n r3b = kb * y[2] * y[3] \n r4f = k_ads_4 * y[3]\n r4b = k_des_4 * y[2]\n \n dydt[0] = r1f - r1b - r3f + r3b\n dydt[1] = 2.0 * r2f - 2.0 * r2b - r3f + r3b\n dydt[2] = r3f - r3b + r4f - r4b\n dydt[3] = -r1f + r1b - 2.0 * r2f + 2.0 * r2b + r3f - r3b - r4f + r4b\n \n return dydt\n\nT_range = np.linspace(300,1000,100)\n\nrate_CO=[]\nrate_O2 =[]\nrate_CO2 = []\n\nTheta_CO = []\nTheta_O = []\nTheta_CO2 = []\nTheta_vac = []\n\nfor T in T_range: \n \n # =============================================================================\n # 2/Solve the differential equation \n # =============================================================================\n y0 = [0,0,0,1] #initial condittion\n #T = Temperature # temperature in K\n pt = 20 # total pressure in bar\n pa = 2.0/3.0 * pt * 1e5 # pressure of CO in Pa\n pb = 1.0/3.0 * pt * 1e5\n pc = 0\n # t = np.linspace(0,1,110)\n r = ode(dydt).set_integrator('vode', method='bdf', atol=1e-8, rtol=1e-8, \n nsteps=1000, with_jacobian=True) #Jacobian = true is very important\n r.set_initial_value(y0, 0).set_f_params([T, pa, pb, pc]) #CA_0 and t = 0\n \n t1 = 100\n # xx = np.linspace(-4,1,150)\n xx = np.linspace(-12, np.log10(t1), 500)\n yy = []\n tt = []\n for x in xx:\n tnew = 10.0**x\n tt.append(tnew)\n yy.append(r.integrate(tnew))\n \n Theta = np.matrix(yy) #yy is a list of array! to make\n #it easier to plot with legend, better transorm it into a matrix\n\n# =============================================================================\n# 3/ Plot results\n# =============================================================================\n\n# legend = [\"Theta_CO\", \"Theta_O\", \"Theta_CO2\", \"Theta*\"]\n\n# for i in range(4):\n# plt.semilogx(tt,Theta[:,i], label= legend[i])\n# plt.title(\"Coverage in function of time at \"+str(Temperature)+\" K\")\n# plt.xlabel(\"time(s)\")\n# plt.ylabel(\"coverage Theta\")\n# plt.legend()\n# plt.show()\n\n# =============================================================================\n# 4/ Calculate rate in function of Temperature\n# =============================================================================\n r_co = calc_kdes(T, 1e-20, ma, 1, 2.8, 80e3) * Theta[-1,0] - calc_kads(T, pa, 1e-20, ma)*Theta[-1,3] # \n r_o2 = 0.5*(-calc_k_arr(T, 1e13, 120e3)*Theta[-1,0]*Theta[-1,1]+calc_k_arr(T, 1e13, 80e3)*Theta[-1,3]*Theta[-1,2] )\n r_co2 = calc_kdes(T, 1e-20, mc, 1, 0.561, 10e3) * Theta[-1,2] - calc_kads(T, pc, 1e-20, mc)*Theta[-1,3]\n #NEGATIVE INDEX: Theta[-1,:] -1 MEANS THE LAST ELEMENT OF THE MATRIX\n #print(r_co, r_o2, r_co2)\n \n rate_CO.append(r_co)\n rate_O2.append(r_o2)\n rate_CO2.append(r_co2)\n\n \n# =============================================================================\n# 5/ Plot rate in function of Temperature\n# =============================================================================\n\n# legend = [\"CO\", \"O2\", \"CO2\"] \n# rate = [rate_CO,rate_O2, rate_CO2]\n# # plt.plot(T_range, rate[0])\n# # plt.plot(T_range, rate[2])\n# for i in range(3):\n# plt.plot(T_range, rate[i], label= legend[i])\n# plt.title(\"Coverage in function of Temperature\")\n# plt.xlabel(\"Temperature (K)\")\n# plt.ylabel(\"Reaction rate\")\n# plt.legend()\n\n\n# =============================================================================\n# 7/ Expressions of coverage in function of time\n# =============================================================================\n\n k_ads_1 = calc_kads(T, pa, 1e-20, ma)\n k_des_1 = calc_kdes(T, 1e-20, ma, 1, 2.8, 80e3)\n K1 = k_ads_1/k_des_1\n \n k_ads_2 = calc_kads(T, pb, 1e-20, mb)\n k_des_2 = calc_kdes(T, 1e-20, mb, 2, 2.08, 40e3) \n K2 = k_ads_2/k_des_2\n \n kf = calc_k_arr(T, 1e13, 120e3)\n kb = calc_k_arr(T, 1e13, 80e3) \n K3 = kf/kb\n \n k_ads_4 = calc_kads(T, pc, 1e-20, mc)\n k_des_4 = calc_kdes(T, 1e-20, mc, 1, 0.561, 10e3)\n K4 = k_des_4/k_ads_4\n \n cov_CO = K1 / (1+K1 + np.sqrt(K2) + K3)\n cov_O = np.sqrt(K2) / (1+K1 + np.sqrt(K2) + K3)\n cov_CO2 = K4 / (1+K1 + np.sqrt(K2) + K3)\n cov_vac = 1 / (1+K1 + np.sqrt(K2) + K3) \n \n print(cov_CO, cov_O, cov_CO2, cov_vac )\n \n Theta_CO.append(cov_CO)\n Theta_O.append(cov_O)\n Theta_CO2.append(cov_CO2)\n Theta_vac.append(cov_vac)\n \n# =============================================================================\n# 7/ Plot coverage in function of Temperature\n# =============================================================================\n\nlegend = [\"CO*\", \"O2*\", \"CO2*\", \"*\"] \ncoverage = [Theta_CO, Theta_O, Theta_CO2, Theta_vac]\n\n# plt.plot(T_range, Theta_CO)\n# plt.plot(T_range, Theta_O)\n# plt.plot(T_range, Theta_CO2)\n# plt.plot(T_range, Theta_vac)\n\nfor i in range(4):\n plt.plot(T_range, coverage[i], label= legend[i])\nplt.title(\"Coverage in function of Temperature\")\nplt.xlabel(\"Temperature (K)\")\nplt.ylabel(\"Coverage\")\nplt.legend()\n","repo_name":"domoina27/MKM_NH3","sub_path":"template/CO_oxidation.py","file_name":"CO_oxidation.py","file_ext":"py","file_size_in_byte":6293,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"43372970288","text":"import pandas as pd\nimport pandas.testing\n\n# A country is big if:\n# it has an area of at least three million (i.e., 3000000 km2), or\n# it has a population of at least twenty-five million (i.e., 25000000).\n# Write a solution to find the name, population, and area of the big countries.\n# Return the result table in any order.\n# The result format is in the following example.\n\n\n# First experience with pandas, so it's better to populate and check everything.\nWorld: pd.DataFrame = pd.DataFrame(\n [],\n columns=['name', 'continent', 'area', 'population', 'gdp']\n).astype(\n {\n 'name': 'object',\n 'continent': 'object',\n 'area': 'Int64',\n 'population': 'Int64',\n 'gdp': 'Int64',\n }\n)\n\nTest = pd.DataFrame(\n [],\n columns=['name', 'population', 'area']\n).astype(\n {\n 'name': 'object',\n 'population': 'Int64',\n 'area': 'Int64',\n }\n)\n# Ok. Populating is just key=value, dictionary type:\nWorld['name'] = ['Afghanistan', 'Albania', 'Algeria', 'Andorra', 'Angola']\nWorld['continent'] = ['Asia', 'Europe', 'Africa', 'Europe', 'Africa']\nWorld['area'] = [652230, 28748, 2381741, 468, 1246700]\nWorld['population'] = [25500100, 2831741, 37100000, 78115, 20609294]\nWorld['gdp'] = [20343000000, 12960000000, 188681000000, 3712000000, 100990000000]\n\nTest['name'] = ['Afghanistan', 'Algeria']\nTest['population'] = [25500100, 37100000]\nTest['area'] = [652230, 2381741]\n\n\ndef big_countries(world: pd.DataFrame) -> pd.DataFrame:\n # world.query() or just key -> condition.\n # Extra better to use bitwise operators.\n world = world[\n (world['population'] >= 25000000) | (world['area'] >= 3000000)\n ].reset_index(drop=True)\n return world[['name', 'population', 'area']]\n\n\n# Ok. We can't use just ASSERT to check Test == out.\n# I need to use extra panda's lib.\n# Resetting index to Test correctly. Actually I could just test 2 columns not whole DF.\n# Fine for the first_time.\npandas.testing.assert_frame_equal(Test, big_countries(World))\n","repo_name":"Massprod/leetcode-testing","sub_path":"leetcode_problems/p595_big_countries_pandas.py","file_name":"p595_big_countries_pandas.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"40924768887","text":"import logging\nfrom datetime import datetime, timedelta\nimport ebt_cloud\nimport os\n\n\nlog = logging.getLogger('__main__')\n\n\nclass CleanUpGlacier(object):\n def __init__(self, aws_access_key_id, aws_secret_access_key, region_name, vault, dayexp=365):\n self.dayexp = dayexp\n self.vault = vault\n self.glacier = ebt_cloud.AmazonGlacier(aws_access_key_id=aws_access_key_id,\n aws_secret_access_key=aws_secret_access_key,\n region_name=region_name)\n\n def _check_archive_expiration(self, archive):\n archive_id = archive['ArchiveId']\n creation_date = datetime.strptime(archive['CreationDate'], \"%Y-%m-%dT%H:%M:%SZ\")\n description = archive['ArchiveDescription']\n size_gb = int(archive['Size'] / (1024 * 1024 * 1024))\n if creation_date + timedelta(days=self.dayexp) <= datetime.now():\n log.info('Remove archive. ID: \"{0}\", Description: \"{1}\", Creation date: \"{2}\", Size in GB: \"{3}\"'.format(\n archive_id, description, creation_date, size_gb\n ))\n return True\n else:\n log.info('Skip archive. ID: \"{0}\", Description: \"{1}\", Creation date: \"{2}\", Size in GB: \"{3}\"'.format(\n archive_id, description, creation_date, size_gb\n ))\n return False\n pass\n\n def start(self):\n log.info('Cleanup vault \"{0}\"'.format(self.vault))\n inventory = self.glacier.get_inventory(self.vault)\n for archive in inventory['ArchiveList']:\n if self._check_archive_expiration(archive) is True:\n self.glacier.delete_archive(vault_name=self.vault, archive_id=archive['ArchiveId'])\n\n\nclass RetrieveArchive(object):\n def __init__(self, aws_access_key_id, aws_secret_access_key, region_name, vault, dest_dir):\n self.dest_dir = dest_dir\n self.vault = vault\n self.glacier = ebt_cloud.AmazonGlacier(aws_access_key_id=aws_access_key_id,\n aws_secret_access_key=aws_secret_access_key,\n region_name=region_name)\n\n def get_file(self, archive_id, filename=None):\n if filename is None:\n dest = os.path.join(self.dest_dir, archive_id)\n else:\n dest = os.path.join(self.dest_dir, filename)\n log.info(\"Download archive {0} to {1}\".format(archive_id, dest))\n self.glacier.download_file(self.vault, archive_id, dest)\n\n","repo_name":"larrabee/ebt","sub_path":"ebt_jobs/amazon.py","file_name":"amazon.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"77"}
+{"seq_id":"72064946490","text":"import unittest\n\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nfrom pywatts.modules import StatisticExtraction, StatisticFeature\n\nfrom unittest.mock import MagicMock\nclass TestStatisticExtraction(unittest.TestCase):\n\n def test_get_set_params(self):\n statistic_extraction = StatisticExtraction()\n self.assertEqual(\n {\"dim\": \"horizon\",\n \"name\":\"statistics\",\n \"features\": [StatisticFeature.min, StatisticFeature.max, StatisticFeature.std, StatisticFeature.mean]},\n statistic_extraction.get_params()\n )\n statistic_extraction.set_params(dim=2, features=[StatisticFeature.min])\n self.assertEqual(\n {\"dim\": 2,\n \"name\": \"statistics\",\n \"features\": [StatisticFeature.min]},\n statistic_extraction.get_params()\n )\n\n def test_transform(self):\n time = pd.date_range('2000-01-01', freq='24H', periods=3)\n da = xr.DataArray([[0, 0], [1, 3], [1, 5]],\n dims=[\"time\", \"horizon\"], coords={\"time\": time})\n statistic_extraction = StatisticExtraction(dim=\"horizon\")\n expected_result = xr.DataArray([[0, 0, 0,0], [1, 3, 1,2], [1, 5, 2,3]],\n dims=[\"time\", \"stat_features\"], coords={\"time\": time, \"stat_features\": [1, 2, 3, 4]})\n\n result = statistic_extraction.transform(da)\n xr.testing.assert_equal(result, expected_result)\n\n def test_save_load(self):\n statistic_extraction = StatisticExtraction(dim=\"horizon\", features=[StatisticFeature.max])\n json = statistic_extraction.save(fm=MagicMock())\n\n statistic_extraction_reloaded = StatisticExtraction.load(json)\n\n self.assertEqual(\n statistic_extraction.get_params(),\n statistic_extraction_reloaded.get_params()\n )\n","repo_name":"KIT-IAI/pyWATTS","sub_path":"tests/unit/modules/test_statistic_extraction.py","file_name":"test_statistic_extraction.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"77"}
+{"seq_id":"35820028586","text":"\"\"\"Module with GP model definitions using various kernels.\"\"\"\n\nimport gpytorch as gp\nfrom gpytorch.distributions import MultivariateNormal\nfrom gpytorch.likelihoods import GaussianLikelihood\nfrom gpytorch.kernels import (\n SpectralMixtureKernel,\n RBFKernel,\n AdditiveKernel,\n PolynomialKernel,\n)\n\nimport torch\nfrom torch.distributions.categorical import Categorical\nfrom torch.distributions.independent import Independent\nfrom torch.distributions.mixture_same_family import MixtureSameFamily\nfrom torch.distributions.normal import Normal\n\n\nclass GP(gp.models.ExactGP):\n def __init__(self, cov, train_x, train_y):\n super(GP, self).__init__(train_x, train_y, GaussianLikelihood())\n self.mean = gp.means.ConstantMean()\n self.cov = cov\n\n def forward(self, x):\n return MultivariateNormal(self.mean(x), self.cov(x))\n\n def predict(self, x):\n self.eval()\n with torch.no_grad(), gp.settings.fast_pred_var():\n pred = self.likelihood(self(x))\n lower, upper = pred.confidence_region()\n\n return pred.mean, lower, upper\n\n def spectral_density(self, smk) -> MixtureSameFamily:\n \"\"\"Returns the Mixture of Gaussians thet model the spectral density\n of the provided spectral mixture kernel.\"\"\"\n mus = smk.mixture_means.detach().reshape(-1, 1)\n sigmas = smk.mixture_scales.detach().reshape(-1, 1)\n mix = Categorical(smk.mixture_weights.detach())\n comp = Independent(Normal(mus, sigmas), 1)\n return MixtureSameFamily(mix, comp)\n\n\nclass SMKernelGP(GP):\n def __init__(self, train_x, train_y, num_mixtures=10):\n kernel = SpectralMixtureKernel(num_mixtures)\n kernel.initialize_from_data(train_x, train_y)\n\n super(SMKernelGP, self).__init__(kernel, train_x, train_y)\n self.mean = gp.means.ConstantMean()\n self.cov = kernel\n\n def spectral_density(self):\n return super().spectral_density(self.cov)\n\n\nclass CompositeKernelGP(GP):\n def __init__(self, train_x, train_y, num_mixtures=10):\n smk = SpectralMixtureKernel(num_mixtures)\n smk.initialize_from_data(train_x, train_y)\n kernel = AdditiveKernel(\n smk,\n PolynomialKernel(2),\n RBFKernel(),\n )\n super(CompositeKernelGP, self).__init__(kernel, train_x, train_y)\n self.mean = gp.means.ConstantMean()\n self.smk = smk\n\n def spectral_density(self):\n return super().spectral_density(self.smk)\n","repo_name":"SebastianCallh/blog-spectral-mixture-kernel","sub_path":"src/smk/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"77"}
+{"seq_id":"6152241860","text":"'''\n### Q4 \n\n### 두 수의 최소공배수(Least Common Multiple)란 입력된 두 수의 배수 중 공통이 되는 가장 작은 숫자를 의미합니다. 예를 들어 2와 7의 최소공배수는 14가 됩니다. 정의를 확장해서, n개의 수의 최소공배수는 n 개의 수들의 배수 중 공통이 되는 가장 작은 숫자가 됩니다. n개의 숫자를 담은 배열 arr이 입력되었을 때 이 수들의 최소공배수를 반환하는 함수, solution을 완성해 주세요.\n\n### 제한 사항\n- arr은 길이 1이상, 15이하인 리스트입니다.\n- arr의 원소는 100 이하인 자연수입니다.\n\n### 입출력 예\n|arr\t| result\n|-------|-------\n|[2,6,8,14]\t|168\n|[1,2,3]\t|6\n'''\n# Q4 Answer Template\ndef gg(a, b):\n answer = 1\n if a>b:\n a, b = b, a\n for i in range(b, a*b+1):\n if i%a==0 and i%b==0:\n answer=i\n break\n return answer\n\ndef solution(arr):\n answer = gg(arr[0], arr[1])\n for i in range(2, len(arr)):\n answer = gg(answer, arr[i])\n \n return answer\n\narr = [2,6,8,14]\nanswer = solution(arr)\nprint(answer)","repo_name":"Lee-Siyoung/aivle-python-exercise","sub_path":"chapter2/Q4.py","file_name":"Q4.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"37166050832","text":"FILENAME = \"input.txt\"\n\ndots = []\nfolds = []\n\nwith open(FILENAME, \"r\") as fo:\n for line in fo:\n digits = [int(d) for d in line.strip().split(\",\") if d]\n if digits:\n dots.append(digits)\n else:\n break\n for line in fo:\n if line:\n folds.append(line)\n\n\ndef fold_in_y(dots, y):\n new_dots = []\n for i, j in dots:\n pair = [i, j]\n if j >= y:\n jj = y - (j - y)\n pair = [i, jj]\n if pair not in new_dots:\n new_dots.append(pair)\n return new_dots\n\n\ndef fold_in_x(dots, x):\n new_dots = []\n for i, j in dots:\n pair = [i, j]\n if i >= x:\n ii = x - (i - x)\n pair = [ii, j]\n if pair not in new_dots:\n new_dots.append(pair)\n return new_dots\n\n\nfor fold in folds:\n fold_location = int(fold.split(\"=\")[-1])\n if \"along y\" in fold:\n dots = fold_in_y(dots, fold_location)\n print(f\"{fold.strip().title()} -> dots: {len(dots)}\")\n if \"along x\" in fold:\n dots = fold_in_x(dots, fold_location)\n print(f\"{fold.strip().title()} -> dots: {len(dots)}\")\n\nmax_x = 1 + max(v[0] for v in dots)\nmax_y = 1 + max(v[1] for v in dots)\n\nprint()\narray = [[\".\" for _ in range(max_x)] for _ in range(max_y)]\nfor j, i in dots:\n array[i][j] = \"#\"\nfor l in array:\n print(\"\".join(l))\n","repo_name":"miguelsmatos/advent-of-code-2021","sub_path":"13/13.py","file_name":"13.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"23203194147","text":"import datetime\nimport matplotlib.pyplot as plt\n\n\ndef draw_losses(losses, title=['', ''], save_dir='./'):\n plt.figure(figsize=(6, 7))\n plt.xlabel('epoches', fontsize=10)\n plt.ylabel('Loss', fontsize=10)\n for i in range(len(title)):\n plt.subplot(2, 1, i + 1)\n plt.plot(list(range(1, len(losses[i]) + 1)), losses[i])\n plt.title(title[i])\n filetime = str(\n datetime.datetime.strftime(datetime.datetime.today(), '%Y%m%d_%H%M%S'))\n plt.savefig(os.path.join(save_dir, 'loss_' + filetime + '.jpg'))\n plt.show()\n","repo_name":"criterion326/IE-HGNN","sub_path":"utils/draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"16531588033","text":"#!/usr/bin/env python3\n\"\"\"\ninherits from tensorflow.keras.layers.Layer\n\"\"\"\nimport tensorflow as tf\n\n\nclass RNNEncoder(tf.keras.layers.Layer):\n \"\"\"\n inherits from tensorflow.keras.layers.Layer\n \"\"\"\n\n def __init__(self, vocab, embedding, units, batch):\n \"\"\"\n def init constructor\n \"\"\"\n super().__init__()\n self.batch = batch\n self.units = units\n self.embedding = tf.keras.layers.Embedding(input_dim=vocab,\n output_dim=embedding)\n self.gru = tf.keras.layers.GRU(units,\n recurrent_initializer=\"glorot_uniform\",\n return_sequences=True,\n return_state=True)\n\n def initialize_hidden_state(self):\n \"\"\"\n Initializes the hidden states\n \"\"\"\n\n initializer = tf.keras.initializers.Zeros()\n hidden_states = initializer(shape=(self.batch, self.units))\n return hidden_states\n\n def call(self, x, initial):\n \"\"\"\n the last hidden state of the encoder\n \"\"\"\n embedding = self.embedding(x)\n encoder_outputs, state_h = self.gru(embedding, initial_state=initial)\n return encoder_outputs, state_h\n","repo_name":"AhmedOmi/holbertonschool-machine_learning","sub_path":"supervised_learning/0x11-attention/0-rnn_encoder.py","file_name":"0-rnn_encoder.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"16655548656","text":"import kaa\nfrom kaa import document\nfrom kaa.ui.filenameindex import filenameindexmode\n\n\ndef show(commandline, s):\n doc = document.Document()\n doc.set_title(' '.join(commandline.split()))\n mode = MakeoutputMode()\n doc.setmode(mode)\n\n doc.insert(0, s)\n\n mode = doc.mode\n style_filename = mode.get_styleid('filenameindex-filename')\n style_lineno = mode.get_styleid('filenameindex-lineno')\n\n for m in mode.RE_FILENAME.finditer(doc):\n f, t = m.span('FILENAME')\n doc.setstyles(f, t, style_filename, update=False)\n\n f, t = m.span('LINENO')\n doc.setstyles(f, t, style_lineno, update=False)\n\n kaa.app.show_doc(doc)\n\n\nclass MakeoutputMode(filenameindexmode.FilenameIndexMode):\n MODENAME = 'Make'\n","repo_name":"kaaedit/kaa","sub_path":"kaa/ui/makeoutput/makeoutputmode.py","file_name":"makeoutputmode.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":124,"dataset":"github-code","pt":"77"}
+{"seq_id":"11140752710","text":"import os\nimport pickle\nimport sys\nfrom datetime import datetime\nfrom pathlib import Path\n\nimport pytest\nimport shotgun_api3\nfrom sqlalchemy import create_engine\n\nsys.path.append(str(Path(__file__).parent.parent))\nimport fakegrid\nfrom fakegrid.fakegrid import Fakegrid\n\n# artists taken from demo site\nARTIST_1 = {\"type\": \"HumanUser\", \"id\": 19}\nARTIST_2 = {\"type\": \"HumanUser\", \"id\": 18}\nSHOTGRID_SUPPORT = {\"type\": \"HumanUser\", \"id\": 24}\nZEBRA_VERSION = {\"id\": 6944, \"name\": \"alias_model_Zebra\", \"type\": \"Version\"}\n\nLOCAL_TIMEZONE = shotgun_api3.sg_timezone.local\n\nRESULTS_FILE = Path(__file__).parent.parent / \"test/real_test_results.pickle\"\nEXPECTED_RESULTS = pickle.load(RESULTS_FILE.open(\"rb\"))\n\n\n# Queries to test the reading and filtering of different data types\nTEST_QUERIES = [\n # Addressing\n (\"Note\", [], [\"addressings_to\", \"addressings_cc\"]),\n (\n \"Note\",\n [[\"addressings_to\", \"is\", ARTIST_1]],\n [\"addressings_to\", \"addressings_cc\"],\n ),\n (\n \"Note\",\n [[\"addressings_to\", \"is_not\", ARTIST_1]],\n [\"addressings_to\", \"addressings_cc\"],\n ),\n (\n \"Note\",\n [[\"addressings_to\", \"contains\", ARTIST_1]],\n [\"addressings_to\", \"addressings_cc\"],\n ),\n (\n \"Note\",\n [[\"addressings_to\", \"not_contains\", ARTIST_1]],\n [\"addressings_to\", \"addressings_cc\"],\n ),\n (\n \"Note\",\n [[\"addressings_to\", \"in\", [ARTIST_1, ARTIST_2]]],\n [\"addressings_to\", \"addressings_cc\"],\n ),\n (\n \"Note\",\n [[\"addressings_to\", \"is\", [ARTIST_1, ARTIST_2]]],\n [\"addressings_to\", \"addressings_cc\"],\n ),\n (\n \"Note\",\n [[\"addressings_to\", \"in\", ARTIST_1]],\n [\"addressings_to\", \"addressings_cc\"],\n ),\n (\n \"Note\",\n [[\"addressings_to\", \"type_is\", \"HumanUser\"]],\n [\"addressings_to\", \"addressings_cc\"],\n ),\n (\n \"Note\",\n [[\"addressings_to\", \"type_is_not\", \"HumanUser\"]],\n [\"addressings_to\", \"addressings_cc\"],\n ),\n (\n \"Note\",\n [[\"addressings_to\", \"name_contains\", \"a\"]],\n [\"addressings_to\", \"addressings_cc\"],\n ),\n (\n \"Note\",\n [[\"addressings_to\", \"name_not_contains\", \"a\"]],\n [\"addressings_to\", \"addressings_cc\"],\n ),\n (\n \"Note\",\n [[\"addressings_to\", \"name_starts_with\", \"a\"]],\n [\"addressings_to\", \"addressings_cc\"],\n ),\n (\n \"Note\",\n [[\"addressings_to\", \"name_ends_with\", \"a\"]],\n [\"addressings_to\", \"addressings_cc\"],\n ),\n (\n \"Note\",\n [\n [\"addressings_to\", \"greater_than\", ARTIST_1],\n [\"addressings_cc\", \"is\", ARTIST_2],\n ],\n [\"addressings_to\", \"addressings_cc\"],\n ),\n # Checkbox\n (\"Note\", [], [\"client_note\"]),\n (\"Note\", [[\"client_note\", \"is\", True]], [\"client_note\"]),\n (\"Note\", [[\"client_note\", \"is_not\", True]], [\"client_note\"]),\n (\"Note\", [[\"client_note\", \"greater_than\", 0]], [\"client_note\"]),\n # Color\n (\"Step\", [], [\"color\"]),\n (\"Step\", [[\"color\", \"is\", \"50,149,253\"]], [\"color\"]),\n (\"Step\", [[\"color\", \"is_not\", \"50,149,253\"]], [\"color\"]),\n (\n \"Step\",\n [[\"color\", \"in\", \"50,149,253\"]], # unintuitive but valid I guess!\n [\"color\"],\n ),\n (\"Step\", [[\"color\", \"not_in\", \"50,149,253\"]], [\"color\"]),\n (\"Step\", [[\"color\", \"in\", [\"50,149,253\"]]], [\"color\"]),\n (\"Step\", [[\"color\", \"not_in\", [\"50,149,253\"]]], [\"color\"]),\n # Currency - no currency field on demo site?\n # Date\n (\"Task\", [], [\"due_date\"]),\n (\"Task\", [[\"due_date\", \"is\", \"2016-01-18\"]], [\"due_date\"]),\n (\"Task\", [[\"due_date\", \"is_not\", \"2016-01-18\"]], [\"due_date\"]),\n (\"Task\", [[\"due_date\", \"greater_than\", \"2016-01-18\"]], [\"due_date\"]),\n (\"Task\", [[\"due_date\", \"less_than\", \"2016-01-18\"]], [\"due_date\"]),\n (\"Task\", [[\"due_date\", \"in_last\", 1, \"DAY\"]], [\"due_date\"]),\n (\"Task\", [[\"due_date\", \"not_in_last\", 1, \"DAY\"]], [\"due_date\"]),\n (\"Task\", [[\"due_date\", \"in_last\", 10, \"SECOND\"]], [\"due_date\"]), # bad\n (\"Task\", [[\"due_date\", \"in_last\", 10, \"HOUR\"]], [\"due_date\"]),\n (\"Task\", [[\"due_date\", \"in_last\", 10, \"MONTH\"]], [\"due_date\"]),\n (\"Task\", [[\"due_date\", \"in_last\", 10, \"YEAR\"]], [\"due_date\"]),\n (\"Task\", [[\"due_date\", \"in_next\", 1, \"DAY\"]], [\"due_date\"]),\n (\"Task\", [[\"due_date\", \"not_in_next\", 1, \"DAY\"]], [\"due_date\"]),\n (\"Task\", [[\"due_date\", \"in_calendar_day\", 0]], [\"due_date\"]),\n (\"Task\", [[\"due_date\", \"in_calendar_week\", 0]], [\"due_date\"]),\n (\"Task\", [[\"due_date\", \"in_calendar_month\", 0]], [\"due_date\"]),\n (\"Task\", [[\"due_date\", \"in_calendar_year\", 0]], [\"due_date\"]),\n (\"Task\", [[\"due_date\", \"between\", [\"2016-01-18\", \"2016-02-18\"]]], [\"due_date\"]),\n (\"Task\", [[\"due_date\", \"in\", [\"2016-01-18\"]]], [\"due_date\"]),\n (\"Task\", [[\"due_date\", \"not_in\", [\"2016-01-18\"]]], [\"due_date\"]),\n # Date/Time\n (\"Version\", [], [\"created_at\"]),\n (\n \"Version\",\n [[\"created_at\", \"is\", datetime(2015, 12, 1, 8, 51, tzinfo=LOCAL_TIMEZONE)]],\n [\"created_at\"],\n ),\n (\n \"Version\",\n [[\"created_at\", \"is_not\", datetime(2015, 12, 1, 8, 51, tzinfo=LOCAL_TIMEZONE)]],\n [\"created_at\"],\n ),\n (\n \"Version\",\n [\n [\n \"created_at\",\n \"greater_than\",\n datetime(2015, 12, 1, 8, 51, tzinfo=LOCAL_TIMEZONE),\n ]\n ],\n [\"created_at\"],\n ),\n (\n \"Version\",\n [\n [\n \"created_at\",\n \"less_than\",\n datetime(2015, 12, 1, 8, 51, tzinfo=LOCAL_TIMEZONE),\n ]\n ],\n [\"created_at\"],\n ),\n (\n \"Version\",\n [\n [\n \"created_at\",\n \"between\",\n [\n datetime(2015, 12, 1, 8, 50, tzinfo=LOCAL_TIMEZONE),\n datetime(2015, 12, 1, 8, 55, tzinfo=LOCAL_TIMEZONE),\n ],\n ]\n ],\n [\"created_at\"],\n ),\n (\n \"Version\",\n [[\"created_at\", \"in\", [datetime(2015, 12, 1, 8, 51, tzinfo=LOCAL_TIMEZONE)]]],\n [\"created_at\"],\n ),\n (\n \"Version\",\n [\n [\n \"created_at\",\n \"not_in\",\n [datetime(2015, 12, 1, 8, 51, tzinfo=LOCAL_TIMEZONE)],\n ]\n ],\n [\"created_at\"],\n ),\n # Duration\n (\"Task\", [], [\"duration\"]),\n (\"Task\", [[\"duration\", \"is\", 3000]], [\"duration\"]),\n (\"Task\", [[\"duration\", \"is_not\", 3000]], [\"duration\"]),\n (\"Task\", [[\"duration\", \"greater_than\", 3000]], [\"duration\"]),\n (\"Task\", [[\"duration\", \"less_than\", 3000]], [\"duration\"]),\n (\"Task\", [[\"duration\", \"between\", [3000, 3600]]], [\"duration\"]),\n (\"Task\", [[\"duration\", \"in\", [3000, 3600]]], [\"duration\"]),\n (\"Task\", [[\"duration\", \"not_in\", [3000, 3600]]], [\"duration\"]),\n # Entity\n (\"Version\", [], [\"created_by\"]),\n (\"Version\", [[\"created_by\", \"is\", ARTIST_1]], [\"created_by\"]),\n (\"Version\", [[\"created_by\", \"is_not\", ARTIST_1]], [\"created_by\"]),\n (\"Version\", [[\"entity\", \"type_is\", \"Shot\"]], [\"entity\"]),\n (\"Version\", [[\"entity\", \"type_is_not\", \"Shot\"]], [\"entity\"]),\n (\"Version\", [[\"created_by\", \"name_contains\", \"1\"]], [\"created_by\"]),\n (\"Version\", [[\"created_by\", \"name_not_contains\", \"1\"]], [\"created_by\"]),\n (\"Version\", [[\"created_by\", \"name_is\", \"Artist 1\"]], [\"created_by\"]),\n (\"Version\", [[\"created_by\", \"in\", [ARTIST_1, ARTIST_2]]], [\"created_by\"]),\n (\"Version\", [[\"created_by\", \"not_in\", [ARTIST_1, ARTIST_2]]], [\"created_by\"]),\n # Float\n (\"Version\", [], [\"sg_uploaded_movie_frame_rate\"]),\n (\n \"Version\",\n [[\"sg_uploaded_movie_frame_rate\", \"is\", 24.0]],\n [\"sg_uploaded_movie_frame_rate\"],\n ),\n (\n \"Version\",\n [[\"sg_uploaded_movie_frame_rate\", \"is_not\", 24.0]],\n [\"sg_uploaded_movie_frame_rate\"],\n ),\n (\n \"Version\",\n [[\"sg_uploaded_movie_frame_rate\", \"greater_than\", 23.0]],\n [\"sg_uploaded_movie_frame_rate\"],\n ),\n (\n \"Version\",\n [[\"sg_uploaded_movie_frame_rate\", \"less_than\", 24.1]],\n [\"sg_uploaded_movie_frame_rate\"],\n ),\n (\n \"Version\",\n [[\"sg_uploaded_movie_frame_rate\", \"between\", [24.0, 30.0]]],\n [\"sg_uploaded_movie_frame_rate\"],\n ),\n (\n \"Version\",\n [[\"sg_uploaded_movie_frame_rate\", \"in\", [24.0, 30.0]]],\n [\"sg_uploaded_movie_frame_rate\"],\n ),\n (\n \"Version\",\n [[\"sg_uploaded_movie_frame_rate\", \"not_in\", [24.0, 30.0]]],\n [\"sg_uploaded_movie_frame_rate\"],\n ),\n # footage - no footage field on demo site?\n # Image - Don't test results because our demo database\n # may copy images to local dir and change result\n (\"Asset\", [[\"image\", \"is\", None]], [\"image\"]),\n # List\n (\"Asset\", [], [\"sg_asset_type\"]),\n (\"Asset\", [[\"sg_asset_type\", \"is\", \"Character\"]], [\"sg_asset_type\"]),\n (\"Asset\", [[\"sg_asset_type\", \"is_not\", \"Character\"]], [\"sg_asset_type\"]),\n (\"Asset\", [[\"sg_asset_type\", \"in\", [\"Character\"]]], [\"sg_asset_type\"]),\n (\"Asset\", [[\"sg_asset_type\", \"not_in\", [\"Character\"]]], [\"sg_asset_type\"]),\n # Multi-Entity - lets test both natural multi-entity fields\n # and reverse fields of single entity links\n (\"Project\", [], [\"users\"]),\n (\"Project\", [[\"users\", \"is\", SHOTGRID_SUPPORT]], [\"users\"]),\n (\"Project\", [[\"users\", \"is_not\", SHOTGRID_SUPPORT]], [\"users\"]),\n (\"Project\", [[\"users\", \"type_is\", \"HumanUser\"]], [\"users\"]),\n (\"Project\", [[\"users\", \"type_is_not\", \"HumanUser\"]], [\"users\"]),\n (\"Project\", [[\"users\", \"name_contains\", \"Support\"]], [\"users\"]),\n (\"Project\", [[\"users\", \"name_not_contains\", \"Support\"]], [\"users\"]),\n (\"Project\", [[\"users\", \"name_is\", \"Shotgrid Support\"]], [\"users\"]),\n (\"Project\", [[\"users\", \"in\", [SHOTGRID_SUPPORT, ARTIST_2]]], [\"users\"]),\n (\"Project\", [[\"users\", \"not_in\", [SHOTGRID_SUPPORT, ARTIST_2]]], [\"users\"]),\n (\n \"Project\",\n [[\"users\", \"is\", ARTIST_1]],\n [\"users\"],\n ), # won't work - account disabled\n (\"Asset\", [], [\"sg_versions\"]),\n (\"Asset\", [[\"sg_versions\", \"is\", ZEBRA_VERSION]], [\"sg_versions\"]),\n (\"Asset\", [[\"sg_versions\", \"is_not\", ZEBRA_VERSION]], [\"sg_versions\"]),\n (\"Asset\", [[\"sg_versions\", \"type_is\", \"Version\"]], [\"sg_versions\"]),\n (\"Asset\", [[\"sg_versions\", \"type_is_not\", \"Version\"]], [\"sg_versions\"]),\n (\"Asset\", [[\"sg_versions\", \"name_contains\", \"Zebra\"]], [\"sg_versions\"]),\n (\"Asset\", [[\"sg_versions\", \"name_not_contains\", \"Zebra\"]], [\"sg_versions\"]),\n (\"Asset\", [[\"sg_versions\", \"name_is\", \"alias_model_Zebra\"]], [\"sg_versions\"]),\n (\"Asset\", [[\"sg_versions\", \"in\", [ZEBRA_VERSION]]], [\"sg_versions\"]),\n (\"Asset\", [[\"sg_versions\", \"not_in\", [ZEBRA_VERSION]]], [\"sg_versions\"]),\n # number\n (\"Version\", [], [\"id\"]),\n (\"Version\", [[\"id\", \"is\", 6947]], [\"id\"]),\n (\"Version\", [[\"id\", \"is_not\", 6947]], [\"id\"]),\n (\"Version\", [[\"id\", \"less_than\", 6947]], [\"id\"]),\n (\"Version\", [[\"id\", \"greater_than\", 6947]], [\"id\"]),\n (\"Version\", [[\"id\", \"between\", [6947, 6949]]], [\"id\"]),\n (\"Version\", [[\"id\", \"in\", [6947, 6949]]], [\"id\"]),\n (\"Version\", [[\"id\", \"not_in\", [6947, 6949]]], [\"id\"]),\n # password\n (\"HumanUser\", [], [\"password_proxy\"]),\n (\"HumanUser\", [[\"password_proxy\", \"is\", \"test\"]], [\"password_proxy\"]),\n # Percent\n (\"HumanUser\", [], [\"percent_capacity\"]),\n (\"HumanUser\", [[\"percent_capacity\", \"is\", 100]], [\"percent_capacity\"]),\n (\"HumanUser\", [[\"percent_capacity\", \"is_not\", 100]], [\"percent_capacity\"]),\n (\"HumanUser\", [[\"percent_capacity\", \"less_than\", 100]], [\"percent_capacity\"]),\n (\"HumanUser\", [[\"percent_capacity\", \"greater_than\", 100]], [\"percent_capacity\"]),\n (\"HumanUser\", [[\"percent_capacity\", \"between\", [5, 100]]], [\"percent_capacity\"]),\n (\"HumanUser\", [[\"percent_capacity\", \"in\", [99, 100]]], [\"percent_capacity\"]),\n (\"HumanUser\", [[\"percent_capacity\", \"not_in\", [1, 2]]], [\"percent_capacity\"]),\n # Serializable\n (\"EventLogEntry\", [[\"id\", \"is\", 481221]], [\"meta\"]), # First event log on demo site\n # Status List\n (\"Task\", [], [\"sg_status_list\"]),\n (\"Task\", [[\"sg_status_list\", \"is\", \"ip\"]], [\"sg_status_list\"]),\n (\"Task\", [[\"sg_status_list\", \"is_not\", \"ip\"]], [\"sg_status_list\"]),\n (\"Task\", [[\"sg_status_list\", \"in\", [\"ip\"]]], [\"sg_status_list\"]),\n (\"Task\", [[\"sg_status_list\", \"not_in\", [\"ip\"]]], [\"sg_status_list\"]),\n # Tag List - no tags in demo site\n # Text\n (\"Version\", [], [\"code\"]),\n (\"Version\", [[\"code\", \"is\", \"bunny_080_0200_layout_v000\"]], [\"code\"]),\n (\"Version\", [[\"code\", \"is_not\", \"bunny_080_0200_layout_v000\"]], [\"code\"]),\n (\"Version\", [[\"code\", \"contains\", \"bunny_080_0200\"]], [\"code\"]),\n (\"Version\", [[\"code\", \"not_contains\", \"bunny_080_0200\"]], [\"code\"]),\n (\"Version\", [[\"code\", \"starts_with\", \"bunny\"]], [\"code\"]),\n (\"Version\", [[\"code\", \"ends_with\", \"v000\"]], [\"code\"]),\n (\n \"Version\",\n [[\"code\", \"in\", [\"bunny_080_0200_layout_v000\", \"bunny_080_0200_layout_v001\"]]],\n [\"code\"],\n ),\n (\n \"Version\",\n [\n [\n \"code\",\n \"not_in\",\n [\"bunny_080_0200_layout_v000\", \"bunny_080_0200_layout_v001\"],\n ]\n ],\n [\"code\"],\n ),\n # Timecode - no timecode field on demo site?\n # url\n # (\"Version\", [], [\"sg_uploaded_movie\"]), # url changes on demo site due to AWS\n # so this has been manually tested unfortunately\n # other interesting scenarios\n # projects only show active users- so all demo site disabled users won't appear here\n (\"Project\", [], [\"users\"]),\n # and querying won't work!\n (\"Project\", [[\"users\", \"is\", ARTIST_1]], [\"users\"]),\n # dotted syntax\n (\n \"Version\",\n [[\"entity.Asset.code\", \"is\", \"Assembly\"]],\n [\"code\", \"entity\", \"entity.Shot.addressings_cc\"],\n ),\n (\n \"Shot\",\n [[\"sg_versions.Version.project.Project.id\", \"is\", 70]],\n [\"sg_versions\", \"code\"],\n ),\n (\n \"Shot\",\n [[\"sg_versions.Version.project.Project.id\", \"is\", None]],\n [\"sg_versions\", \"code\"],\n ),\n (\n \"Shot\",\n [[\"sg_versions.Version.entity.Shot.id\", \"is\", None]],\n [\"sg_versions\", \"code\"],\n ),\n (\n \"Shot\",\n [[\"sg_versions.Version.entity\", \"is\", None]],\n [\"sg_versions\", \"code\"],\n ),\n (\n \"Shot\",\n [[\"sg_versions.Version.entity.Shot.id\", \"is\", 1021]],\n [\"sg_versions\", \"code\"],\n ),\n # ( # This is broken see example below\n # something is weird with Notes in SG's backend\n # \"Shot\",\n # [[\"sg_versions.Version.open_notes.Note.project.Project.id\", \"is\", 70]],\n # [\"sg_versions\", \"code\"],\n # ),\n # ( # Example: This produces results on SG when it shouldn't??\n # \"Version\",\n # [[\"open_notes.Note.project.Project.id\", \"is\", 70], [\"open_notes\", \"is\", None]], # should cancel each other\n # [\"sg_versions\", \"code\"],\n # ),\n (\n \"Shot\",\n [[\"assets.Asset.sequences.Sequence.shots.Shot.id\", \"is\", 862]],\n [\"code\"],\n ),\n # stuff that doesn't exist\n (\"NotAnEntity\", [], [\"code\"]),\n (\"Version\", [], [\"not_a_field\"]),\n (\"Version\", [[\"not_a_field\", \"is\", \"test\"]], [\"not_a_field\"]),\n (\"Version\", [[\"code\", \"not_an_operator\", \"test\"]], [\"code\"]),\n # complex queries\n (\n \"Version\",\n [\n {\n \"filter_operator\": \"any\",\n \"filters\": [\n [\"code\", \"is\", \"bunny_080_0200_layout_v000\"],\n [\"code\", \"is\", \"bunny_080_0200_layout_v001\"],\n ],\n }\n ],\n [\"code\"],\n ),\n (\n \"Version\",\n [\n {\n \"filter_operator\": \"all\",\n \"filters\": [\n [\"code\", \"contains\", \"bunny\"],\n {\n \"filter_operator\": \"any\",\n \"filters\": [\n [\"code\", \"contains\", \"0200\"],\n [\"code\", \"is\", \"layout\"],\n ],\n },\n ],\n }\n ],\n [\"code\"],\n ),\n]\n\n\n@pytest.fixture(scope=\"module\")\ndef sg():\n import sqlite3\n\n source = sqlite3.connect(\"demo_site.sqlite\")\n engine = create_engine(\"sqlite:///\")\n source.backup(engine.raw_connection().driver_connection) # type:ignore\n schema = fakegrid.ShotgridSchema.from_file(\n Path(__file__).parent.parent / \"schema.pickle\"\n )\n return Fakegrid.from_schema(schema, engine)\n\n\n@pytest.mark.parametrize(\"entity_type, filters, fields\", TEST_QUERIES)\ndef test_queries(entity_type, filters, fields, sg):\n key = \"{} {} {}\".format(entity_type, filters, fields)\n expected_result = EXPECTED_RESULTS[key]\n try:\n our_result = sg.find(entity_type, filters, fields)\n except Exception as e:\n our_result = e\n if isinstance(expected_result, Exception):\n assert type(our_result) == type(expected_result)\n else:\n assert our_result == expected_result\n\n\n# Running this file directly will regenerate test results\n# Do this if you have changed the test queries!\nif __name__ == \"__main__\":\n sg = shotgun_api3.Shotgun( # noqa # type:ignore\n os.environ[\"SG_SERVER\"],\n os.environ[\"SG_SCRIPT_NAME\"],\n os.environ[\"SG_SCRIPT_KEY\"],\n )\n all_results = {}\n for entity_type, filters, fields in TEST_QUERIES:\n key = \"{} {} {}\".format(entity_type, filters, fields)\n print(\"Testing query: {} {} {}\".format(entity_type, filters, fields))\n try:\n results = sg.find(entity_type, filters, fields)\n except Exception as e:\n results = e\n\n print(\"Result: {}\".format(results))\n all_results[key] = results\n\n with RESULTS_FILE.open(\"wb\") as f:\n pickle.dump(all_results, f)\n","repo_name":"austinwitherspoon/fakegrid","sub_path":"tests/test_queries.py","file_name":"test_queries.py","file_ext":"py","file_size_in_byte":17919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"12135966561","text":"def verificar():\n if (l1==l2!=l3) or (l2==l3!=l1) or (l1==l3!=l2):\n tri = \"Isoceles\"\n elif (l1!=l2!=l3):\n tri = \"Escaleno\"\n else:\n tri = \"Equilatero\"\n return tri\ndef retangulo():\n ret = (l1**2+l2**2==l3**2) or (l2**2+l3**2==l1**2) or (l1**2+l3**2==l2**2)\n if ret == True:\n ret = \"S\"\n else:\n ret = \"N\"\n return ret\n\nl1, l2, l3 = map(int, input().split())\nvalidar = (l3= (self.size))\n\n def parse(self, raw):\n \"\"\"Parse raw bytearray and assign to fields\n Return offset into raw of unparsed portion\n Base method to be overridden in subclass\n \"\"\"\n if (raw is None) or (not self.verifySize(raw)):\n raise ValueError(\"Parse Packer: Not enough raw data for packer. \"\n \"Need {0} bytes, got {1} bytes.\".format(self.size,\n len(raw)))\n\n result = self.packer.unpack_from(raw) # result should be empty tuple\n self.packed[:] = raw[0:self.packer.size]\n\n return self.size #return offset to start of unparsed portion of data\n\n def pack(self, **kwa):\n \"\"\"\n Return .packed with data if any\n Base method to be overridden in sub class\n \"\"\"\n\n self.packer.pack_into(self.packed, 0) # empty\n\n if self.size != self.packer.size :\n raise ValueError(\"Build Packer: size packed={0} not match \"\n \"format={1}\".format(self.size, self.packer.size))\n return self.packed\n\n\nclass PackifierPart(Part):\n \"\"\"\n Base class for packet packifier part classes with packify .fmt\n .fmt is the packify string format for the fixed size portion of part\n packify allows bit field packing\n \"\"\"\n Format = '' # default packer struct format string for packed\n\n def __init__(self,\n fmt=None,\n raw=None,\n **kwa):\n \"\"\"\n Initialization method for instance.\n\n Inherited Parameters:\n size is initial size of .packed\n\n Parameters:\n fmt is packify format string to pack into .packed\n raw is input bytearray of data to parse(unpack)\n\n Inherited Attributes:\n .packed is bytearray of packed binary data\n\n Attributes:\n .fmt is packify format string\n\n Inherited Properties:\n .size is length of .packed\n\n \"\"\"\n self.fmt = fmt if fmt is not None else self.Format\n tbfl = sum((int(x) for x in self.fmt.split()))\n size = (tbfl // 8) + 1 if tbfl % 8 else tbfl // 8\n kwa['size'] = size # override size to match packify size of whole bytes\n super(PackifierPart, self).__init__(**kwa)\n\n if raw is not None:\n self.parse(raw=raw)\n\n def verifySize(self, raw=bytearray(b'')):\n \"\"\"\n Return True if len(raw) is at least long enough for packed size\n \"\"\"\n return (len(raw) >= (self.size))\n\n def parse(self, raw):\n \"\"\"Parse raw bytearray and assign to fields\n Return offset into raw of unparsed portion\n Base method to be overridden in subclass\n \"\"\"\n if (not raw) or (not self.verifySize(raw)):\n raise ValueError(\"Parse Packifier: Not enough raw data for packifier. \"\n \"Need {0} bytes, got {1} bytes.\".format(self.size,\n len(raw)))\n\n result = unpackify(self.fmt, raw, boolean=True, size=self.size) # empty result\n self.packed[:] = raw[0:self.size]\n\n return self.size #return offset to start of unparsed portion of data\n\n def pack(self, **kwa):\n \"\"\"\n Return .packed with data if any\n Base method to be overridden in sub class\n \"\"\"\n size = packifyInto(self.packed, fmt=self.fmt, fields=())\n\n if self.size != size :\n raise ValueError(\"Build Packifier: size packed={0} not match \"\n \"format={1}\".format(self.size, size))\n return self.packed\n\n def show(self):\n \"\"\"\n Returns descriptive string for display purposes\n \"\"\"\n name = self.__class__.__name__\n result = (\" {0}: packed=0x{1}\\n\".format(name,\n hexlify(self.packed).decode('ascii')))\n return result\n\n\nclass PacketPart(Part):\n \"\"\"\n PacketPart base class for parts of packets.\n Allows PacketPart to reference other parts of its Packet\n \"\"\"\n\n def __init__(self,\n packet=None,\n **kwa\n ):\n \"\"\"\n Initialization method for instance.\n Base class method to be overridden in subclass\n Need to add parts to packet in subclass\n\n Inherited Parameters:\n size is initial size of .packed\n\n Parameters:\n packet is Packet instance that holds this part\n\n Inherited Attributes:\n .packed is bytearray of packed binary data\n\n Attributes:\n .packet is Packet instance that holds this part\n\n Properties:\n .size is length of .packed\n\n \"\"\"\n super(PacketPart, self).__init__(**kwa)\n self.packet = packet\n\n def show(self):\n \"\"\"\n Returns descriptive string for display purposes\n \"\"\"\n name = self.__class__.__name__\n result = (\" {0}: packed=0x{1}\\n\".format(name,\n hexlify(self.packed).decode('ascii')))\n return result\n\n\nclass Packet(Part):\n \"\"\"\n Packet base class\n Allows packet to reference its stack\n \"\"\"\n\n def __init__(self,\n stack=None,\n **kwa\n ):\n \"\"\"\n Initialization method for instance.\n Base class method to be overridden in subclass\n Need to add parts to packet in subclass\n\n Inherited Parameters:\n size is initial size of .packed\n\n Parameters:\n stack is I/O stack that handles this packet\n\n Inherited Attributes:\n .packed is bytearray of packed binary data\n\n Attributes:\n .stack is I/O stack that handles this packet\n\n Inherited Properties:\n .size is length of .packed\n\n\n \"\"\"\n super(Packet, self).__init__(**kwa)\n self.stack = stack\n\n\n def parse(self, raw):\n \"\"\"\n Parse raw data into .packed\n \"\"\"\n return self.size\n\n def pack(self):\n \"\"\"\n Pack into .packed\n \"\"\"\n return self.packed\n\n","repo_name":"amir17688/google_data_p2","sub_path":"73191_packeting.py_C__Users_user_Desktop_data_2_data_google_data_ioflo_ioflo_ioflo_aio_proto.py","file_name":"73191_packeting.py_C__Users_user_Desktop_data_2_data_google_data_ioflo_ioflo_ioflo_aio_proto.py","file_ext":"py","file_size_in_byte":9328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"36463465830","text":"list = [\"hi\", \"Martin\"]\nfor word in list:\n\tprint(word)\n\nfor num in [1,2,3,4]:\n\tif not num % 2 == 0:\n\t\tprint(num)\n\nnames = ['yolo', 'yili', 'QUIT', 'ntm']\n\nfor name in names:\n\tif name == 'QUIT':\n\t\tbreak\n\telif name == 'yolo':\n\t\tcontinue\n\tprint(name)","repo_name":"Mziserman/p2018","sub_path":"python/for.py","file_name":"for.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"38253970109","text":"\"\"\"\nINPUT => CONV => RELU => POOL => CONV => RELU => POOL => FC => RELU => FC\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport time\nfrom keras import models, layers\n\nfrom keras.datasets import mnist\nfrom keras.utils import np_utils\nimport numpy as np\nfrom sklearn.metrics import accuracy_score,classification_report,confusion_matrix\n\n# import tensorflow as tf\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\n#%%\n# NUM_PARALLEL_EXEC_UNITS = 4\n# config = tf.ConfigProto(intra_op_parallelism_threads=NUM_PARALLEL_EXEC_UNITS, inter_op_parallelism_threads=2,\n# allow_soft_placement=True, device_count={'CPU': NUM_PARALLEL_EXEC_UNITS})\n# session = tf.Session(config=config)\n# K.set_session(session)\n\ndef plot_digit(X, y, idx):\n img = X[idx].reshape(28,28)\n plt.imshow(img, cmap='Greys', interpolation='nearest')\n plt.annotate(y[idx], xy=(0.05, 0.85), xycoords=\"axes fraction\", color=\"blue\", fontsize=23)\n plt.show()\n\ntic=time.time()\n(train_images,train_labels), (test_images,test_labels) = mnist.load_data()\n\ntrain_images = np.array(train_images)\ntest_images = np.array(test_images)\n\n#Reshape the training and test set\ntrain_images = train_images.reshape(train_images.shape[0], 28, 28, 1)\ntest_images = test_images.reshape(test_images.shape[0], 28, 28, 1)\n\n# train_images = np.pad(train_images, ((0,0),(2,2),(2,2),(0,0)), 'constant')\n# test_images = np.pad(test_images, ((0,0),(2,2),(2,2),(0,0)), 'constant')\n\n# Normalize\ntrain_images = train_images.astype('float32')/255\ntest_images = test_images.astype('float32')/255\n\ntrain_labels = np_utils.to_categorical(train_labels, 10)\ntest_labels = np_utils.to_categorical(test_labels, 10)\n\nprint(np.array(train_labels).shape)\n\n\"\"\"\nConvolution #1. Input = 32x32x1. Output = 32x32x6 conv2d\nSubSampling #1. Input = 28x28x6. Output = 14x14x6. SubSampling is simply Average Pooling so we use avg_pool\nConvolution #2. Input = 14x14x6. Output = 10x10x16 conv2d\nSubSampling #2. Input = 10x10x16. Output = 5x5x16 avg_pool\nFully Connected #1. Input = 5x5x16. Output = 120\nFully Connected #2. Input = 120. Output = 84\nOutput 10\n\"\"\"\n\n\n#\nmodel = models.Sequential()\n\nmodel.add(layers.Conv2D(filters = 6,kernel_size=(5, 5), strides=1,activation = 'relu',input_shape = (28,28,1)))\n\nmodel.add(layers.AveragePooling2D(pool_size = 2, strides = 2, padding='valid'))\n\nmodel.add(layers.Conv2D(filters = 16,kernel_size=(5, 5), strides=1,activation = 'relu',input_shape = (14,14,6)))\n\nmodel.add(layers.AveragePooling2D(pool_size = 2, strides = 2))\n\nmodel.add(layers.Flatten())\n\nmodel.add(layers.Dense(units = 120, activation = 'relu'))\n\nmodel.add(layers.Dense(units = 84, activation = 'relu'))\n\nmodel.add(layers.Dense(units = 10, activation = 'softmax'))\n\nmodel.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])\nprint(model.summary())\n#%%\ntic=time.time()\nhist = model.fit(x=train_images,y=train_labels,\n epochs=25, batch_size=64,\n # validation_data=(test_images, test_labels),\n validation_split=0.2,\n verbose=1)\nprint('Training:'+str(time.time() - tic) + ' s')\n#%%\ntic=time.time()\ntest_score = model.evaluate(test_images, test_labels)\nprint(\"Test loss {:.4f}, accuracy {:.2f}%\".format(test_score[0], test_score[1] * 100))\nprint('Training:'+str(time.time() - tic) + ' s')\n\n#%%\n#\nf, ax = plt.subplots()\nax.plot([None] + hist.history['acc'], 'o-')\nax.plot([None] + hist.history['val_acc'], 'x-')\nax.legend(['Train acc', 'Validation acc'], loc = 'best')\nax.set_title('Training/Validation accuracy per Epoch')\nax.set_xlabel('Epoch')\nax.set_ylabel('Accuracy')\nplt.grid()\nplt.show()\n\nf, ax = plt.subplots()\nax.plot([None] + hist.history['loss'], 'o-')\nax.plot([None] + hist.history['val_loss'], 'x-')\nax.legend(['Train Loss', 'Validation Loss'], loc = 'best')\nax.set_title('Training/Validation Loss per Epoch')\nax.set_xlabel('Epoch')\nax.set_ylabel('Loss')\nplt.grid()\nplt.show()\nprint(str(time.time() - tic) + ' s')\n#%%\npredicted=model.predict(test_images,verbose=1)\npredicted=np.argmax(predicted, axis=1)\n#%%\nprint(classification_report(np.argmax(test_labels, axis=1),predicted ))\nprint(accuracy_score(np.argmax(test_labels, axis=1),predicted ))\nprint(confusion_matrix(np.argmax(test_labels, axis=1),predicted ))\n\n","repo_name":"ianmuge/dissertation-prep","sub_path":"MNIST/Lenet5.py","file_name":"Lenet5.py","file_ext":"py","file_size_in_byte":4258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"19803338187","text":"from functools import partial\nimport sys\n#sys.path.append('.')\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom timm.models.layers import trunc_normal_, DropPath\nfrom torchsummary import summary\n\nimport os\n# os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"2\"\n\n\nclass EDSR3DBlock(nn.Module):\n \"\"\"\n Building block of EDSR.\n \"\"\"\n\n def __init__(self, dim, res_scale=0.1):\n super(EDSR3DBlock, self).__init__()\n self.res_scale = res_scale\n self.net = nn.Sequential(\n nn.ReflectionPad3d(1),\n nn.Conv3d(dim, dim, kernel_size=3),\n nn.ReLU(),\n nn.ReflectionPad3d(1),\n nn.Conv3d(dim, dim, kernel_size=3),\n )\n\n def forward(self, x):\n return x + self.net(x) * self.res_scale\n\n\nclass Block(nn.Module):\n r\"\"\" ConvNeXt Block. There are two equivalent implementations:\n (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W)\n (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back\n We use (2) as we find it slightly faster in PyTorch\n \n Args:\n dim (int): Number of input channels.\n drop_path (float): Stochastic depth rate. Default: 0.0\n layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.\n \"\"\"\n def __init__(self, dim, drop_path=0., layer_scale_init_value=1e-6):\n super().__init__()\n self.dwconv = nn.Conv3d(dim, dim, kernel_size=7, padding=3, groups=dim) # depthwise conv\n self.norm = LayerNorm(dim, eps=1e-6)\n self.pwconv1 = nn.Linear(dim, 4 * dim) # pointwise/1x1 convs, implemented with linear layers\n self.act = nn.GELU()\n self.pwconv2 = nn.Linear(4 * dim, dim)\n self.gamma = nn.Parameter(layer_scale_init_value * torch.ones((dim)), \n requires_grad=True) if layer_scale_init_value > 0 else None\n self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()\n\n def forward(self, x):\n input = x\n #print('input',x.shape)\n x = self.dwconv(x) #卷积 卷积之后大小通道不变 [4, 96, 64, 64]\n #print('dwconv',x.shape)\n x = x.permute(0, 2, 3, 4, 1) # (N, C, H, W) -> (N, H, W, C) [4, 96, 64, 64])\n #print('dwconv',x.shape)\n x = self.norm(x) \n #print('norm',x.shape) #Layernorm \n x = self.pwconv1(x) #1*1卷积 [4, 64, 64, 384] 384 = dim(96) * 4 (把(4,64,64)看做整体输入线性层)\n #print('pwconv1',x.shape) #1*1卷积 [4, 64, 64, 384] 384 = dim(96) * 4 (把(4,64,64)看做整体输入线性层)\n\n x = self.act(x) #GELU\n x = self.pwconv2(x) #1*1卷积 [4, 64, 64, 384]\n #print('pwconv2',x.shape)\n if self.gamma is not None:\n x = self.gamma * x\n x = x.permute(0, 4, 1, 2,3) # (N, H, W, C) -> (N, C, H, W) [4, 96, 64, 64]\n\n x = input + self.drop_path(x) #残差\n return x\n\n\n# class Block(nn.Module):\n# r\"\"\" ConvNeXt Block. There are two equivalent implementations:\n# (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W)\n# (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back\n# We use (2) as we find it slightly faster in PyTorch\n \n# Args:\n# dim (int): Number of input channels.\n# drop_path (float): Stochastic depth rate. Default: 0.0\n# layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.\n# \"\"\"\n# def __init__(self, dim, drop_path=0., layer_scale_init_value=1e-6):\n# super().__init__()\n# self.dwconv = nn.Conv3d(dim, dim, kernel_size=7, padding=3, groups=dim) # depthwise conv\n# self.norm = LayerNorm(dim, eps=1e-6)\n# self.pwconv1 = nn.Conv3d(dim, 4*dim, kernel_size=1,padding=0)#nn.Linear(dim, 4 * dim) # pointwise/1x1 convs, implemented with linear layers\n# self.act = nn.GELU()\n# self.pwconv2 = nn.Conv3d(4*dim, dim, kernel_size=1,padding=0)#nn.Linear(4 * dim, dim)\n# self.gamma = nn.Parameter(layer_scale_init_value * torch.ones((dim)), \n# requires_grad=True) if layer_scale_init_value > 0 else None\n# self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()\n\n# def forward(self, x):\n# input = x\n# x = self.dwconv(x) #卷积 卷积之后大小通道不变 [4, 96, 64, 64]\n# x = x.permute(0, 2, 3, 4, 1) # (N, C, H, W) -> (N, H, W, C) [4, 96, 64, 64])\n# x = self.norm(x)\n# x = x.permute(0, 4, 1, 2,3) #Layernorm \n# x = self.pwconv1(x) #1*1卷积 [4, 64, 64, 384] 384 = dim(96) * 4 (把(4,64,64)看做整体输入线性层)\n# x = self.act(x) #GELU\n# x = self.pwconv2(x) #1*1卷积 [4, 64, 64, 384]\n# x = x.permute(0, 2, 3, 4, 1)\n# if self.gamma is not None:\n# x = self.gamma * x\n# x = x.permute(0, 4, 1, 2,3) # (N, H, W, C) -> (N, C, H, W) [4, 96, 64, 64]\n\n# x = input + self.drop_path(x) #残差\n# return x\n\n\n\n\nclass ConvNeXt(nn.Module):\n\n def __init__(self, in_chans=3, depths=[3, 3, 9, 3], dims=[96, 192, 384, 768], \n drop_path_rate=0., layer_scale_init_value=1e-6, out_indices=[0, 1, 2, 3],\n ):\n super().__init__()\n\n self.downsample_layers = nn.ModuleList() \n \n #stem层为transformer中的,4*4卷积,stride=4 替换resnet的池化\n stem = nn.Sequential(\n nn.Conv3d(in_chans, dims[0], kernel_size=4, stride=4),\n LayerNorm(dims[0], eps=1e-6, data_format=\"channels_first\")\n )\n \n ###stage2-stage4的3个downsample\n self.downsample_layers.append(stem)\n for i in range(3):\n downsample_layer = nn.Sequential(\n LayerNorm(dims[i], eps=1e-6, data_format=\"channels_first\"),\n nn.Conv3d(dims[i], dims[i+1], kernel_size=2, stride=2),\n )\n self.downsample_layers.append(downsample_layer)\n\n self.stages = nn.ModuleList() # 4 feature resolution stages, each consisting of multiple residual blocks\n dp_rates=[x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] \n cur = 0\n \n ##这里才用到block\n for i in range(4):\n stage = nn.Sequential(\n *[Block(dim=dims[i], drop_path=dp_rates[cur + j], \n layer_scale_init_value=layer_scale_init_value) for j in range(depths[i])]\n )\n self.stages.append(stage)\n cur += depths[i]\n\n self.out_indices = out_indices\n\n norm_layer = partial(LayerNorm, eps=1e-6, data_format=\"channels_first\")\n for i_layer in range(4):\n layer = norm_layer(dims[i_layer])\n layer_name = f'norm{i_layer}'\n self.add_module(layer_name, layer)\n\n self.apply(self._init_weights)\n\n def _init_weights(self, m):\n if isinstance(m, (nn.Conv3d, nn.Linear)):\n trunc_normal_(m.weight, std=.02)\n nn.init.constant_(m.bias, 0)\n\n def init_weights(self, pretrained=None):\n \"\"\"Initialize the weights in backbone.\n Args:\n pretrained (str, optional): Path to pre-trained weights.\n Defaults to None.\n \"\"\"\n\n def _init_weights(m):\n if isinstance(m, nn.Linear):\n trunc_normal_(m.weight, std=.02)\n if isinstance(m, nn.Linear) and m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.LayerNorm):\n nn.init.constant_(m.bias, 0)\n nn.init.constant_(m.weight, 1.0)\n\n if pretrained is None:\n self.apply(_init_weights)\n else:\n raise TypeError('pretrained must be a str or None')\n\n def forward_features(self, x):\n \n ##分类的区别,分类在卷积层输出后拉平(N, C, H, W) -> (N, C)\n # 而分割直接接卷积的输出,里面的结构模块都是一样的\n outs = []\n for i in range(4):\n x = self.downsample_layers[i](x) #[4,3,256,256]-->[4, 96, 64, 64]--->[4,192,32,32]--->[4, 384, 16, 16]--.[4,768,8,8]\n x = self.stages[i](x) #为什么不加上这一部分\n if i in self.out_indices:\n norm_layer = getattr(self, f'norm{i}')\n x_out = norm_layer(x)\n outs.append(x_out)\n\n return tuple(outs)\n\n def forward(self, x):\n x = self.forward_features(x)\n return x\n\nclass LayerNorm(nn.Module):\n #看数据输入是[n,c,w,d]还是[n,w,d,c]来决定参数channels_last or channels_first\n def __init__(self, normalized_shape, eps=1e-6, data_format=\"channels_last\"):\n super().__init__()\n self.weight = nn.Parameter(torch.ones(normalized_shape))\n self.bias = nn.Parameter(torch.zeros(normalized_shape))\n self.eps = eps\n self.data_format = data_format\n if self.data_format not in [\"channels_last\", \"channels_first\"]:\n raise NotImplementedError \n self.normalized_shape = (normalized_shape, )\n \n def forward(self, x):\n if self.data_format == \"channels_last\":\n return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)\n elif self.data_format == \"channels_first\":\n u = x.mean(1, keepdim=True)\n s = (x - u).pow(2).mean(1, keepdim=True)\n x = (x - u) / torch.sqrt(s + self.eps)\n x = self.weight[:, None, None,None] * x + self.bias[:, None, None,None]\n return x\n\n\nclass Convnext3D_isotropic(nn.Module):\n \"\"\"\n PyTorch Module for EDSR, https://arxiv.org/pdf/1707.02921.\n \"\"\"\n\n def __init__(self, in_channels=1, out_channels=1, ngf=96, n_blocks=32, res_scale=0.1, layer_scale_init_value=1e-6,\n depths=[2,2,2,2,2,2],dims=[96,96,96,96,96,96]):\n super(Convnext3D_isotropic, self).__init__()\n\n self.head = nn.Sequential(\n nn.ReflectionPad3d(1),\n nn.Conv3d(in_channels, ngf, kernel_size=3),\n )\n self.body=nn.ModuleList()\n for i in range(len(depths)):\n body = nn.Sequential(\n *[Block(dim=dims[i], drop_path=0.1, \n layer_scale_init_value=layer_scale_init_value) for j in range(depths[i])],\n nn.ReflectionPad3d(1),\n nn.Conv3d(ngf, ngf, kernel_size=3),)\n self.body.append(body)\n\n\n\n\n self.tail = nn.Sequential(\n nn.ReflectionPad3d(1),\n nn.Conv3d(ngf, out_channels, kernel_size=3)\n )\n\n # mean value of DIV2K\n self.register_buffer(\n name='mean',\n tensor=torch.tensor([[[0.4488]], [[0.4371]], [[0.4040]]],\n requires_grad=False)\n )\n\n def __normalize(self, x):\n x.sub_(self.mean.detach())\n\n def __denormalize(self, x):\n x.add_(self.mean.detach())\n\n def forward(self, x):\n # self.__normalize(x)\n\n x = self.head(x)\n x0=x\n for i in range(len(self.body)):\n x=self.body[i](x)+x\n print(i,x.shape)\n x=x+x0\n x = self.tail(x)\n\n # self.__denormalize(x)\n\n return x\n\n\n\n\n\n\nclass Convnext3D(nn.Module):\n \"\"\"\n PyTorch Module for EDSR, https://arxiv.org/pdf/1707.02921.\n \"\"\"\n\n def __init__(self, in_channels=1, out_channels=1, ngf=96,layer_scale_init_value=1e-6,\n depths=[6,6,6,6,6,6]):\n super(Convnext3D, self).__init__()\n\n self.head = nn.Conv3d(in_channels, ngf, 3,1,1)\n \n self.body=nn.ModuleList()\n for i in range(len(depths)):\n body = nn.Sequential(\n *[Block(dim=ngf, drop_path=0.1, \n layer_scale_init_value=layer_scale_init_value) for j in range(depths[i])],\n nn.Conv3d(ngf, ngf, 3,1,1),)\n self.body.append(body)\n\n self.conv_after_body = nn.Conv3d(ngf,ngf, 3, 1, 1)\n\n self.tail =nn.Conv3d(ngf, out_channels, 3,1,1)\n\n\n self.apply(self._init_weights)\n def _init_weights(self, m):\n if isinstance(m, (nn.Conv3d, nn.Linear)):\n trunc_normal_(m.weight, std=.02)\n nn.init.constant_(m.bias, 0)\n\n def __denormalize(self, x):\n x.add_(self.mean.detach())\n\n def forward(self, x):\n # self.__normalize(x)\n input=x\n x = self.head(x)\n x0=x\n for body in self.body:\n x=body(x)+x\n #print(x.shape)\n x=self.conv_after_body(x)+x0\n x = self.tail(x)+input\n\n # self.__denormalize(x)\n\n return x\n\n\n\nclass Convnext3D_stem(nn.Module):\n \"\"\"\n PyTorch Module for EDSR, https://arxiv.org/pdf/1707.02921.\n \"\"\"\n\n def __init__(self, in_channels=1, out_channels=1, ngf=96,layer_scale_init_value=1e-6,\n depths=[6,6,6,6,6,6]):\n super(Convnext3D_stem, self).__init__()\n\n self.head = nn.Conv3d(ngf, ngf, 3,1,1)##使用stem时这里改为in_channels->ngf\n \n self.body=nn.ModuleList()\n for i in range(len(depths)):\n body = nn.Sequential(\n *[Block(dim=ngf, drop_path=0.1, \n layer_scale_init_value=layer_scale_init_value) for j in range(depths[i])],\n nn.Conv3d(ngf, ngf, 3,1,1),)\n self.body.append(body)\n\n self.conv_after_body = nn.Conv3d(ngf,ngf, 3, 1, 1)\n self.stem=nn.Conv3d(in_channels,ngf,2,2,0)\n self.tail =nn.Conv3d(ngf, out_channels, 3,1,1)\n self.up=nn.ConvTranspose3d(ngf,ngf,2,2,0)\n\n\n self.apply(self._init_weights)\n def _init_weights(self, m):\n if isinstance(m, (nn.Conv3d, nn.Linear)):\n trunc_normal_(m.weight, std=.02)\n nn.init.constant_(m.bias, 0)\n\n def __denormalize(self, x):\n x.add_(self.mean.detach())\n\n def forward(self, x):\n # self.__normalize(x)\n input=x\n x = self.stem(x)\n #print('stem',x.shape)\n x=self.head(x)\n x0=x\n for body in self.body:\n x=body(x)+x\n #print(x.shape)\n x=self.conv_after_body(x)+x0\n\n x=self.up(x)\n x = self.tail(x)+input\n\n # self.__denormalize(x)\n\n return x\n\n\n\n\n\n\n\nfrom torchstat import stat\n \nif __name__ == '__main__':\n #data = torch.randn((1,3,256,256,256))\n #model = ConvNeXt(in_chans=1, depths=[1, 1, 3, 1], dims=[16, 32, 64, 128]).cuda()\n model =Convnext3D_stem(ngf=48,depths=[3,3,9,3]).cuda()\n # out = model(data)\n # print(out)\n\n \n # 导入模型,输入一张输入图片的尺寸\n #stat(model, input_size=[1,96,96,96])\n\n\n\n print(summary(model,[1,96,96,96]))\n data = torch.randn(2,1,96,96,96).cuda()\n y=model(data)\n # block = Block(1)\n # out = block(data)\n # print(out)\n # depths=[3, 3, 9, 3]\n # dp_rates=[x.item() for x in torch.linspace(0, 1, sum(depths))] \n # print(dp_rates)","repo_name":"yunzxu/Ultra-low-Dose-PET-Imaging-Challenge","sub_path":"pet/models/convnext.py","file_name":"convnext.py","file_ext":"py","file_size_in_byte":15148,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"8893429872","text":"# encoding: utf-8\n\ndef anchor_relative_position(startpoint:set, endpoint:set, anchorpoint:set) -> int:\n \"\"\"\n インテラクション(start,end)のポジションとanchorのポジションからanchorの相対値をもとめる\n Args:\n startpoint: interactionのstart座標(x,y)\n endpoint: interactionのend座標(x,y)\n anchorpoint: anchorの座標(x,y)\n Returns:\n Int: anchorの相対位置\n \"\"\"\n node1_node2_pos = (startpoint, endpoint)\n anchor_pos = anchorpoint\n node1_node2_dist = sum((p2 - p1) ** 2 for p1, p2 in zip(*node1_node2_pos)) ** 0.5\n node1_anchor_dist = sum((p2 - p1) ** 2 for p1, p2 in zip(node1_node2_pos[0], anchor_pos)) ** 0.5\n return node1_anchor_dist / node1_node2_dist","repo_name":"dogrun-inc/txt2gpml","sub_path":"src/anchor_position.py","file_name":"anchor_position.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"77"}
+{"seq_id":"9223982383","text":"# Program to check whether a person is in profit or loss\n\ncostPrice = int(input(\"Cost Price of a product? : \"))\nsellingPrice = int(input(\"Selling Price of a product? : \"))\n\njhol = costPrice - sellingPrice\n\nif jhol > 0:\n print(\"Seller is in loss by Rs.{}\".format(jhol))\nelif jhol < 0:\n jhol = int(jhol*-1)\n print(\"Seller is in profit by Rs.{}\".format(jhol))\nelse:\n print(\"No profit nor loss\")\n","repo_name":"bhupendpatil/Practice","sub_path":"Python/Program to check whether a person is in profit or loss.py","file_name":"Program to check whether a person is in profit or loss.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"77"}
+{"seq_id":"74878164727","text":"from flask import Flask\nfrom flask import render_template, request, redirect, session, jsonify, url_for\nimport networkx as nx\nimport json\nfrom flaskext.mysql import MySQL\nfrom datetime import datetime\nimport hashlib\nfrom flask_jwt_extended import JWTManager, create_access_token\nfrom email.message import EmailMessage\nimport ssl\nimport smtplib\nimport os\n\napp = Flask(__name__)\n\napp.secret_key = \"digitalforge\"\n\n# AGREGAR UN CONTROL DE TIEMPO DE LA SESION, (SOLO SI ES REQUERIDO)\n\nmysql = MySQL()\n\napp.config['MYSQL_DATABASE_HOST'] = 'reto-senasoft.mysql.database.azure.com'\napp.config['MYSQL_DATABASE_PORT'] = 3306\napp.config['MYSQL_DATABASE_USER'] = 'camilo'\napp.config['MYSQL_DATABASE_PASSWORD'] = 'Reto1234'\napp.config['MYSQL_DATABASE_DB'] = 'reto_ssoft'\n\nmysql.init_app(app)\n\nconexion = mysql.connect()\ncursor = conexion.cursor()\n\n@app.route('/index')\ndef index():\n if session.get(\"logueado\") and session.get(\"verificado\") == 1:\n return render_template('sitio/index.html')\n else:\n return redirect('/')\n\n@app.route('/')\ndef login():\n return render_template('auth/login.html')\n\n@app.route('/registro')\ndef registro():\n return render_template('auth/registro.html')\n\n@app.route('/formAdd')\ndef formAdd():\n if session.get(\"logueado\"):\n return render_template('sitio/agregarUbi.html')\n else:\n return redirect('/')\n\n@app.route('/addUbicacion', methods=['POST'])\ndef addUbicacion():\n if session.get(\"logueado\") and session.get(\"verificado\") == 1:\n nombre = request.form['nombreUbi']\n posX = request.form['latitud']\n posY = request.form['longitud']\n\n conexion = mysql.connect()\n cursor = conexion.cursor()\n\n sql = f\"INSERT INTO ubicaciones (nombre, posX, posY) VALUES ('{nombre}', '{posX}', '{posY}')\"\n cursor.execute(sql)\n conexion.commit()\n conexion.close()\n return redirect('/formAdd')\n else:\n return redirect('/')\n\n\n@app.route('/data')\ndef get_data():\n cursor.execute(\"SELECT * FROM ubicaciones\")\n ubicaciones = cursor.fetchall()\n\n cursor.execute(\"SELECT * FROM conexiones\")\n conexiones = cursor.fetchall()\n\n data = []\n for ubicacion in ubicaciones:\n nombre, posX, posY = ubicacion\n data.append({\n \"nombre\": nombre,\n \"posX\": posX,\n \"posY\": posY\n })\n\n print(\"Ubicaciones:\", ubicaciones)\n print(\"Conexiones:\", conexiones)\n\n\n return jsonify({\"ubicaciones\": data, \"conexiones\": conexiones})\n\n# Crea la ruta para para visuaizar conexiones y formulario\n\n@app.route('/conexionesUbi')\ndef conexionesUbi():\n sql = \"SELECT * FROM conexiones\"\n cursor.execute(sql)\n conexion.commit()\n resultados = cursor.fetchall()\n\n return render_template('sitio/conexionesUbi.html', datosCon = resultados)\n\n# Agrega los datos de las conexiones en la BD\n\n@app.route('/crearConexiones', methods = ['POST'])\ndef crearConexiones():\n ubicacion1 = request.form['ubicacion1']\n ubicacion2 = request.form['ubicacion2']\n peso = request.form['peso']\n\n sql = f\"INSERT INTO conexiones (ubicacion1, ubicacion2, peso) VALUES ('{ubicacion1}','{ubicacion2}','{peso}')\"\n cursor.execute(sql)\n conexion.commit()\n\n return redirect('/conexionesUbi')\n\n@app.route('/addJSON')\ndef addJSON():\n sql = \"SELECT * FROM ubicaciones\"\n cursor.execute(sql)\n conexion.commit()\n resultados = cursor.fetchall()\n \n return render_template('sitio/cargarJson.html', datosUbi = resultados)\n\n@app.route('/cargar_json', methods=['POST'])\ndef cargar_json():\n # Verificar si se envió un archivo JSON\n if 'json_file' not in request.files:\n return \"No se seleccionó ningún archivo JSON.\"\n\n archivo = request.files['json_file']\n\n # Verificar si el archivo tiene un nombre y una extensión válidos\n if archivo.filename == '':\n return \"El archivo no tiene un nombre válido.\"\n\n if archivo.filename.endswith('.json'):\n # Procesar el archivo JSON\n try:\n data = archivo.read() # Leer el contenido del archivo\n datos_json = json.loads(data) # Cargar el JSON en un diccionario\n\n # Inicializa la conexión a la base de datos\n conexion = mysql.connect()\n cursor = conexion.cursor()\n\n # Procesa las ubicaciones y guárdalas en la tabla 'ubicaciones'\n for ubicacion in datos_json['ubicaciones']:\n nombre = ubicacion['nombre']\n posX = ubicacion['posX']\n posY = ubicacion['posY']\n cursor.execute(\"INSERT INTO ubicaciones (nombre, posX, posY) VALUES (%s, %s, %s)\", (nombre, posX, posY))\n conexion.commit()\n\n # Procesa las conexiones y guárdalas en la tabla 'conexiones'\n for conexionn in datos_json['conexiones']:\n ubicacion1 = conexionn['ubicacion1']\n ubicacion2 = conexionn['ubicacion2']\n peso = conexionn['peso']\n cursor.execute(\"INSERT INTO conexiones (ubicacion1, ubicacion2, peso) VALUES (%s, %s, %s)\", (ubicacion1, ubicacion2, peso))\n conexion.commit()\n\n cursor.close() # Cierra el cursor\n conexion.close() # Cierra la conexión\n\n return \"Archivo JSON cargado y procesado correctamente.\"\n except Exception as e:\n return f\"Error al procesar el archivo JSON: {str(e)}\"\n else:\n return \"El archivo no tiene una extensión JSON válida.\"\n\n# Calcular la ruta mas corta\n\n@app.route('/rutaCorta', methods = ['POST'])\ndef rutaCorta():\n # Consulta las ubicaciones y conexiones desde la base de datos\n cursor.execute('SELECT * FROM ubicaciones')\n ubicaciones = cursor.fetchall()\n\n\n cursor.execute('SELECT * FROM conexiones')\n conexiones = cursor.fetchall()\n\n\n # Crea un diccionario que contiene los datos\n data = {\n \"ubicaciones\": [],\n \"conexiones\": [],\n \"inicio\": \"\" # Establece el nodo de inicio\n }\n\n # Procesa las ubicaciones y agrega al diccionario\n for ubicacion in ubicaciones:\n nombre, posX, posY = ubicacion\n data[\"ubicaciones\"].append({\n \"nombre\": nombre,\n \"posX\": posX,\n \"posY\": posY\n })\n\n # Procesa las conexiones y agrega al diccionario\n for conexion in conexiones:\n ubicacion1, ubicacion2, peso = conexion\n data[\"conexiones\"].append({\n \"ubicacion1\": ubicacion1,\n \"ubicacion2\": ubicacion2,\n \"peso\": peso\n })\n\n\n # Cierra la conexión a la base de datos\n\n\n # Convierte los datos en formato JSON\n json_data = json.dumps(data)\n\n # Crea un gráfico vacío\n G = nx.Graph()\n\n # Agrega los nodos desde el JSON\n for ubicacion in data[\"ubicaciones\"]:\n nombre = ubicacion[\"nombre\"]\n G.add_node(nombre, posX=ubicacion[\"posX\"], posY=ubicacion[\"posY\"])\n\n # Agrega las aristas desde el JSON\n for conexion in data[\"conexiones\"]:\n ubicacion1 = conexion[\"ubicacion1\"]\n ubicacion2 = conexion[\"ubicacion2\"]\n peso = conexion[\"peso\"]\n G.add_edge(ubicacion1, ubicacion2, weight=peso)\n\n\n\n # Encuentra la ruta más corta entre los nodos especificados en el JSON\n start_node = request.form['ubicacion1']\n end_node = request.form['ubicacion2'] # Puedes cambiar esto según tus necesidades\n\n\n\n print(G.nodes())\n\n # Puedes cambiar esto según tus necesidades\n\n shortest_path = nx.shortest_path(G, start_node, end_node, weight='weight')\n shortest_distance = nx.shortest_path_length(G, start_node, end_node, weight='weight')\n\n print(f'Ruta más corta: {shortest_path}')\n print(f'Distancia más corta: {shortest_distance}')\n\n return render_template('sitio/index.html', mensaje = shortest_path)\n\n\n\n\n#Verificaion de cuenta por correo\n\n\n# Configura la clave secreta para JWT (debe ser segura en un entorno real)\napp.config['SECRET_KEY'] = os.urandom(24)\n\n# Configura el JWT Manager\njwt = JWTManager(app)\n\n# Ruta para registrar un nuevo usuario y luego enviar el correo de verificación\n@app.route('/registro', methods=['POST'])\ndef register():\n try:\n # Procesa el formulario de registro y almacena los datos en la base de datos\n nombre = request.form['nombre']\n correo = request.form['correo']\n contrasena = request.form['contrasena']\n cifrada = hashlib.sha512(contrasena.encode(\"utf-8\")).hexdigest()\n\n # Crea un token de verificación usando JWT\n verification_token = create_access_token(identity=correo)\n print(verification_token)\n\n # Inserta los datos del usuario en tu base de datos\n conexion = mysql.connect()\n cursor = conexion.cursor()\n cursor.execute(\"INSERT INTO usuarios (full_name, email, password, token, verified) VALUES (%s, %s, %s, %s, %s)\", (nombre, correo, cifrada, verification_token, 0))\n conexion.commit()\n cursor.close()\n conexion.close()\n\n # Aquí se envía un correo electrónico de verificación con el token\n asunto = 'Verificación de correo'\n\n # Crea un mensaje de correo electrónico\n cuerpo = f'Por favor, haga clic en el siguiente enlace para verificar su correo: http://127.0.0.1:5000/verify_email/{verification_token}'\n\n \n email_emisor = 'cdvanegas830@misena.edu.co' # Correo de prácticas\n email_contrasena = 'sagenav0'\n\n em = EmailMessage()\n em['From'] = email_emisor\n em['To'] = correo\n em['Subject'] = asunto\n em.set_content(cuerpo)\n\n # Configura el contexto SSL\n contexto = ssl.create_default_context()\n\n # Envía el correo electrónico\n with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=contexto) as smtp:\n smtp.login(email_emisor, email_contrasena)\n smtp.sendmail(email_emisor, correo, em.as_string())\n\n return render_template('verificacionToken/verificacion.html')\n\n except Exception as e:\n print(str(e))\n return \"Error al registrar al usuario.\"\n\n\n# Ruta para verificar el token y redirigir al usuario a la página principal\n@app.route('/verify_email/', methods=['GET'])\ndef verify_email(token):\n print(token)\n try:\n # Verifica si el token existe en la base de datos\n conexion = mysql.connect()\n cursor = conexion.cursor()\n cursor.execute(\"SELECT email FROM usuarios WHERE token = %s\", (token,))\n correo = cursor.fetchone()\n cursor.close()\n print(correo)\n\n if correo:\n # Token válido, marca la cuenta de usuario como verificada en la base de datos\n cursor = conexion.cursor()\n cursor.execute(\"UPDATE usuarios SET verified = 1 WHERE email = %s\", (correo[0],))\n conexion.commit()\n cursor.close()\n conexion.close()\n\n # Redirige al usuario a la página principal\n return redirect('/index')\n else:\n return \"Token de verificación no válido.\"\n\n except Exception as e:\n print(str(e))\n return \"Error al verificar el token.\"\n\n# Ruta para la página principal\n@app.route('/main_page', methods=['GET'])\ndef main_page():\n return \"Bienvenido a la página principal.\"\n\n\n# Validacion de credenciales\n\n@app.route('/validationLogin', methods = ['POST'])\ndef ValidationLogin():\n if request.method == 'POST':\n correo = request.form['correo']\n contrasena = request.form['contrasena']\n\n encriptada = hashlib.sha512(contrasena.encode(\"utf-8\")).hexdigest()\n\n conexion = mysql.connect()\n cursor = conexion.cursor()\n\n consulta = f\"SELECT * FROM usuarios WHERE email = '{correo}' AND verified = 1\"\n cursor.execute(consulta)\n resultado = cursor.fetchall()\n conexion.commit()\n\n print(resultado)\n\n if len(resultado) > 0:\n if encriptada == resultado[0][2]:\n session[\"logueado\"] = True\n session[\"user_name\"] = resultado[0][0]\n session[\"verificado\"] = resultado[0][4]\n\n if session[\"logueado\"] == True:\n return render_template(\"sitio/index.html\")\n else:\n return render_template(\"auth/login.html\", mensaje = \"Acesso denegado\")\n\n else:\n return render_template('auth/login.html', mensaje = \"Acesso denegado\")\n else:\n return render_template('auth/login.html', mensaje = \"Acesso denegado\")\n\n# Cierra la sesion\n\n@app.route('/cerrarSesion')\ndef cerrarSesion():\n session.clear()\n return redirect('/')\n\n\n\ndef pagina_no_encontrada(error):\n return render_template('errores/404.html'), 404\n\ndef inicializador_app():\n app.register_error_handler(404, pagina_no_encontrada)\n return app","repo_name":"Horux69/reto_senasoft","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12783,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"24678395535","text":"# @mark.steps\n# ----------------------------------------------------------------------------\n# STEPS:\n# ----------------------------------------------------------------------------\nimport os\nimport re\n\nfrom behave import given, then, when\nfrom pyshould import should, should_not\n\nfrom servicebindingoperator import Servicebindingoperator\nfrom dboperator import DbOperator\nfrom openshift import Openshift\nfrom postgres_db import PostgresDB\nfrom namespace import Namespace\nfrom nodejs_application import NodeJSApp\nfrom service_binding_request import ServiceBindingRequest\nimport time\n\n\n# STEP\n@given(u'Namespace \"{namespace_name}\" is used')\ndef given_namespace_is_used(context, namespace_name):\n namespace = Namespace(namespace_name)\n if not namespace.is_present():\n print(\"Namespace is not present, creating namespace: {}...\".format(namespace_name))\n namespace.create() | should.be_truthy.desc(\"Namespace {} is created\".format(namespace_name))\n print(\"Namespace {} is created!!!\".format(namespace_name))\n context.namespace = namespace\n\n\n# STEP\n@given(u'Namespace [{namespace_env}] is used')\ndef given_namespace_from_env_is_used(context, namespace_env):\n env = os.getenv(namespace_env, \"\")\n env | should_not.be_none.desc(f\"{namespace_env} env variable is set\")\n print(f\"{namespace_env} = {env}\")\n given_namespace_is_used(context, env)\n\n\n# STEP\nsbo_is_running_in_namespace_step = u'Service Binding Operator is running in \"{operator_namespace}\" namespace'\n\n\n@given(sbo_is_running_in_namespace_step)\n@when(sbo_is_running_in_namespace_step)\ndef sbo_is_running_in_namespace(context, operator_namespace):\n \"\"\"\n Checks if the SBO is up and running in the given namespace\n \"\"\"\n sb_operator = Servicebindingoperator(namespace=operator_namespace)\n sb_operator.is_running() | should.be_truthy.desc(\"Service Binding Operator is running\")\n print(\"Service binding operator is running!!!\")\n\n\n# STEP\nsbo_is_running_in_namespace_from_env_step = u'Service Binding Operator is running in [{operator_namespace_env}] namespace'\n\n\n@given(sbo_is_running_in_namespace_from_env_step)\n@when(sbo_is_running_in_namespace_from_env_step)\ndef sbo_is_running_in_namespace_from_env(context, operator_namespace_env):\n env = os.getenv(operator_namespace_env, \"\")\n env | should_not.be_none.desc(f\"{operator_namespace_env} env variable is set\")\n print(f\"{operator_namespace_env} = {env}\")\n sbo_is_running_in_namespace(context, env)\n\n\n# STEP\nsbo_is_running_step = u'Service Binding Operator is running'\n\n\n@given(sbo_is_running_step)\n@when(sbo_is_running_step)\ndef sbo_is_running(context):\n context.namespace | should_not.be_none.desc(\"Namespace set in context\")\n sbo_is_running_in_namespace(context, context.namespace.name)\n\n\n# STEP\n@given(u'PostgreSQL DB operator is installed')\ndef given_db_operator_is_installed(context):\n db_operator = DbOperator()\n if not db_operator.is_running():\n print(\"DB operator is not installed, installing...\")\n db_operator.install_catalog_source() | should.be_truthy.desc(\"DB catalog source installed\")\n db_operator.install_operator_subscription() | should.be_truthy.desc(\"DB operator subscription installed\")\n db_operator.is_running(wait=True) | should.be_truthy.desc(\"DB operator installed\")\n print(\"PostgresSQL DB operator is running!!!\")\n\n\n# STEP\nimported_nodejs_app_is_running_step = u'Imported Nodejs application \"{application_name}\" is running'\n\n\n@given(imported_nodejs_app_is_running_step)\n@when(imported_nodejs_app_is_running_step)\ndef imported_nodejs_app_is_running(context, application_name):\n namespace = context.namespace\n application = NodeJSApp(application_name, namespace.name)\n if not application.is_running():\n print(\"application is not running, trying to import it\")\n application.install() | should.be_truthy.desc(\"Application is installed\")\n application.is_running(wait=True) | should.be_truthy.desc(\"Application is running\")\n print(\"Nodejs application is running!!!\")\n application.get_db_name_from_api() | should_not.be_none\n context.nodejs_app_original_generation = application.get_observed_generation()\n context.nodejs_app_original_pod_name = application.get_running_pod_name()\n context.nodejs_app = application\n\n\n# STEP\nimported_nodejs_app_is_not_running_step = u'Imported Nodejs application \"{application_name}\" is not running'\n\n\n@given(imported_nodejs_app_is_not_running_step)\n@when(imported_nodejs_app_is_not_running_step)\ndef imported_nodejs_app_is_not_running(context, application_name):\n namespace = context.namespace\n application = NodeJSApp(application_name, namespace.name)\n application.is_running() | should.be_falsy.desc(\"Aplication not running\")\n\n\n# STEP\ndb_instance_is_running_step = u'DB \"{db_name}\" is running'\n\n\n@given(db_instance_is_running_step)\n@when(db_instance_is_running_step)\ndef db_instance_is_running(context, db_name):\n namespace = context.namespace\n\n db = PostgresDB(db_name, namespace.name)\n if not db.is_running():\n db.create() | should.be_truthy.desc(\"Postgres DB created\")\n db.is_running(wait=True) | should.be_truthy.desc(\"Postgres DB is running\")\n print(f\"DB {db_name} is running!!!\")\n\n\n# STEP\nsbr_is_applied_step = u'Service Binding Request is applied to connect the database and the application'\n\n\n@given(sbr_is_applied_step)\n@when(sbr_is_applied_step)\ndef sbr_is_applied(context):\n sbr_yaml = context.text\n sbr = ServiceBindingRequest()\n if context.__contains__(\"nodejs_app\"):\n application = context.nodejs_app\n context.nodejs_app_original_generation = application.get_observed_generation()\n context.nodejs_app_original_pod_name = application.get_running_pod_name()\n sbr.create(sbr_yaml) | should.be_truthy.desc(\"Service Binding Request Created\")\n\n\n# STEP\n@then(u'application should be re-deployed')\ndef then_application_redeployed(context):\n application = context.nodejs_app\n application.get_redeployed_pod_name(context.nodejs_app_original_pod_name) | should_not.be_none.desc(\n \"There is a running pod of the application different from the original one before redeployment.\")\n\n\n# STEP\n@then(u'application should be connected to the DB \"{db_name}\"')\ndef then_app_is_connected_to_db(context, db_name):\n application = context.nodejs_app\n app_db_name = application.get_db_name_from_api()\n app_db_name | should.be_equal_to(db_name)\n\n\n# STEP\n@then(u'jsonpath \"{json_path}\" of Service Binding Request \"{sbr_name}\" should be changed to \"{json_value_regex}\"')\ndef then_sbo_jsonpath_is(context, json_path, sbr_name, json_value_regex):\n openshift = Openshift()\n openshift.search_resource_in_namespace(\"servicebindingrequests\", sbr_name, context.namespace.name) | should_not.be_none.desc(\"SBR {sbr_name} exists\")\n result = openshift.get_resource_info_by_jsonpath(\"sbr\", sbr_name, context.namespace.name, json_path, wait=True)\n result | should_not.be_none.desc(\"jsonpath result\")\n re.fullmatch(json_value_regex, result) | should_not.be_none.desc(\"SBO jsonpath result \\\"{result}\\\" should match \\\"{json_value_regex}\\\"\")\n\n\n# STEP\n@then(u'jq \"{jq_expression}\" of Service Binding Request \"{sbr_name}\" should be changed to \"{json_value_regex}\"')\ndef then_sbo_jq_is(context, jq_expression, sbr_name, json_value_regex):\n openshift = Openshift()\n openshift.search_resource_in_namespace(\"servicebindingrequests\", sbr_name, context.namespace.name) | should_not.be_none.desc(\"SBR {sbr_name} exists\")\n result = openshift.get_resource_info_by_jq(\"sbr\", sbr_name, context.namespace.name, jq_expression, wait=True)\n result | should_not.be_none.desc(\"jq result\")\n re.fullmatch(json_value_regex, result) | should_not.be_none.desc(\"SBO jq result \\\"{result}\\\" should match \\\"{json_value_regex}\\\"\")\n\n\n# STEP\n@then(u'\"{app_name}\" deployment must contain SBR name \"{sbr_name1}\" and \"{sbr_name2}\"')\ndef then_envFrom_contains(context, app_name, sbr_name1, sbr_name2):\n time.sleep(60)\n openshift = Openshift()\n result = openshift.get_deployment_envFrom_info(app_name, context.namespace.name)\n result | should.be_equal_to(\"[map[secretRef:map[name:binding-request-1]] map[secretRef:map[name:binding-request-2]]]\")\\\n .desc(f'{app_name} deployment should contain secretRef: {sbr_name1} and {sbr_name2}')\n","repo_name":"ajm01/service-binding-operator","sub_path":"test/acceptance/features/steps/steps.py","file_name":"steps.py","file_ext":"py","file_size_in_byte":8308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"77"}
+{"seq_id":"3629048760","text":"from odoo import SUPERUSER_ID, api, fields, models, registry, _\nfrom odoo.tools import add, float_compare, frozendict, split_every\nfrom odoo.addons.stock.models.stock_rule import ProcurementException\nfrom collections import defaultdict\nfrom dateutil.relativedelta import relativedelta\nfrom itertools import groupby\n\n\nclass StockRule(models.Model):\n _inherit = 'stock.rule'\n\n @api.model\n def _run_buy(self, procurements):\n \"\"\"\n Overwrite the standard function to modify something in the middle of the standard behaviour\n Change only executed if come from \"Orderpoint\" (Context)\n \"\"\"\n if self._context.get('from_orderpoint'):\n account_group_env = self.env['account.analytic.group']\n procurements_by_po_domain = defaultdict(list)\n errors = []\n for procurement, rule in procurements:\n\n # Get the schedule date in order to find a valid seller\n procurement_date_planned = fields.Datetime.from_string(procurement.values['date_planned'])\n\n supplier = False\n if procurement.values.get('supplierinfo_id'):\n supplier = procurement.values['supplierinfo_id']\n else:\n supplier = procurement.product_id.with_company(procurement.company_id.id)._select_seller(\n partner_id=procurement.values.get(\"supplierinfo_name\"),\n quantity=procurement.product_qty,\n date=procurement_date_planned.date(),\n uom_id=procurement.product_uom)\n\n # Fall back on a supplier for which no price may be defined. Not ideal, but better than\n # blocking the user.\n supplier = supplier or procurement.product_id._prepare_sellers(False).filtered(\n lambda s: not s.company_id or s.company_id == procurement.company_id\n )[:1]\n\n if not supplier:\n msg = _(\n 'There is no matching vendor price to generate the purchase order for product %s'\n ' (no vendor defined, minimum quantity not reached, dates not valid, ...). '\n 'Go on the product form and complete the list of vendors.') % (\n procurement.product_id.display_name)\n errors.append((procurement, msg))\n\n partner = supplier.name\n # we put `supplier_info` in values for extensibility purposes\n procurement.values['supplier'] = supplier\n procurement.values['propagate_cancel'] = rule.propagate_cancel\n\n domain = rule._make_po_get_domain(procurement.company_id, procurement.values, partner)\n procurements_by_po_domain[domain].append((procurement, rule))\n\n if errors:\n raise ProcurementException(errors)\n\n for domain, procurements_rules in procurements_by_po_domain.items():\n # Get the procurements for the current domain.\n # Get the rules for the current domain. Their only use is to create\n # the PO if it does not exist.\n procurements, rules = zip(*procurements_rules)\n\n # Get the set of procurement origin for the current domain.\n origins = set([p.origin for p in procurements])\n # Check if a PO exists for the current domain.\n po = self.env['purchase.order'].sudo().search([dom for dom in domain], limit=1)\n company_id = procurements[0].company_id\n if not po:\n positive_values = [p.values for p in procurements if\n float_compare(p.product_qty, 0.0, precision_rounding=p.product_uom.rounding) >= 0]\n if positive_values:\n # We need a rule to generate the PO. However the rule generated\n # the same domain for PO and the _prepare_purchase_order method\n # should only uses the common rules's fields.\n vals = rules[0]._prepare_purchase_order(company_id, origins, positive_values)\n # The company_id is the same for all procurements since\n # _make_po_get_domain add the company in the domain.\n # We use SUPERUSER_ID since we don't want the current user to be follower of the PO.\n # Indeed, the current user may be a user without access to Purchase, or even be a portal user.\n po = self.env['purchase.order'].with_company(company_id).with_user(SUPERUSER_ID).create(vals)\n # When Purchase order is created the bussiness center should be set\n acc_group = account_group_env.search([('picking_type_id', '=', po.picking_type_id.id)], limit=1)\n po.analytic_group_id = acc_group\n po.auto_send = True\n else:\n # If a purchase order is found, adapt its `origin` field.\n if po.origin:\n missing_origins = origins - set(po.origin.split(', '))\n if missing_origins:\n po.write({'origin': po.origin + ', ' + ', '.join(missing_origins)})\n else:\n po.write({'origin': ', '.join(origins)})\n\n procurements_to_merge = self._get_procurements_to_merge(procurements)\n procurements = self._merge_procurements(procurements_to_merge)\n\n po_lines_by_product = {}\n # The lines by default will be grouped by product uom,\n # but in the new behaviour should be by the cheaper supplier uom,\n # value previously changed in the procurement. Only will be set the behaviour is come from orderpoint\n if self._context.get('from_orderpoint'):\n grouped_po_lines = groupby(\n po.order_line.filtered\n (lambda l: not l.display_type and l.product_uom == procurement.product_uom).sorted(\n lambda l: l.product_id.id), key=lambda l: l.product_id.id)\n else:\n grouped_po_lines = groupby(\n po.order_line.filtered\n (lambda l: not l.display_type and l.product_uom == l.product_id.uom_po_id).sorted(\n lambda l: l.product_id.id), key=lambda l: l.product_id.id)\n for product, po_lines in grouped_po_lines:\n po_lines_by_product[product] = self.env['purchase.order.line'].concat(*list(po_lines))\n po_line_values = []\n for procurement in procurements:\n po_lines = po_lines_by_product.get(procurement.product_id.id, self.env['purchase.order.line'])\n po_line = po_lines._find_candidate(*procurement)\n\n if po_line:\n # If the procurement can be merge in an existing line. Directly\n # write the new values on it.\n vals = self._update_purchase_order_line(procurement.product_id,\n procurement.product_qty, procurement.product_uom,\n company_id,\n procurement.values, po_line)\n po_line.write(vals)\n else:\n if float_compare(procurement.product_qty, 0,\n precision_rounding=procurement.product_uom.rounding) <= 0:\n # If procurement contains negative quantity, don't create a new line that would contain negative qty\n continue\n # If it does not exist a PO line for current procurement.\n # Generate the create values for it and add it to a list in\n # order to create it in batch.\n partner = procurement.values['supplier'].name\n po_line_values.append \\\n (self.env['purchase.order.line']._prepare_purchase_order_line_from_procurement(\n procurement.product_id, procurement.product_qty,\n procurement.product_uom, procurement.company_id,\n procurement.values, po))\n # Check if we need to advance the order date for the new line\n order_date_planned = procurement.values['date_planned'] - relativedelta(\n days=procurement.values['supplier'].delay)\n if fields.Date.to_date(order_date_planned) < fields.Date.to_date(po.date_order):\n po.date_order = order_date_planned\n self.env['purchase.order.line'].sudo().create(po_line_values)\n else:\n super(StockRule, self)._run_buy(procurements)\n\n def _update_purchase_order_line(self, product_id, product_qty, product_uom, company_id, values, line):\n \"\"\"\n Overwrite the standard function to modify something in the middle of the standard behaviour\n Change only executed if come from \"Orderpoint\" (Context)\n \"\"\"\n if self._context.get('from_orderpoint'):\n partner = values['supplier'].name\n # Use the qty from the procurenment and do not recompute with the product uom like as follow\n # product_qty = product_uom._compute_quantity(product_qty, product_id.uom_po_id)\n seller = product_id.with_company(company_id)._select_seller(\n partner_id=partner,\n quantity=line.product_qty + product_qty,\n date=line.order_id.date_order and line.order_id.date_order.date(),\n uom_id=product_uom)\n\n price_unit = self.env['account.tax']._fix_tax_included_price_company(seller.supplier_price, line.product_id.supplier_taxes_id, line.taxes_id, company_id) if seller else 0.0\n if price_unit and seller and line.order_id.currency_id and seller.currency_id != line.order_id.currency_id:\n price_unit = seller.currency_id._convert(\n price_unit, line.order_id.currency_id, line.order_id.company_id, fields.Date.today())\n\n res = {\n 'product_qty': line.product_qty + product_qty,\n 'price_unit': price_unit,\n 'move_dest_ids': [(4, x.id) for x in values.get('move_dest_ids', [])]\n }\n orderpoint_id = values.get('orderpoint_id')\n if orderpoint_id:\n res['orderpoint_id'] = orderpoint_id.id\n else:\n res = super(StockRule, self)._update_purchase_order_line(product_id, product_qty, product_uom, company_id, values, line)\n return res\n","repo_name":"rotoclub/rotoclub","sub_path":"rap_roto_purchase/models/stock_rule.py","file_name":"stock_rule.py","file_ext":"py","file_size_in_byte":11144,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"43735264865","text":"# wemake-django-template documentation build configuration file, created by\n# sphinx-quickstart on Sat Sep 30 12:42:34 2017.\n#\n# This file is execfile()d with the current directory set to its\n# containing dir.\n#\n# Note that not all possible configuration values are present in this\n# autogenerated file.\n#\n# All configuration values have a default; values that are commented out\n# serve to show the default.\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n\nimport os\nimport sys\n\nimport django\nimport tomli\n\n# We need `server` to be importable from here:\nsys.path.insert(0, os.path.abspath('..'))\n\n# Django setup, all deps must be present to succeed:\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings')\ndjango.setup()\n\n\n# -- Project information -----------------------------------------------------\n\ndef _get_project_meta() -> dict[str, str]: # lying abour return type\n with open('../pyproject.toml', mode='rb') as pyproject:\n return tomli.load(pyproject)['tool']['poetry']\n\n\npkg_meta = _get_project_meta()\nproject = pkg_meta['name']\nauthor = pkg_meta['authors'][0]\ncopyright = author # noqa: WPS125\n\n# The short X.Y version\nversion = pkg_meta['version']\n# The full version, including alpha/beta/rc tags\nrelease = version\n\n\n# -- General configuration ------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\nneeds_sphinx = '7.2'\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx.ext.doctest',\n 'sphinx.ext.todo',\n 'sphinx.ext.coverage',\n 'sphinx.ext.viewcode',\n 'sphinx.ext.githubpages',\n 'sphinx.ext.napoleon',\n\n # 3rd party, order matters:\n # https://github.com/wemake-services/wemake-django-template/issues/159\n 'sphinx_autodoc_typehints',\n]\n\n# If true, Sphinx will warn about all references\n# where the target cannot be found. Default is `False``.\n# You can activate this mode temporarily using the `-n` command-line switch.\nnitpicky = True\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The suffix(es) of source filenames.\n# You can specify multiple suffix as a list of string:\nsource_suffix = ['.rst']\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#\n# This is also used if you do content translation via gettext catalogs.\n# Usually you set \"language\" from the command line for these cases.\nlanguage = 'en'\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This patterns also effect to html_static_path and html_extra_path\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = 'sphinx'\n\n# If true, `todo` and `todoList` produce output, else they produce nothing.\ntodo_include_todos = True\n\n\n# -- Options for HTML output ----------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\nhtml_theme = 'alabaster'\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\n# Custom sidebar templates, must be a dictionary that maps document names\n# to template names.\n#\n# This is required for the alabaster theme\n# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars\nhtml_sidebars = {\n '**': [\n 'about.html',\n 'navigation.html',\n 'moreinfo.html',\n 'searchbox.html',\n ],\n}\n","repo_name":"wemake-services/wemake-django-template","sub_path":"{{cookiecutter.project_name}}/docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":4122,"program_lang":"python","lang":"en","doc_type":"code","stars":1846,"dataset":"github-code","pt":"77"}
+{"seq_id":"18756460133","text":"from django.urls import re_path\nfrom apps.Nodes.views import PersonList, PersonCreate, PersonUpdate, PersonDelete, PersonAPI\nfrom apps.Nodes.views import PhoneList, PhoneCreate, PhoneUpdate, PhoneDelete, PhoneAPI\nfrom apps.Nodes.views import MeetingPointList, MeetingPointCreate, MeetingPointUpdate, MeetingPointDelete, MeetingPointAPI\nfrom apps.Nodes.views import all_people_delete, all_phones_delete, all_meeting_points_delete\n\nurlpatterns = [\n\tre_path(r'^newPerson$', PersonCreate.as_view(), name='newPerson'),\n\tre_path(r'^newPhone$', PhoneCreate.as_view(), name='newPhone'),\n\tre_path(r'^newMeetingPoint$', MeetingPointCreate.as_view(), name='newMeetingPoint'),\n\tre_path(r'^listPerson$', PersonList.as_view(), name='listPerson'),\n\tre_path(r'^listPhone$', PhoneList.as_view(), name='listPhone'),\n\tre_path(r'^listMeetingPoint$', MeetingPointList.as_view(), name='listMeetingPoint'),\n\tre_path(r'^editPerson/(?P[\\w|\\W]+)/$', PersonUpdate.as_view(), name='editPerson'),\n\tre_path(r'^editPhone/(?P[\\w|\\W]+)/$', PhoneUpdate.as_view(), name='editPhone'),\n\tre_path(r'^editMeetingPoint/(?P[\\w|\\W]+)/$', MeetingPointUpdate.as_view(), name='editMeetingPoint'),\n\tre_path(r'^deletePerson/(?P[\\w|\\W]+)/$', PersonDelete.as_view(), name='deletePerson'),\n\tre_path(r'^deletePhone/(?P[\\w|\\W]+)/$', PhoneDelete.as_view(), name='deletePhone'),\n\tre_path(r'^deleteMeetingPoint/(?P[\\w|\\W]+)/$', MeetingPointDelete.as_view(), name='deleteMeetingPoint'),\n\tre_path(r'^deleteAllPeople$', all_people_delete, name='deleteAllPeople'),\n\tre_path(r'^deleteAllPhones$', all_phones_delete, name='deleteAllPhones'),\n\tre_path(r'^deleteAllMeetingPoints$', all_meeting_points_delete, name='deleteAllMeetingPoints'),\n\tre_path(r'^apiPerson$', PersonAPI.as_view(), name='apiPerson'),\n\tre_path(r'^apiPhone$', PhoneAPI.as_view(), name='apiPhone'),\n\tre_path(r'^apiMeetingPoint$', MeetingPointAPI.as_view(), name='apiMeetingPoint'),\n]","repo_name":"rubenamador/ProyectoDjango","sub_path":"apps/Nodes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"22519116394","text":"from PyQt4 import QtGui, QtCore\nfrom PyQt4.QtGui import QSizePolicy\nfrom PyQt4.QtCore import Qt, QTimer\n\nimport os\n\nimport numpy as np\nimport pandas as pd\nfrom scipy import ndimage\nimport json\nimport errno\nfrom waldo.wio import Experiment, PlateDistance\nimport math\n\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as grd\nimport matplotlib.image as mpimg\nfrom matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar\nfrom skimage import morphology\nfrom skimage.measure import regionprops\nimport matplotlib.patches as patches\n\n# from waldo.images.grab_images import grab_images_in_time_range\nfrom waldo.gui import tasking\nfrom waldo.wio import paths\nfrom .loaders import CacheThresholdLoadingDialog\nfrom .helpers import circle_3pt\nfrom waldo.conf import settings\n\n# from waldo.conf import settings\n# from waldo.prepare import summarize as prepare_summarize\n# from waldo.images import summarize as images_summarize\n# from waldo.metrics.report_card import WaldoSolver\n# from waldo.wio import Experiment\n# from waldo.output.writer import OutputWriter\nfrom waldo import wio\nimport waldo.images.evaluate_acuracy as ea\n# import waldo.images.worm_finder as wf\nimport waldo.metrics.report_card as report_card\n# import waldo.metrics.step_simulation as ssim\n# import waldo.viz.eye_plots as ep\n# from waldo.gui import pathcustomize\n\n\nSTYLE = 'ggplot'\n\ntry:\n # MPL 1.4+\n plt.style.use(STYLE)\nexcept AttributeError:\n # fallback to mpltools\n from mpltools import style\n style.use(STYLE)\n\n\nclass CalibrationBar(QtGui.QWidget):\n calibration_changed = QtCore.pyqtSignal([])\n\n def __init__(self, enclosureSizeValue, figure, ax, color=(0.5, 0.8, 0.4, 1), parent=None):\n super(CalibrationBar, self).__init__()\n self.enclosureSizeValue = enclosureSizeValue\n self.figure = figure\n self.ax = ax\n self.parent = parent\n self.plate_distance = None\n\n self.plate_distance_artists = []\n self.color = color\n\n self.calibrationLabel = QtGui.QLabel(\"Current enclosure size (mm)\")\n self.enclosureSizeLabel = QtGui.QLabel(\"{}\".format(enclosureSizeValue))\n self.enclosureSizeLineEdit = QtGui.QLineEdit(\"{}\".format(enclosureSizeValue))\n self.enclosureSizeLineEdit.setValidator(QtGui.QIntValidator(0, 500000, self))\n self.calibrateButton = QtGui.QPushButton(\"Calibrate\")\n self.saveButton = QtGui.QPushButton(\"Save changes\")\n self.cancelButton = QtGui.QPushButton(\"Cancel\")\n\n self.calibrateButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)\n self.saveButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)\n self.cancelButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)\n\n self.calibrateButton.clicked.connect(self.calibrateButton_clicked)\n self.saveButton.clicked.connect(self.saveButton_clicked)\n self.cancelButton.clicked.connect(self.cancelButton_clicked)\n\n layout = QtGui.QHBoxLayout()\n layout.addWidget(self.calibrationLabel)\n layout.addWidget(self.enclosureSizeLabel)\n layout.addWidget(self.enclosureSizeLineEdit)\n layout.addWidget(self.calibrateButton)\n layout.addWidget(self.cancelButton)\n layout.addWidget(self.saveButton)\n self.setLayout(layout)\n\n self.editingCalibration = False\n self.set_initial_state()\n\n def set_initial_state(self):\n self.editingCalibration = False\n self.calibrationLabel.setVisible(True)\n self.enclosureSizeLabel.setVisible(True)\n self.enclosureSizeLineEdit.setVisible(False)\n self.calibrateButton.setVisible(True)\n self.saveButton.setVisible(False)\n self.cancelButton.setVisible(False)\n self.update_image()\n\n def clear_calibration(self):\n self.enclosureSizeValue = settings.DEFAULT_CALIBRATION_ENCLOSURE_SIZE\n self.enclosureSizeLabel.setText(str(self.enclosureSizeValue))\n self.enclosureSizeLineEdit.setText(str(self.enclosureSizeValue))\n\n def json_to_data(self, data):\n self.enclosureSizeValue = data.get('enclosureSize', settings.DEFAULT_CALIBRATION_ENCLOSURE_SIZE)\n self.enclosureSizeLabel.setText(\"{}\".format(self.enclosureSizeValue))\n self.enclosureSizeLineEdit.setText(\"{}\".format(self.enclosureSizeValue))\n\n def data_to_json(self):\n mm = self.enclosureSizeValue\n px = self.plate_distance.largest_distance()\n factor = 1 if px == 0 else mm / px\n return {'enclosureSize_mm': mm,\n 'enclosureSize_px': px,\n 'px_to_mm': factor}\n\n def update_image(self):\n for artist in self.plate_distance_artists:\n try:\n artist.remove()\n except:\n pass\n self.plate_distance_artists = []\n\n if not self.editingCalibration:\n return\n\n if self.plate_distance is not None:\n polygons = self.plate_distance.largest_segment_pretty(arrow_size=75)\n for polygon in polygons:\n points = [(y, x) for x, y in polygon] # traspose\n artist = plt.Polygon(\n points,\n closed=False,\n linewidth=3,\n fill=False,\n edgecolor=self.color)\n self.ax.add_artist(artist)\n self.plate_distance_artists.append(artist)\n print(\"Artist added!!!!\")\n self.figure.canvas.draw()\n\n def update_plate_distance(self, plate_distance):\n self.plate_distance = plate_distance\n self.update_image()\n\n def calibrateButton_clicked(self, ev):\n self.editingCalibration = True\n self.calibrationLabel.setVisible(True)\n self.enclosureSizeLabel.setVisible(False)\n self.enclosureSizeLineEdit.setVisible(True)\n self.calibrateButton.setVisible(False)\n self.saveButton.setVisible(True)\n self.cancelButton.setVisible(True)\n self.update_image()\n\n def saveButton_clicked(self, ev):\n value, result = self.enclosureSizeLineEdit.text().toInt()\n if result:\n self.enclosureSizeValue = value\n self.enclosureSizeLabel.setText(\"{}\".format(value))\n self.set_initial_state()\n self.calibration_changed.emit()\n\n def cancelButton_clicked(self, ev):\n self.enclosureSizeLineEdit.setText(\"{}\".format(self.enclosureSizeValue))\n self.set_initial_state()\n\n\nclass ROISelectorBar(QtGui.QWidget):\n roi_changed = QtCore.pyqtSignal([])\n def __init__(self, figure, ax, color=(1, 0, 0, 0.25), parent=None):\n super(ROISelectorBar, self).__init__()\n self.figure = figure\n self.ax = ax\n self.parent = parent\n self.guess_polygon = []\n\n self.roi_type = 'circle'\n self.roi_center = [0, 0]\n self.roi_radius = 1\n self.roi_points = []\n\n self.previous_artist = None\n self.artist = None\n self.current_polygon_artist = None\n self.color = color\n\n self.explainLabel = QtGui.QLabel(\"\")\n self.newCircleButton = QtGui.QPushButton(\"New Circle\")\n self.newPolygonButton = QtGui.QPushButton(\"New Polygon\")\n self.guessPolygonButton = QtGui.QPushButton(\"Guess polygon\")\n\n self.cancelCircleButton = QtGui.QPushButton(\"Cancel\")\n self.closePolygonButton = QtGui.QPushButton(\"Close\")\n self.cancelPolygonButton = QtGui.QPushButton(\"Cancel\")\n self.acceptGuessPolygonButton = QtGui.QPushButton(\"Accept\")\n self.cancelGuessPolygonButton = QtGui.QPushButton(\"Cancel\")\n\n self.explainLabel.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)\n self.newCircleButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)\n self.newPolygonButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)\n self.cancelCircleButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)\n self.closePolygonButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)\n self.cancelPolygonButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)\n self.acceptGuessPolygonButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)\n self.cancelGuessPolygonButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)\n\n self.newCircleButton.clicked.connect(self.newCircleButton_clicked)\n self.newPolygonButton.clicked.connect(self.newPolygonButton_clicked)\n self.guessPolygonButton.clicked.connect(self.guessPolygonButton_clicked)\n self.cancelCircleButton.clicked.connect(self.cancelCircleButton_clicked)\n self.closePolygonButton.clicked.connect(self.closePolygonButton_clicked)\n self.cancelPolygonButton.clicked.connect(self.cancelPolygonButton_clicked)\n self.acceptGuessPolygonButton.clicked.connect(self.acceptGuessPolygonButton_clicked)\n self.cancelGuessPolygonButton.clicked.connect(self.cancelGuessPolygonButton_clicked)\n\n layout = QtGui.QHBoxLayout()\n layout.addWidget(self.explainLabel)\n layout.addWidget(self.newCircleButton)\n layout.addWidget(self.newPolygonButton)\n layout.addWidget(self.guessPolygonButton)\n layout.addWidget(self.cancelCircleButton)\n layout.addWidget(self.cancelPolygonButton)\n layout.addWidget(self.closePolygonButton)\n layout.addWidget(self.cancelGuessPolygonButton)\n layout.addWidget(self.acceptGuessPolygonButton)\n self.setLayout(layout)\n\n self.figure.canvas.mpl_connect('button_press_event', self.on_figure_button_pressed)\n self.set_initial_state()\n\n def set_initial_state(self):\n self.current_roi_type = None\n self.explainLabel.setVisible(False)\n self.newCircleButton.setVisible(True)\n self.newPolygonButton.setVisible(True)\n self.guessPolygonButton.setVisible(True)\n self.cancelCircleButton.setVisible(False)\n self.closePolygonButton.setVisible(False)\n self.cancelPolygonButton.setVisible(False)\n self.acceptGuessPolygonButton.setVisible(False)\n self.cancelGuessPolygonButton.setVisible(False)\n\n def clear_roi(self):\n #self.circle = None\n self.roi_type = 'circle'\n self.roi_center = (0, 0)\n self.roi_radius = 1\n self.roi_points = []\n\n def json_to_data(self, data):\n self.roi_type = data.get('roi_type', 'circle')\n self.roi_center = (data.get('x', 0), data.get('y', 0)) # no longer transposed\n self.roi_radius = data.get('r', 1)\n self.roi_points = data.get('points', [])\n\n def data_to_json(self):\n return {'roi_type': self.roi_type,\n 'x': self.roi_center[0], # no longer transposed!!\n 'y': self.roi_center[1],\n 'r': self.roi_radius,\n 'points': self.roi_points}\n\n def set_guess_polygon(self, points):\n self.guess_polygon_points = points\n\n def update_image(self):\n if self.artist is not None:\n try:\n self.artist.remove()\n self.artist = None\n except:\n pass\n\n if self.roi_type == 'circle':\n self.artist = plt.Circle(self.roi_center, self.roi_radius, color=self.color)\n self.ax.add_artist(self.artist)\n self.figure.canvas.draw()\n\n elif self.roi_type == 'polygon':\n self.artist = plt.Polygon(\n self.roi_points,\n closed=True,\n linewidth=0,\n fill=True,\n color=self.color)\n self.ax.add_artist(self.artist)\n self.figure.canvas.draw()\n\n else:\n self.artist = None\n\n def isComplete(self):\n if self.roi_type == 'circle':\n return self.roi_center[0] != 0 or self.roi_center[1] != 0\n elif self.roi_type == 'polygon':\n return len(self.roi_points) > 2\n else:\n return False\n\n def newCircleButton_clicked(self, ev):\n self.current_roi_type = 'circle'\n self.mouse_points = []\n\n self.explainLabel.setText(\"Click next point (3 remains)\")\n self.explainLabel.setVisible(True)\n self.newCircleButton.setVisible(False)\n self.newPolygonButton.setVisible(False)\n self.guessPolygonButton.setVisible(False)\n self.cancelCircleButton.setVisible(True)\n self.closePolygonButton.setVisible(False)\n self.cancelPolygonButton.setVisible(False)\n self.acceptGuessPolygonButton.setVisible(False)\n self.cancelGuessPolygonButton.setVisible(False)\n\n self.previous_artist = self.artist\n if self.artist is not None:\n self.artist.remove()\n self.artist = None\n self.figure.canvas.draw()\n\n def newPolygonButton_clicked(self, ev):\n self.current_roi_type = 'polygon'\n self.mouse_points = []\n\n self.explainLabel.setText(\"Click next point or 'close' to close the polygon\")\n self.explainLabel.setVisible(True)\n self.newCircleButton.setVisible(False)\n self.newPolygonButton.setVisible(False)\n self.guessPolygonButton.setVisible(False)\n self.cancelCircleButton.setVisible(False)\n self.closePolygonButton.setVisible(True)\n self.cancelPolygonButton.setVisible(True)\n self.acceptGuessPolygonButton.setVisible(False)\n self.cancelGuessPolygonButton.setVisible(False)\n\n self.previous_artist = self.artist\n if self.artist is not None:\n self.artist.remove()\n self.artist = None\n self.figure.canvas.draw()\n\n def guessPolygonButton_clicked(self, ev):\n self.current_roi_type = 'guess_polygon'\n\n self.explainLabel.setText(\"Accept this polygon?\")\n self.explainLabel.setVisible(True)\n self.newCircleButton.setVisible(False)\n self.newPolygonButton.setVisible(False)\n self.guessPolygonButton.setVisible(False)\n self.cancelCircleButton.setVisible(False)\n self.closePolygonButton.setVisible(False)\n self.cancelPolygonButton.setVisible(False)\n self.acceptGuessPolygonButton.setVisible(True)\n self.cancelGuessPolygonButton.setVisible(True)\n\n self.previous_artist = self.artist\n if self.artist is not None:\n self.artist.remove()\n self.artist = None\n self.figure.canvas.draw()\n\n self.current_polygon_artist = plt.Polygon(\n self.guess_polygon_points,\n closed=True,\n linewidth=0,\n fill=True,\n color=self.color)\n self.ax.add_artist(self.current_polygon_artist)\n self.figure.canvas.draw()\n\n def cancelCircleButton_clicked(self, ev):\n self.current_roi_type = None\n self.set_initial_state()\n\n if self.previous_artist is not None:\n self.artist = self.previous_artist\n self.ax.add_artist(self.artist)\n self.figure.canvas.draw()\n self.previous_artist = None\n\n def closePolygonButton_clicked(self, ev):\n if len(self.mouse_points) < 3:\n self.cancelPolygonButton_clicked(ev)\n else:\n self.__close_polygon()\n\n def cancelPolygonButton_clicked(self, ev):\n self.current_roi_type = None\n self.set_initial_state()\n\n draw = False\n if self.previous_artist is not None:\n self.artist = self.previous_artist\n self.ax.add_artist(self.artist)\n draw = True\n self.previous_artist = None\n\n if self.current_polygon_artist is not None:\n self.current_polygon_artist.remove()\n self.current_polygon_artist = None\n draw = True\n\n if draw:\n self.figure.canvas.draw()\n\n def acceptGuessPolygonButton_clicked(self, ev):\n self.roi_points = self.guess_polygon_points\n self.set_initial_state()\n\n self.artist = plt.Polygon(\n self.roi_points,\n closed=True,\n linewidth=0,\n fill=True,\n color=self.color)\n\n if self.current_polygon_artist is not None:\n self.current_polygon_artist.remove()\n self.current_polygon_artist = None\n\n self.ax.add_artist(self.artist)\n self.figure.canvas.draw()\n\n self.roi_type = 'polygon'\n self.roi_changed.emit()\n\n def cancelGuessPolygonButton_clicked(self, ev):\n self.current_roi_type = None\n self.set_initial_state()\n\n draw = False\n if self.previous_artist is not None:\n self.artist = self.previous_artist\n self.ax.add_artist(self.artist)\n draw = True\n self.previous_artist = None\n\n if self.current_polygon_artist is not None:\n self.current_polygon_artist.remove()\n self.current_polygon_artist = None\n draw = True\n\n if draw:\n self.figure.canvas.draw()\n\n def on_figure_button_pressed(self, ev):\n if ev.xdata is None or ev.ydata is None:\n return\n\n if self.current_roi_type == 'circle':\n self.mouse_points.append((ev.xdata, ev.ydata))\n if len(self.mouse_points) < 3:\n remain = 3 - len(self.mouse_points)\n self.explainLabel.setText(\n \"Click next point ({} remain{})\".format(\n remain, \"s\" if remain > 1 else \"\"))\n else:\n center, radius = circle_3pt(*self.mouse_points)\n self.roi_center = center\n self.roi_radius = radius\n self.set_initial_state()\n\n self.artist = plt.Circle(self.roi_center, self.roi_radius, color=self.color)\n self.ax.add_artist(self.artist)\n self.figure.canvas.draw()\n\n self.roi_type = 'circle'\n self.roi_changed.emit()\n\n elif self.current_roi_type == 'polygon':\n self.mouse_points.append((ev.xdata, ev.ydata))\n\n closed = False\n\n if len(self.mouse_points) > 2:\n first = self.mouse_points[0]\n last = self.mouse_points[-1]\n d = math.hypot(first[0] - last[0], first[1] - last[1])\n if d < 75:\n self.__close_polygon()\n closed = True\n\n if not closed:\n if self.current_polygon_artist is None:\n self.current_polygon_artist = plt.Polygon(\n self.mouse_points,\n closed=False,\n linewidth=3,\n fill=False,\n edgecolor=self.color)\n self.ax.add_artist(self.current_polygon_artist)\n else:\n self.current_polygon_artist.set_xy(self.mouse_points)\n self.figure.canvas.draw()\n\n def __close_polygon(self):\n self.roi_points = self.mouse_points\n self.set_initial_state()\n\n self.artist = plt.Polygon(\n self.roi_points,\n closed=True,\n linewidth=0,\n fill=True,\n color=self.color)\n\n if self.current_polygon_artist is not None:\n self.current_polygon_artist.remove()\n self.current_polygon_artist = None\n\n self.ax.add_artist(self.artist)\n self.figure.canvas.draw()\n\n self.roi_type = 'polygon'\n self.roi_changed.emit()\n\n\nclass ThresholdCacheWidget(QtGui.QWidget):\n def __init__(self, on_changed_ev, parent=None):\n super(ThresholdCacheWidget, self).__init__()\n self.on_changed_ev = on_changed_ev\n self.parent = parent\n\n self.histogram_figure = plt.figure()\n self.histogram_canvas = FigureCanvas(self.histogram_figure)\n self.histogram_canvas.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)\n self.histogram_canvas.setMinimumSize(50, 50)\n self.histogram_toolbar = NavigationToolbar(self.histogram_canvas, parent)\n self.histogram_toolbar.coordinates = False\n self.histogram_toolbar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)\n\n self.image_figure = plt.figure()\n self.image_canvas = FigureCanvas(self.image_figure)\n self.image_canvas.setMinimumSize(50, 50)\n self.image_canvas.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)\n self.image_toolbar = NavigationToolbar(self.image_canvas, parent)\n self.image_toolbar.coordinates = False\n self.image_toolbar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)\n\n gs = grd.GridSpec(3, 1)\n self.ax_objects = self.histogram_figure.add_subplot(gs[0, 0])\n self.ax_area = self.histogram_figure.add_subplot(gs[1, 0], sharex=self.ax_objects)\n self.ax_image = self.image_figure.add_subplot(111)\n\n layout = QtGui.QGridLayout()\n\n q1 = QtGui.QLabel(\"Choose Threshold \")\n layout.addWidget(q1, 0, 0, 1, 1)\n layout.addWidget(QtGui.QLabel(\"Click on either graph to pick a threshold value\"), 1, 0, 1, 1)\n layout.addWidget(self.histogram_canvas, 3, 0, 1, 1)\n layout.addWidget(self.histogram_toolbar, 4, 0, 1, 1)\n\n self.roiSelectorBar = ROISelectorBar(self.image_figure, self.ax_image)\n self.roiSelectorBar.roi_changed.connect(self.roiSelectorBar_roi_changed)\n\n self.calibrationBar = CalibrationBar(10, self.image_figure, self.ax_image)\n self.calibrationBar.calibration_changed.connect(self.calibrationBar_calibration_changed)\n\n q2 = QtGui.QLabel(\"Define Region of Interest \")\n layout.addWidget(q2, 0, 1, 1, 1)\n layout.addWidget(self.roiSelectorBar, 1, 1, 1, 1)\n layout.addWidget(self.calibrationBar, 2, 1, 1, 1)\n layout.addWidget(self.image_canvas, 3, 1, 1, 1)\n layout.addWidget(self.image_toolbar, 4, 1, 1, 1)\n self.setLayout(layout)\n\n self.histogram_figure.canvas.mpl_connect('button_press_event', self.on_histogram_button_pressed)\n # self.image_figure.canvas.mpl_connect('button_press_event', self.on_image_button_pressed)\n\n self.thresholds = []\n\n @staticmethod\n def create_background(impaths):\n \"\"\"\n create a background image for background subtraction.\n The background image is the maximum pixel values from three grayscale images.\n\n params\n ---------\n impaths: (list)\n this is a sorted list containing paths to all the image files from one recording.\n \"\"\"\n if len(impaths) == 0:\n return None\n first = mpimg.imread(impaths[0])\n mid = mpimg.imread(impaths[int(len(impaths)/2)])\n last = mpimg.imread(impaths[-1])\n return np.maximum(np.maximum(first, mid), last)\n\n def clear_experiment_data(self):\n self.roiSelectorBar.clear_roi()\n self.threshold = 0.0005\n\n def load_experiment(self, experiment):\n self.experiment = experiment\n self.annotation_filename = str(paths.threshold_data(experiment.id))\n try:\n with open(self.annotation_filename, \"rt\") as f:\n data = json.loads(f.read())\n # self.circle = None\n self.roiSelectorBar.json_to_data(data)\n self.threshold = data.get('threshold', 0.0005)\n except IOError as ex:\n self.clear_experiment_data()\n\n self.calibration_filename = str(paths.calibration_data(experiment.id))\n try:\n with open(self.calibration_filename, \"rt\") as f:\n data = json.loads(f.read())\n self.calibrationBar.json_to_data(data)\n except IOError as ex:\n self.calibrationBar.clear_calibration()\n\n times, impaths = zip(*sorted(experiment.image_files.items()))\n impaths = [str(s) for s in impaths]\n\n if times is not None and len(times) > 0:\n times = [float(t) for t in times]\n times, impaths = zip(*sorted(zip(times, impaths)))\n\n if impaths is None or len(impaths) == 0:\n self.background = None\n self.mid_image = None\n self.plate_distance = None\n self.roiSelectorBar.set_guess_polygon([])\n else:\n self.background = ThresholdCacheWidget.create_background(impaths)\n self.im_shape = self.background.shape # shape is (y,x)\n self.mid_image = mpimg.imread(impaths[int(len(impaths)/2)])\n self.plate_distance = PlateDistance(self.background)\n self.plate_distance.calculate()\n p = self.plate_distance.polygon(border=settings.ROI_BORDER_OFFSET, corner=settings.ROI_CORNER_OFFSET)\n p = [(y, x) for x, y in p]\n self.roiSelectorBar.set_guess_polygon(p)\n\n self.calibrationBar.update_plate_distance(self.plate_distance)\n self.mouse_points = []\n QTimer.singleShot(0, self.show_dialog)\n\n def show_dialog(self):\n dlg = CacheThresholdLoadingDialog(self.experiment.id, self.calculate_threshold, self.finished, self.parent)\n dlg.setModal(True)\n dlg.exec_()\n\n def calculate_threshold(self, callback):\n self.thresholds = []\n for i, t in enumerate(np.linspace(start=0.00001, stop=0.001, num=30)):\n valid, N, m, s = self.data_from_threshold(t)\n if valid:\n self.thresholds.append((t, N, m, s))\n callback(0, i / 30.)\n callback(0, 1)\n\n def finished(self):\n self.update_data(self.thresholds, self.threshold)\n self.histogram_figure.canvas.draw()\n\n def isComplete(self):\n return self.roiSelectorBar.isComplete()\n\n def create_binary_mask(self, img, background, threshold, minsize=100):\n \"\"\"\n creates a binary array the same size as the image with 1s denoting objects\n and 0s denoting background.\n\n params\n --------\n img: (image ie. numpy array)\n each pixel denotes greyscale pixel intensities.\n background: (image ie. numpy array)\n the background image with maximum pixel intensities (made with create_background)\n threshold: (float)\n the threshold value used to create the binary mask after pixel intensities for (background - image) have been calculated.\n minsize: (int)\n the fewest allowable pixels for an object. objects with an area containing fewer pixels are removed.\n \"\"\"\n if img is None or background is None:\n return None\n mask = (background - img) > threshold\n result = morphology.remove_small_objects(mask, minsize)\n return result\n\n def data_from_threshold(self, threshold):\n if self.mid_image is None:\n return False, None, None, None\n mask = self.create_binary_mask(self.mid_image, self.background, threshold=threshold)\n labels, N = ndimage.label(mask)\n sizes = [r.area for r in regionprops(labels)]\n if len(sizes) == 0:\n return False, None, None, None\n else:\n m, s = np.mean(sizes), np.std(sizes)\n return True, N, m, s\n\n @staticmethod\n def mkdir_p(path):\n try:\n os.makedirs(path)\n except OSError as exc: # Python >2.5\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else: raise\n\n def save_roi_data(self):\n if self.annotation_filename is None:\n return\n\n # note: the image is usually transposed. we didn't here,\n # so x and y are flipped during saving process.\n data = self.roiSelectorBar.data_to_json()\n data['threshold'] = self.threshold\n data['shape'] = self.im_shape\n\n ThresholdCacheWidget.mkdir_p(os.path.dirname(self.annotation_filename))\n with open(self.annotation_filename, \"wt\") as f:\n f.write(json.dumps(data, indent=4))\n\n def save_calibration_data(self):\n if self.calibration_filename is None:\n return\n\n data = self.calibrationBar.data_to_json()\n ThresholdCacheWidget.mkdir_p(os.path.dirname(self.calibration_filename))\n with open(self.calibration_filename, \"wt\") as f:\n f.write(json.dumps(data, indent=4))\n\n def update_data(self, thresholds, current_threshold):\n if len(thresholds) == 0:\n self.ax_objects.clear()\n self.ax_area.clear()\n self.ax_image.clear()\n self.line_objects = None\n self.line_area = None\n return\n\n x, ns, means, stds = zip(*thresholds)\n final_t = x[-1]\n\n # make the plot\n self.ax_objects.clear()\n self.ax_objects.plot(x, ns, '.-', color='black')\n self.ax_objects.set_ylabel('N Objects')\n self.ax_objects.set_ylim([0, 150])\n\n top = np.array(means) + np.array(stds)\n bottom = np.array(means) - np.array(stds)\n\n self.ax_area.clear()\n self.ax_area.plot(x, means, '.-', color='blue', label='mean')\n self.ax_area.fill_between(x, top, bottom, color='green', alpha=0.5)\n # self.ax_area.plot(x, top, '--', color='green', label='mean')\n # self.ax_area.plot(x, bottom, '--', color='green', label='mean - std')\n self.ax_area.axvline(x=.5, ymin=0, ymax=1)\n self.ax_area.legend(loc='upper right')\n\n self.ax_area.set_ylim([0, 600])\n self.ax_area.set_ylabel('Blob Area (pxls)')\n self.ax_area.set_xlabel('Contrast Threshold')\n self.ax_objects.set_xlim([0, final_t])\n\n self.line_objects = self.ax_objects.plot((current_threshold, current_threshold), (-10000, 10000), '--', color='red')\n self.line_area = self.ax_area.plot((current_threshold, current_threshold), (-1000000, 1000000), '--', color='red')\n self.show_threshold()\n\n def show_threshold(self):\n \"\"\"\n plots an image with the outlines of all objects overlaid on top.\n\n params\n --------\n img: (image ie. numpy array)\n each pixel denotes greyscale pixel intensities.\n background: (image ie. numpy array)\n the background image with maximum pixel intensities (made with create_background)\n threshold: (float)\n the threshold value used to create the binary mask after pixel intensities for (background - image) have been calculated.\n \"\"\"\n mask = self.create_binary_mask(self.mid_image, self.background, self.threshold)\n self.ax_image.clear()\n self.ax_image.imshow(self.mid_image, cmap=plt.cm.gray, interpolation='nearest')\n self.ax_image.contour(mask, [0.5], linewidths=1.2, colors='b')\n self.ax_image.axis('off')\n\n self.roiSelectorBar.update_image()\n self.calibrationBar.update_image()\n\n def on_histogram_button_pressed(self, ev):\n if self.threshold != ev.xdata:\n self.threshold = ev.xdata\n\n if self.line_objects is not None and len(self.line_objects) > 0:\n self.line_objects[0].remove()\n if self.line_area is not None and len(self.line_area) > 0:\n self.line_area[0].remove()\n self.line_objects = self.ax_objects.plot((self.threshold, self.threshold), (-10000, 10000), '--', color='red')\n self.line_area = self.ax_area.plot((self.threshold, self.threshold), (-1000000, 1000000), '--', color='red')\n\n self.show_threshold()\n self.histogram_figure.canvas.draw()\n self.save_roi_data()\n\n def roiSelectorBar_roi_changed(self):\n self.save_roi_data()\n self.on_changed_ev()\n\n def calibrationBar_calibration_changed(self):\n self.save_calibration_data()\n\n\nclass ExperimentResultWidget(QtGui.QWidget):\n def __init__(self, parent=None):\n super(ExperimentResultWidget, self).__init__()\n\n self.tab = QtGui.QTabWidget()\n\n # Figure 1\n figure = plt.figure()\n canvas = FigureCanvas(figure)\n canvas.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)\n canvas.setMinimumSize(50, 50)\n toolbar = NavigationToolbar(canvas, self)\n toolbar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)\n\n widget = QtGui.QWidget()\n layout = QtGui.QVBoxLayout()\n layout.addWidget(canvas)\n layout.addWidget(toolbar)\n widget.setLayout(layout)\n self.tab.addTab(widget, 'Results')\n self.plot = figure\n\n # Tab 1\n self.trackCountsTable = QtGui.QTableWidget()\n self.tab.addTab(self.trackCountsTable, 'Track Counts')\n\n # Tab 2\n self.networkOverviewTable = QtGui.QTableWidget()\n self.tab.addTab(self.networkOverviewTable, 'Network Overview')\n\n # Tab 3\n self.trackTerminationTable = QtGui.QTableWidget()\n self.trackInitiationTable = QtGui.QTableWidget()\n\n widget = QtGui.QWidget()\n layout = QtGui.QVBoxLayout()\n layout.addWidget(self.trackTerminationTable)\n layout.addWidget(self.trackInitiationTable)\n widget.setLayout(layout)\n self.tab.addTab(widget, 'Track Fragmentation')\n\n layout = QtGui.QVBoxLayout()\n layout.addWidget(self.tab)\n self.setLayout(layout)\n\n def initializeWidget(self, experiment):\n self.make_figures(experiment.id)\n\n report_card_df = experiment.prepdata.load('report-card')\n if report_card_df is None:\n self.trackCountsTable.clear()\n self.networkOverviewTable.clear()\n else:\n self.make_trackCountsTable(report_card_df)\n self.make_networkOverviewTable(report_card_df)\n\n end_report_df = experiment.prepdata.load('end_report')\n if end_report_df is None:\n self.trackTerminationTable.clear()\n else:\n self.make_trackTerminationTable(end_report_df)\n\n start_report_df = experiment.prepdata.load('start_report')\n if start_report_df is None:\n self.trackInitiationTable.clear()\n else:\n self.make_trackInitiationTable(start_report_df)\n\n\n def make_trackCountsTable(self, report_card_df):\n headers = ['phase', 'step', 'total-nodes', '>10min', '>20min', '>30min', '>40min', '>50min', 'duration-mean', 'duration-std']\n rightAligns = [False, False, True, True, True, True, True, True, True, True ]\n widths = [100, 150, 100, 100, 100, 100, 100, 100, 100, 100]\n\n self.trackCountsTable.clear()\n self.trackCountsTable.setColumnCount(len(headers))\n self.trackCountsTable.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)\n self.trackCountsTable.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)\n for col, (header, width) in enumerate(zip(headers, widths)):\n self.trackCountsTable.setHorizontalHeaderItem(col, QtGui.QTableWidgetItem(header))\n self.trackCountsTable.setColumnWidth(col, width)\n self.trackCountsTable.verticalHeader().setVisible(False)\n\n prev_phase = ''\n b = report_card_df[headers]\n for row_data in b.iterrows():\n row = row_data[0]\n self.trackCountsTable.setRowCount(row + 1)\n col_data = row_data[1]\n for col, (header, rightAlign) in enumerate(zip(headers, rightAligns)):\n current = str(col_data[header])\n if col == 0 and current == prev_phase:\n current = \"\"\n item = QtGui.QTableWidgetItem(current)\n item.setFlags(item.flags() ^ Qt.ItemIsEditable)\n if rightAlign:\n item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)\n self.trackCountsTable.setItem(row, col, item)\n prev_phase = col_data['phase']\n\n def make_networkOverviewTable(self, report_card_df):\n headers = ['phase', 'step', 'total-nodes', 'connected-nodes', 'isolated-nodes', 'giant-component-size', '# components']\n rightAligns = [False, False, True, True, True, True, True]\n widths = [100, 150, 100, 100, 100, 100, 100]\n\n self.networkOverviewTable.clear()\n self.networkOverviewTable.setColumnCount(len(headers))\n self.networkOverviewTable.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)\n self.networkOverviewTable.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)\n for col, (header, width) in enumerate(zip(headers, widths)):\n self.networkOverviewTable.setHorizontalHeaderItem(col, QtGui.QTableWidgetItem(header))\n self.networkOverviewTable.setColumnWidth(col, width)\n self.networkOverviewTable.verticalHeader().setVisible(False)\n\n prev_phase = ''\n b = report_card_df[headers]\n for row_data in b.iterrows():\n row = row_data[0]\n self.networkOverviewTable.setRowCount(row + 1)\n col_data = row_data[1]\n for col, (header, rightAlign) in enumerate(zip(headers, rightAligns)):\n current = str(col_data[header])\n if col == 0 and current == prev_phase:\n current = \"\"\n item = QtGui.QTableWidgetItem(current)\n item.setFlags(item.flags() ^ Qt.ItemIsEditable)\n if rightAlign:\n item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)\n self.networkOverviewTable.setItem(row, col, item)\n prev_phase = col_data['phase']\n\n def make_trackTerminationTable(self, end_report_df):\n df = end_report_df\n df['lifespan'] = ['0-1 min', '1-5 min', '6-10 min', '11-20 min', '21-60 min', 'total']\n df = df.rename(columns={'lifespan': 'track-duration',\n 'unknown': 'disappear',\n 'timing':'recording-finishes',\n 'on_edge':'image-edge'})\n df.set_index('track-duration', inplace=True)\n\n headers = ['', 'disappear', 'split', 'join', 'recording-finishes', 'image-edge', 'outside-roi']\n rightAligns = [False, True, True, True, True, True, True]\n widths = [100, 100, 100, 100, 100, 100, 100]\n\n self.trackTerminationTable.clear()\n self.trackTerminationTable.setColumnCount(len(headers))\n self.trackTerminationTable.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)\n self.trackTerminationTable.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)\n for col, (header, width) in enumerate(zip(headers, widths)):\n self.trackTerminationTable.setHorizontalHeaderItem(col, QtGui.QTableWidgetItem(header))\n self.trackTerminationTable.setColumnWidth(col, width)\n self.trackTerminationTable.verticalHeader().setVisible(False)\n\n b = df[headers[1:]]\n for row, row_data in enumerate(b.iterrows()):\n first_label = row_data[0]\n self.trackTerminationTable.setRowCount(row + 1)\n col_data = row_data[1]\n for col, (header, rightAlign) in enumerate(zip(headers, rightAligns)):\n if col == 0:\n current = first_label\n else:\n current = str(col_data[header])\n item = QtGui.QTableWidgetItem(current)\n item.setFlags(item.flags() ^ Qt.ItemIsEditable)\n if rightAlign:\n item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)\n self.trackTerminationTable.setItem(row, col, item)\n\n def make_trackInitiationTable(self, start_report_df):\n df = start_report_df\n df['lifespan'] = ['0-1 min', '1-5 min', '6-10 min', '11-20 min', '21-60 min', 'total']\n df = df.rename(columns={'lifespan': 'track-duration',\n 'unknown': 'appear',\n 'timing':'recording-begins',\n 'on_edge':'image-edge'})\n df.set_index('track-duration', inplace=True)\n\n headers = ['', 'appear', 'split', 'join', 'recording-begins', 'image-edge', 'outside-roi']\n rightAligns = [False, True, True, True, True, True, True]\n widths = [100, 100, 100, 100, 100, 100, 100]\n\n self.trackInitiationTable.clear()\n self.trackInitiationTable.setColumnCount(len(headers))\n self.trackInitiationTable.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)\n self.trackInitiationTable.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)\n for col, (header, width) in enumerate(zip(headers, widths)):\n self.trackInitiationTable.setHorizontalHeaderItem(col, QtGui.QTableWidgetItem(header))\n self.trackInitiationTable.setColumnWidth(col, width)\n self.trackInitiationTable.verticalHeader().setVisible(False)\n\n b = df[headers[1:]]\n for row, row_data in enumerate(b.iterrows()):\n first_label = row_data[0]\n self.trackInitiationTable.setRowCount(row + 1)\n col_data = row_data[1]\n for col, (header, rightAlign) in enumerate(zip(headers, rightAligns)):\n if col == 0:\n current = first_label\n else:\n current = str(col_data[header])\n item = QtGui.QTableWidgetItem(current)\n item.setFlags(item.flags() ^ Qt.ItemIsEditable)\n if rightAlign:\n item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)\n self.trackInitiationTable.setItem(row, col, item)\n\n # MAKE FIG\n\n def calculate_stats_for_moves(self, min_moves, prep_data):\n move = prep_data.load('moved')\n\n base_accuracy = prep_data.load('accuracy', index_col=False)\n print(base_accuracy.head())\n print(base_accuracy.columns)\n matches = prep_data.load('matches')\n counts, tps, fps, fns = [], [], [], []\n for mm in min_moves:\n print(mm)\n moved = move[move['bl_moved'] >= mm]\n bids = list(moved['bid'])\n filtered_accuracy = ea.recalculate_accuracy(matches, base_accuracy, bids=bids)\n #filtered_accuracy = filtered_accuracy[np.isfinite(filtered_accuracy['true-pos'])]\n counts.append(len(bids))\n tp = filtered_accuracy['true-pos'].mean()\n #print('tp', tp)\n fp = filtered_accuracy['false-pos'].mean()\n #print('fp', fp)\n fn = filtered_accuracy['false-neg'].mean()\n\n tps.append(tp)\n fps.append(fp)\n fns.append(fn)\n\n tps = np.array(tps)\n fps = np.array(fps)\n fns = np.array(fns)\n totals = fns + tps\n tps_p = tps / totals * 100\n fps_p = fps / totals * 100\n fns_p = fns / totals * 100\n\n print('true counts=', np.mean(totals))\n\n data = pd.DataFrame([tps_p, fns_p, fps_p], index=['TP', 'FN', 'FP']).T\n counts = pd.DataFrame(counts, columns=['counts'])\n return data, counts\n\n def _new_plot(self, ax, df, label, nth_color=0, xmax=60):\n step_df = df\n n_steps = len(step_df)\n steps = []\n\n xs = list(step_df['t0'])\n widths = list(step_df['lifespan'])\n height = 1\n\n # color = ax._get_lines.prop_cycler.next()\n # for i in range(nth_color):\n # color = ax._get_lines.prop_cycler.next()\n # color = color['color']\n color = ax._get_lines.color_cycle.next()\n for i in range(nth_color):\n color = ax._get_lines.color_cycle.next()\n\n for y, (x, width) in enumerate(zip(xs, widths)):\n steps.append(patches.Rectangle((x,y), height=height, width=width,\n fill=True, fc=color, ec=color, alpha=0.5))\n for step in steps:\n ax.add_patch(step)\n\n ax.plot([0], color=color, label=label, alpha=0.5)\n ax.set_xlim([0, xmax])\n\n def steps_from_node_report(self, experiment, min_bl=1):\n node_report = experiment.prepdata.load('node-summary')\n steps = node_report[['bl', 't0', 'tN', 'bid']].copy()\n steps.set_index('bid', inplace=True)\n steps.loc[:, 't0'] = steps['t0'] / 60.0\n steps.loc[:, 'tN'] = steps['tN'] / 60.0\n steps.loc[:, 'lifespan'] = steps['tN'] - steps['t0']\n steps.loc[:, 'mid'] = (steps['tN'] + steps['t0']) / 2.0\n return steps[steps['bl'] >= 1]\n\n def make_figures(self, ex_id, step_min_move = 1):\n experiment = wio.Experiment(experiment_id=ex_id)\n graph = experiment.graph.copy()\n\n self.plot.clf()\n\n moving_nodes = [int(i) for i\n in graph.compound_bl_filter(experiment,\n threshold=step_min_move)]\n steps, durations = report_card.calculate_duration_data_from_graph(experiment, graph, moving_nodes)\n\n final_steps = self.steps_from_node_report(experiment)\n #accuracy = experiment.prepdata.load('accuracy')\n #worm_count = np.mean(accuracy['true-pos'] + accuracy['false-neg'])\n\n self.step_facets(steps, final_steps)\n\n def step_facets(self, df, df2, t1=5, t2=20):\n xmax = max([max(df['tN']), max(df['tN'])])\n\n gs = grd.GridSpec(3, 2)\n gs.update(wspace=0.01, hspace=0.05) #, bottom=0.1, top=0.7)\n\n ax_l0 = self.plot.add_subplot(gs[0,0])\n ax_l1 = self.plot.add_subplot(gs[0,1], sharey=ax_l0)\n ax_m0 = self.plot.add_subplot(gs[1,0])\n ax_m1 = self.plot.add_subplot(gs[1,1], sharey=ax_m0)\n ax_s0 = self.plot.add_subplot(gs[2,0])\n ax_s1 = self.plot.add_subplot(gs[2,1], sharey=ax_s0)\n\n left = [ax_l0, ax_m0, ax_s0]\n right = [ax_l1, ax_m1, ax_s1]\n top = [ax_l0, ax_l1]\n mid = [ax_m0, ax_m1]\n bottom = [ax_s0, ax_s1]\n ylabels = ['> {t2} min'.format(t2=t2), '{t1} to {t2} min'.format(t1=t1, t2=t2), '< {t1} min'.format(t1=t1)]\n\n short1 = df[df['lifespan'] < t1]\n short2 = df2[df2['lifespan'] < t1]\n mid1 = df[(df['lifespan'] < t2) & (df['lifespan'] >= t1)]\n mid2 = df2[(df2['lifespan'] < t2) & (df2['lifespan'] >= t1)]\n long1 = df[df['lifespan'] >= t2]\n long2 = df2[df2['lifespan'] >= t2]\n\n short_max = max([len(short1), len(short2)])\n mid_max = max([len(mid1), len(mid2)])\n long_max = max([len(long1), len(long2)])\n # print('short', short_max)\n # print('long', long_max)\n # print('mid', mid_max)\n # print(long1.head(20))\n\n self._new_plot(ax_s0, short1, 'raw', xmax=xmax)\n self._new_plot(ax_m0, mid1, 'raw', xmax=xmax)\n self._new_plot(ax_l0, long1, 'raw', xmax=xmax)\n\n self._new_plot(ax_s1, short2, 'final', nth_color=1, xmax=xmax)\n self._new_plot(ax_m1, mid2, 'final', nth_color=1, xmax=xmax)\n self._new_plot(ax_l1, long2, 'final', nth_color=1, xmax=xmax)\n\n for ax in right:\n ax.axes.yaxis.tick_right()\n\n for ax, t in zip(top, ['raw', 'final']):\n ax.get_xaxis().set_ticklabels([])\n ax.set_ylim([0, long_max])\n\n top[0].set_title('Input Tracks')\n top[1].set_title('Output Tracks')\n\n for ax in mid:\n ax.get_xaxis().set_ticklabels([])\n ax.set_ylim([0, mid_max])\n\n for ax in bottom:\n ax.set_xlabel('Time (min)', size=12)\n ax.set_ylim([0, short_max])\n\n for ax, t in zip(left, ylabels):\n ax.set_ylabel(t, size=12)\n\n ax_s0.get_xaxis().set_ticklabels([0, 10, 20, 30, 40, 50])\n self.plot.canvas.draw()\n","repo_name":"amarallab/waldo","sub_path":"code/waldo/gui/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":47453,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"38878031396","text":"import time\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom load_balancing_simulations.QueueFunctions import QueueFunctions\nfrom load_balancing_simulations.SimulationBase import SimulationBase\n\n\nclass SimulationHW(SimulationBase):\n # Class for Halfin Witt regime simulations\n\n # Definitions for Halfin-Witt Simulation\n\n empty_queues = []\n two_queues = []\n three_queues = []\n\n # Constructor\n def __init__(self, n, arrivals):\n\n lambda_ = 1 - (1 / np.sqrt(n))\n\n super().__init__(n, lambda_, arrivals)\n\n self.epsilon = (1 / np.sqrt(n))\n\n self.empty_queues.append(self.n - 1)\n self.two_queues.append(0)\n self.three_queues.append(0)\n\n # RUN\n def run_simulation(self):\n # Simulates events in a continuous time space by determining which will happen the soonest\n # from given service and arrival times.\n\n start_time = time.time()\n for i in range(self.num_arrivals):\n\n min_s = min(self.service_times, key=self.service_times.get)\n\n # Arrival\n if min(self.t, self.service_times.get(min_s)) == self.t:\n self.T += self.t\n shortest = min(self.queues, key=self.queues.get)\n temp_str = 's_' + ''.join(filter(str.isdigit, shortest))\n\n self.queues[shortest] += 1\n self.count(self.queues[shortest], 'arrival')\n\n # Adjust arrival and service times\n if self.queues.get(shortest) == 1:\n self.service_times[temp_str] = np.random.exponential(1)\n\n for j in self.service_times:\n if j == temp_str:\n continue\n\n elif self.service_times.get(j) != self.INF:\n self.service_times[j] -= self.t\n else:\n for j in self.service_times:\n if self.service_times.get(j) != self.INF:\n self.service_times[j] -= self.t\n\n self.t = np.random.exponential(1 / (self.n * self.lambda_))\n\n # Service completed\n else:\n self.T += self.service_times.get(min_s)\n\n aux = self.service_times.get(min_s)\n temp_str = 'q_' + ''.join(filter(str.isdigit, min_s))\n\n self.queues[temp_str] -= 1\n self.count(self.queues[temp_str], 'service')\n\n # Adjust arrival and service times\n if self.queues.get(temp_str) == 0:\n self.service_times[min_s] = self.INF\n\n else:\n self.service_times[min_s] = np.random.exponential(1)\n\n self.t -= aux\n\n for j in self.service_times:\n if j != min_s and self.service_times.get(j) != self.INF:\n self.service_times[j] -= aux\n\n queue_sum = sum(self.queues.values())\n\n q_avg = queue_sum / self.n\n\n self.queue_sums[self.qs_i] = queue_sum\n self.qs_i += 1\n\n self.norm_q_perpendicular[self.qpe_i] = QueueFunctions.perpendicular_norm(q_avg, **self.queues)\n self.qpe_i += 1\n\n print(i)\n\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n\n # PLOTTING\n def draw_plots(self):\n # Plots the log of upper tail probabilities\n\n plt.style.use('seaborn-dark')\n\n super().draw_plots()\n\n # Halfin-Witt\n\n # Empty Queues\n plt.figure(1)\n x_values = np.arange(1, self.n + 1, 1)\n\n y_values = [\n np.abs(np.log(\n QueueFunctions.upper_tail_prob(i, self.n, *self.empty_queues[int(len(self.empty_queues) / 2):])))\n for i in x_values]\n\n temp_y = [i for i in y_values if i != np.inf]\n temp_x = [x_values[i] for i in range(len(temp_y))]\n\n m = np.polyfit(temp_x, temp_y, 2)\n\n curve_fit_y = [m[0] * (i ** 2) + m[1] * i + m[2] for i in temp_x]\n\n plt.scatter(x_values, y_values)\n plt.plot(temp_x, curve_fit_y, label='Curve Fit', color='brown')\n\n plt.title(\"Empty queues\")\n plt.ylabel('Log of Probability')\n plt.xlabel('x')\n plt.grid()\n plt.autoscale()\n plt.legend(loc='upper right')\n plt.show()\n\n print(m)\n\n # Two or more\n plt.figure(2)\n y_values = [\n np.abs(\n np.log(QueueFunctions.upper_tail_prob(i, self.n, *self.two_queues[int(len(self.two_queues) / 2):])))\n for i in x_values]\n\n temp_y = [i for i in y_values if i != np.inf]\n temp_x = [x_values[i] for i in range(len(temp_y))]\n\n m = np.polyfit(temp_x, temp_y, 1)\n\n linear_fit_y = [m[0] * i + m[1] for i in temp_x]\n\n plt.scatter(temp_x, temp_y)\n plt.plot(temp_x, linear_fit_y, label='Linear Fit', color='brown')\n\n plt.title(\"Queues with two or more customers\")\n plt.ylabel('Log of Probability')\n plt.xlabel('x')\n plt.grid()\n plt.autoscale()\n plt.legend(loc='upper right')\n plt.show()\n\n print(m)\n\n # To count number of empty queues, etc.\n def count(self, length, mode):\n if mode == 'arrival':\n if length == 1:\n self.empty_queues.append(self.empty_queues[-1] - 1)\n self.two_queues.append(self.two_queues[-1])\n self.three_queues.append(self.three_queues[-1])\n\n elif length == 2:\n self.two_queues.append(self.two_queues[-1] + 1)\n self.empty_queues.append(self.empty_queues[-1])\n self.three_queues.append(self.three_queues[-1])\n\n elif length >= 3:\n self.three_queues.append(self.three_queues[-1] + 1)\n self.empty_queues.append(self.empty_queues[-1])\n self.two_queues.append(self.two_queues[-1])\n\n elif mode == 'service':\n if length == 0:\n self.empty_queues.append(self.empty_queues[-1] + 1)\n self.two_queues.append(self.two_queues[-1])\n self.three_queues.append(self.three_queues[-1])\n elif length == 1:\n self.two_queues.append(self.two_queues[-1] - 1)\n self.empty_queues.append(self.empty_queues[-1])\n self.three_queues.append(self.three_queues[-1])\n elif length == 2:\n self.three_queues.append(self.three_queues[-1] - 1)\n self.empty_queues.append(self.empty_queues[-1])\n self.two_queues.append(self.two_queues[-1])\n","repo_name":"milton-pagan/load-balancing-simulations","sub_path":"load_balancing_simulations/HalfinWitt.py","file_name":"HalfinWitt.py","file_ext":"py","file_size_in_byte":6623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"4876283327","text":"\r\n\r\nimport cv2\r\nfrom matplotlib import pyplot as plt\r\n\r\nimg=cv2.imread('gurultuluresim.JPG',0)\r\n\r\n_,th1=cv2.threshold(img,127,255,cv2.THRESH_BINARY)\r\n_,th2=cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\r\n\r\nblur=cv2.GaussianBlur(img,(5,5),0)\r\n_,th3=cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\r\n\r\nresimler=[img,0,th1,\r\n img,0,th2,\r\n blur,0,th3]\r\nbasliklar=['orjinal g resim','Histogram','Basit Thresholding(127)',\r\n 'orjinal g resim', 'Histogram','Otsu Thresholding',\r\n 'Gaussian Blur', 'Histogram', 'Otsu Thresholding']\r\n\r\nfor i in range(3):\r\n plt.subplot(3,3,i*3+1),plt.imshow(resimler[i*3],'gray')\r\n plt.title(basliklar[i*3]),plt.xticks([]),plt.yticks([])\r\n plt.subplot(3,3,i*3+2),plt.hist(resimler[i*3].ravel(),256)\r\n plt.title(basliklar[i*3+1]),plt.xticks([]),plt.yticks([])\r\n plt.subplot(3,3,i*3+3),plt.imshow(resimler[i*3+2],'gray')\r\n plt.title(basliklar[i*3+2]),plt.xticks([]),plt.yticks([])\r\n\r\nplt.show()","repo_name":"Berbet16/OpenCV","sub_path":"Examples/otsu_thresholding.py","file_name":"otsu_thresholding.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"18978933888","text":"import argparse\nimport functools\n\n# import matplotlib.pyplot as plt\nfrom torch.autograd import Variable\nimport io\nimport json\nimport logging\nimport os\n\nimport numpy as np\nimport requests\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nfrom PIL import Image\nfrom torch.nn import init\nimport torch.nn.functional as F\nimport torch.nn.parallel\nimport torch.optim\nimport torch.utils.data\nimport torch.utils.data.distributed\nimport torchvision\nimport torchvision.models\nimport torchvision.transforms as transforms\n\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n###########\n# model \n###########\n\nclass ResnetBlock(nn.Module):\n def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias):\n super(ResnetBlock, self).__init__()\n self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout, use_bias)\n\n def build_conv_block(self, dim, padding_type, norm_layer, use_dropout, use_bias):\n conv_block = []\n p = 0\n if padding_type == 'reflect':\n conv_block += [nn.ReflectionPad2d(1)]\n elif padding_type == 'replicate':\n conv_block += [nn.ReplicationPad2d(1)]\n elif padding_type == 'zero':\n p = 1\n else:\n raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n\n conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias),\n norm_layer(dim),\n nn.ReLU(True)]\n if use_dropout:\n conv_block += [nn.Dropout(0.5)]\n\n p = 0\n if padding_type == 'reflect':\n conv_block += [nn.ReflectionPad2d(1)]\n elif padding_type == 'replicate':\n conv_block += [nn.ReplicationPad2d(1)]\n elif padding_type == 'zero':\n p = 1\n else:\n raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias),\n norm_layer(dim)]\n\n return nn.Sequential(*conv_block)\n\n def forward(self, x):\n out = x + self.conv_block(x)\n return out\n\n\nclass ResnetGenerator(nn.Module):\n def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6,\n gpu_ids=[], padding_type='reflect'):\n assert (n_blocks >= 0)\n super(ResnetGenerator, self).__init__()\n self.input_nc = input_nc\n self.output_nc = output_nc\n self.ngf = ngf\n self.gpu_ids = gpu_ids\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n\n model = [nn.ReflectionPad2d(3),\n nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0,\n bias=use_bias),\n norm_layer(ngf),\n nn.ReLU(True)]\n\n n_downsampling = 2\n for i in range(n_downsampling):\n mult = 2 ** i\n model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3,\n stride=2, padding=1, bias=use_bias),\n norm_layer(ngf * mult * 2),\n nn.ReLU(True)]\n\n mult = 2 ** n_downsampling\n for i in range(n_blocks):\n model += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout,\n use_bias=use_bias)]\n\n for i in range(n_downsampling):\n mult = 2 ** (n_downsampling - i)\n model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2),\n kernel_size=3, stride=2,\n padding=1, output_padding=1,\n bias=use_bias),\n norm_layer(int(ngf * mult / 2)),\n nn.ReLU(True)]\n model += [nn.ReflectionPad2d(3)]\n model += [nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)]\n model += [nn.Tanh()]\n\n self.model = nn.Sequential(*model)\n\n def forward(self, my_input):\n if self.gpu_ids and isinstance(input.data, torch.cuda.FloatTensor):\n return nn.parallel.data_parallel(self.model, input, self.gpu_ids)\n else:\n return self.model(my_input)\n\n\ndef model_fn(model_dir):\n logger.info(\"model_fn\")\n device = \"cpu\"\n\n def weights_init_normal(m):\n classname = m.__class__.__name__\n # print(classname)\n if classname.find('Conv') != -1:\n nn.init.normal_(m.weight.data, 0.0, 0.02)\n elif classname.find('Linear') != -1:\n nn.init.normal_(m.weight.data, 0.0, 0.02)\n elif classname.find('BatchNorm2d') != -1:\n nn.init.normal_(m.weight.data, 1.0, 0.02)\n\n norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False)\n my_model = ResnetGenerator(3, 3, 64, norm_layer=norm_layer, use_dropout=False, n_blocks=9, gpu_ids=[]).apply(weights_init_normal)\n\n with open(os.path.join(model_dir, \"4d1443ff103ea241e2da442500a881f2.pth\"), \"rb\") as f:\n try: \n state_dict = torch.load(f)\n my_model.load_state_dict(state_dict)\n except RuntimeError: # delete running_mean and running var\n for k in list(state_dict.keys()):\n if (k.find('running_mean') > 0) or (k.find('running_var') > 0):\n del state_dict[k]\n my_model.load_state_dict(state_dict)\n return my_model.to(device)\n\n\ndef input_fn(request_body, content_type='application/json'):\n logger.info('Deserializing the input data.')\n if content_type == 'application/json':\n input_data = json.loads(request_body)\n url = input_data['url']\n logger.info(f'Image url: {url}')\n image_data = Image.open(requests.get(url, stream=True).raw)\n else:\n image_data = Image.open(io.BytesIO(request_body))\n transform_list = [transforms.Resize(size=256),\n# transforms.CenterCrop(size=224),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5),\n (0.5, 0.5, 0.5))]\n transform = transforms.Compose(transform_list)\n img_t = transform(image_data)\n batch_t = torch.unsqueeze(img_t, 0)\n\n return Variable(batch_t)\n\n\ndef predict_fn(input_data, my_model):\n logger.info('Generating prediction based on input parameters.')\n with torch.no_grad():\n my_model.eval()\n return my_model(input_data)\n \n\ndef output_fn(prediction_output, accept='application/json'):\n image_numpy = prediction_output[0].cpu().float().detach().numpy()\n if image_numpy.shape[0] == 1:\n image_numpy = np.tile(image_numpy, (3, 1, 1))\n image_numpy = ((np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0).astype(np.uint8)\n return json.dumps(image_numpy.tolist())\n","repo_name":"NeuraInk/NeuraInk_Backend","sub_path":"SageMaker_ML_Deployment/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":7036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"27300002394","text":"import re, math\n\ndef oneStar(lines):\n mask = \"\"\n mem = {}\n for line in lines:\n a = line.split(\"=\")\n if a[0].strip() == \"mask\":\n mask = a[1].strip()\n else:\n memLoc = a[0][4:-2]\n number = a[1].strip()\n mem[memLoc] = applyMask(number, mask)\n print(sum(mem.values()))\n\ndef applyMask(number, mask):\n modMask = mask.replace(\"X\", \"1\")\n stepOne = int(number) & int(modMask,2)\n modMask = mask.replace(\"X\", \"0\")\n stepTwo = stepOne | int(modMask,2)\n return stepTwo\n\ndef twoStar(lines):\n mem = {}\n allMemLocs = []\n for line in lines:\n a = line.split(\"=\")\n if a[0].strip() == \"mask\":\n mask = a[1].strip()\n else:\n memLoc = a[0][4:-2]\n number = int(a[1].strip())\n allMemLocs = getAllMemLocs(memLoc, mask)\n for loc in allMemLocs:\n mem[int(loc,2)] = number\n print(sum(mem.values()))\n \ndef getAllMemLocs(addr, mask):\n floatingIdx = [m.start() for m in re.finditer(\"X\", mask)]\n floatingIdx.reverse()\n allAddrs = []\n longAddr = f'{int(addr):036b}'\n potAddr = \"\"\n for i, letter in enumerate(mask):\n if letter == \"1\":\n potAddr += letter\n elif letter == \"0\":\n potAddr += longAddr[i]\n else:\n potAddr += \"X\"\n for i in range(2**len(floatingIdx)):\n tempAddr = potAddr\n binaryStr = f'{i:036b}'\n for j, floatIdx in enumerate(floatingIdx):\n tempAddr = tempAddr[:floatIdx] + binaryStr[-(j+1)] + tempAddr[floatIdx+1:]\n allAddrs.append(tempAddr)\n return allAddrs\n\nif __name__ == '__main__':\n file1 = open('data14', 'r')\n lines = file1.read().splitlines()\n oneStar(lines)\n twoStar(lines)\n","repo_name":"martinoman/advent-of-code2020","sub_path":"day14/day14.py","file_name":"day14.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"40531958954","text":"from bs4 import BeautifulSoup\nimport getopt, sys\nimport os # path.basename\n\nusage = \"Usage: \" + sys.argv[0] + \" [-h] [-i] [-p part] file.xml\\n\"\\\n \"Extract or transform information from a musicxml file.\\n\"\\\n \"\\n -h\\tshow this help\\n\"\\\n \" -i\\tshow information about the song\\n\"\\\n \" -p part\\tgenerate .h to include in the project\\n\"\n\nmain_options = \"hip:\"\n\nfile_header=\\\n\"// This file has been generated by \" + os.path.basename(sys.argv[0]) + \"\\n\"\\\n\"// Copyright (C) 2023 Manuel Perez \\n\"\\\n\"// mail: \\n\"\\\n\"// https://github.com/amanuellperez/mcu\\n\"\\\n\"//\\n\"\\\n\"// This file is part of the MCU++ Library.\\n\"\\\n\"//\\n\"\\\n\"// MCU++ Library is a free library: you can redistribute it and/or modify\\n\"\\\n\"// it under the terms of the GNU General Public License as published by\\n\"\\\n\"// the Free Software Foundation, either version 3 of the License, or\\n\"\\\n\"// (at your option) any later version.\\n\"\\\n\"//\\n\"\\\n\"// This library is distributed in the hope that it will be useful,\\n\"\\\n\"// but WITHOUT ANY WARRANTY; without even the implied warranty of\\n\"\\\n\"// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\\n\"\\\n\"// GNU General Public License for more details.\\n\"\\\n\"//\\n\"\\\n\"// You should have received a copy of the GNU General Public License\\n\"\\\n\"// along with this program. If not, see .\\n\"\\\n\"#pragma once\\n\"\\\n\"\\n#ifndef __PRJ_SONGS_H__\\n\"\\\n\"#define __PRJ_SONGS_H__\\n\"\\\n\"\\n#include \\n\"\\\n\"#include \\\"mus_musician.h\\\"\\n\"\n\nfile_tail=\"\\n\\n#endif\"\n\n\ndef open_tree(xml_name):\n with open(xml_name) as xml_doc:\n return BeautifulSoup(xml_doc, \"xml\")\n\n# -------------------------\n# DUDA: con tanto replace seguramente sea más efectivo hacer un bucle for\ndef remove_spaces(str):\n return str.replace(' ', '_').replace('(', '').replace(')', '')\n\n# ------------\ndef error(err):\n print(err)\n print(usage)\n sys.exit(1)\n\n\n# -------------------------\ndef song_name(soup):\n movement_title = soup.find(\"movement-title\")\n if (movement_title != None):\n return remove_spaces(movement_title.string)\n\n work_title = soup.work.find(\"work-title\")\n if (work_title != None):\n return remove_spaces(work_title.string)\n\n return \"unname_song\"\n\n\n# ------------\ndef args(argv):\n try:\n opts, args = getopt.getopt(argv[1:], main_options)\n\n except getopt.GetoptError as err:\n error(err)\n\n if (len(args) != 1 or ('-h', '') in opts):\n print (usage)\n sys.exit(2)\n\n return args[0], opts\n\n\n# -------------------------\ndef generate_header_part(xml_name, part_number):\n\n soup = open_tree(xml_name)\n\n print(file_header)\n print_file_body(soup, part_number)\n print(file_tail)\n\n\n# -------------------------\ndef print_file_body(soup, part_number):\n part_name = []\n for scpart in soup.find_all(\"score-part\"):\n pn = scpart.find(\"part-name\")\n part_name.append(pn.string)\n # print(scpart[\"id\"], \":\", pn.string)\n id = 0\n for part in soup.find_all(\"part\"):\n if (part_number == \"0\" or part_number == part[\"id\"]):\n notes = part.find_all(\"note\")\n notes = [note for note in notes if note.pitch != None]\n num_notes = len(notes)\n\n print(\"\\n\\n// PART \", part[\"id\"], \":\", part_name[id])\n print(\"constexpr const atd::Progmem_array PROGMEM\\n\"\n , song_name(soup) + \"_\" + part[\"id\"]\n , \" =\\n{\")\n\n i = 1\n for note in notes:\n if (note.pitch != None):\n print( \" music::Note{\", note.pitch.octave.string\n , \", music::Step::\", note.pitch.step.string\n , \", \", note.type.string\n , \"}\", end = '')\n\n if (i != num_notes):\n print(\",\")\n\n i += 1\n\n print(\"\\n};\")\n\n id += 1 \n\n\n\n\n# -------------------------\ndef info(xml_name):\n soup = open_tree(xml_name)\n\n print(\"\\nINFO\")\n work_title = soup.work.find(\"work-title\")\n if (work_title != None):\n print(\" Work title\\t:\", work_title.string)\n\n work_number = soup.work.find(\"work-number\")\n if (work_number != None):\n print(\" Work number\\t:\", work_number.string)\n\n movement_title = soup.find(\"movement-title\")\n if (movement_title!= None):\n print(\" Song title\\t:\", movement_title.string)\n\n composer = soup.find(type = \"composer\")\n if (composer != None):\n print(\" Composer\\t:\", composer.string)\n\n\n\n # parts\n # -----\n print(\"\\nPARTS\")\n for scpart in soup.find_all(\"score-part\"):\n pn = scpart.find(\"part-name\")\n print(\" \", scpart[\"id\"], \":\", pn.string)\n\n\n# ------------\ndef main():\n xml_name, opts = args(sys.argv)\n\n for opt, arg in opts:\n if opt == '-i':\n info(xml_name)\n return\n\n elif opt == '-p':\n generate_header_part(xml_name, arg)\n\n \n generate_header_part(xml_name, \"0\")\n\n\n# program\n# -------\nif __name__ == \"__main__\":\n main()\n\n\n\n","repo_name":"amanuellperez/mcu","sub_path":"src/prj/music/tools/read_musicxml.py","file_name":"read_musicxml.py","file_ext":"py","file_size_in_byte":5173,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"77"}
+{"seq_id":"43845686672","text":"import random\n\n\noptions = [\"scissors\", \"stone\", \"paper\"]\n\nuser_score = 0\ncomputer_score = 0\n\n\nfor i in range(5):\n \n computer_choice = random.choice(options)\n \n \n user_choice = input(\"Enter your choice (scissors, stone, or paper): \")\n \n \n if user_choice == computer_choice:\n print(\"Tie!\")\n elif user_choice == \"scissors\" and computer_choice == \"paper\":\n print(\"You win!\")\n user_score += 1\n elif user_choice == \"paper\" and computer_choice == \"stone\":\n print(\"You win!\")\n user_score += 1\n elif user_choice == \"stone\" and computer_choice == \"scissors\":\n print(\"You win!\")\n user_score += 1\n else:\n print(\"Computer wins!\")\n computer_score += 1\n\n\nprint(\"Final scores:\")\nprint(f\"You: {user_score}\")\nprint(f\"Computer: {computer_score}\")\n","repo_name":"davitsvirava/jeirani-game","sub_path":"jeirani.py","file_name":"jeirani.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"73730686328","text":"\"\"\"\nName: Henri Prudhomme\nClass: CS344\n\nProblem Specifications: \n Initial state: Wolf and Sheep are on spot 1\n Goal: Move Wolf and Sheep to spot 2\n Actions: \n 1. Wolf kills Sheep and then moves to spot 2. \n 2. Move Sheep to spot 2 after which Wolf chases and moves to spot 2.\n\nSolution: Move sheep to spot 2, Wolf follows and ends up at spot 2. Puzzle solved.\n\nWhy GPS fails: Gps tries to achieve goal of moving Wolf to spot 2, but ends up killing sheep.\n Then there is no sheep left alive, so the Gps program breaks.\n\nHow to make things work: Swap goals so that 'Sheep is on spot 2' is the first goal\n\"\"\"\nfrom gps import gps\n\n# Formulate the problem states and actions.\nproblem = {\n 'initial': ['Wolf is on spot 1', 'Sheep is on spot 1'],\n 'goal': ['Wolf is on spot 2', 'Sheep is on spot 2'],\n\n 'actions': [\n {\n 'action': 'Wolf eats sheep and moved from spot 1 to spot 2',\n 'preconds': [\n 'Wolf is on spot 1',\n 'Sheep is on spot 1'\n ],\n 'add': [\n 'Wolf is on spot 2',\n ],\n 'delete': [\n 'Sheep is on spot 1',\n 'Wolf is on spot 1'\n ]\n },\n {\n 'action': 'Sheep is moved from spot 1 to spot 2',\n 'preconds': [\n 'Wolf is on spot 1',\n 'Sheep is on spot 1'\n ],\n 'add': [\n 'Sheep is on spot 2',\n 'Wolf is on spot 2'\n ],\n 'delete': [\n 'Sheep is on spot 1',\n 'Wolf is on spot 1'\n ]\n }\n ]\n}\n\nif __name__ == '__main__':\n print('Solution to part a.')\n # Use GPS to solve the problem formulated above.\n actionSequence = gps(\n problem['initial'],\n problem['goal'],\n problem['actions']\n )\n\n # Print the solution, if there is one.\n if actionSequence is not None:\n for action in actionSequence:\n print(action)\n else:\n print('plan failure...')","repo_name":"Henripru/cs344","sub_path":"lab01/lab_3.py","file_name":"lab_3.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"74116212407","text":"\r\nimport numpy as np\r\n\r\ndef sample_size(x):\r\n # Calculate the sample size\r\n n_x = np.size(x)\r\n # n_y = np.size(y)\r\n return (n_x)\r\n\r\n\r\ndef calc_mean(x):\r\n # Calculate the mean\r\n x_m = np.mean(x)\r\n # y_m = np.mean(y)\r\n return (x_m)\r\n\r\n\r\ndef main():\r\n # Main\r\n x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\r\n y = np.array([1, 3, 5, 8, 13, 15, 18, 20, 21, 23])\r\n # Print the array\r\n print('x array: ', x)\r\n print('x array: ', y)\r\n\r\n # Print size of array\r\n n_x = sample_size(x)\r\n n_y = sample_size(y)\r\n print('x size ', n_x)\r\n print('y size ', n_y)\r\n\r\n # Print the mean\r\n x_m = calc_mean(x)\r\n y_m = calc_mean(y)\r\n print('x mean: ', x_m)\r\n print('y mean: ', y_m)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"fahadasat/pybot","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"19655541566","text":"import matplotlib.pyplot as plt\nimport sys\nimport math \nimport numpy\n\ndatafile1 = sys.argv[1]\n\nf = open(datafile1,'r')\n\n\ncc =[]\nchi_square_log = []\n\nfor ll in f.readlines():\n elements=ll.split()\n cc.append(float(elements[0]))\n chi_square_log.append(numpy.log(float(elements[0])))\n\n\nplt.scatter(cc,chi_square_log)\nplt.xlabel('cc') \n# plt.xlim(xmax=0.75,xmin=0.7)\nplt.ylabel('chi_square_log') \n\n\nplt.savefig(\"./cc_chi_5484.png\")\nplt.show()","repo_name":"wangyufan/alignment","sub_path":"plot_cc_chi.py","file_name":"plot_cc_chi.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"15289329820","text":"import logging\n\nfrom typing import Dict, Optional\n\nfrom cattr import structure\n\nfrom robcoewmtypes.helper import get_sample_cr\nfrom robcoewmtypes.warehouseorder import (\n ConfirmWarehouseTask, WarehouseOrderCRDSpec)\n\nfrom k8scrhandler.k8scrhandler import K8sCRHandler\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass OrderHandler(K8sCRHandler):\n \"\"\"Handle K8s custom resources.\"\"\"\n\n def __init__(self, namespace: str) -> None:\n \"\"\"Construct.\"\"\"\n template_cr = get_sample_cr('warehouseorder')\n\n labels: Dict[str, str] = {}\n super().__init__(\n 'ewm.sap.com',\n 'v1alpha1',\n 'warehouseorders',\n namespace,\n template_cr,\n labels\n )\n\n @staticmethod\n def warehouse_order_precheck(\n name: str, custom_res: Dict, robot_name: Optional[str] = None) -> bool:\n \"\"\"Check if warehouse order has to be processed in callback.\"\"\"\n # Check if the order belongs to the right robot\n if robot_name is not None:\n if custom_res['metadata'].get('labels', {}).get(\n 'cloudrobotics.com/robot-name') != robot_name:\n _LOGGER.info(\n 'Skip \"%s\" because warehouse order is assigned to a different robot', name)\n return False\n # Skip warehouse order if process status from order manager is not\n # equal to status of the warehouse order. Consider entries for own robot resource only\n process_status = [s for s in custom_res['spec'].get(\n 'process_status', []) if s['rsrc'].lower() == custom_res['metadata'].get(\n 'labels', {}).get('cloudrobotics.com/robot-name')]\n status_data = custom_res.get('status', {}).get('data', [])\n if status_data != process_status:\n _LOGGER.info(\n 'Skip \"%s\" because order manager process status is not equal to warehouse order '\n 'status', name)\n return False\n\n # Check if a warehouse task is already confirmed\n if status_data:\n for wht in custom_res['spec']['data']['warehousetasks']:\n for conf in status_data:\n if wht['tanum'] == conf['tanum'] and wht['lgnum'] == conf['lgnum']:\n if (conf['confirmationnumber'] == ConfirmWarehouseTask.FIRST_CONF\n and conf['confirmationtype'] == ConfirmWarehouseTask.CONF_SUCCESS\n and wht['vlpla'] != ''):\n _LOGGER.error(\n 'Skip \"%s\" because warehouse task \"%s\" already got first '\n 'confirmation but includes a source bin', name, wht['tanum'])\n return False\n if (conf['confirmationnumber'] == ConfirmWarehouseTask.SECOND_CONF\n and conf['confirmationtype'] == ConfirmWarehouseTask.CONF_SUCCESS):\n _LOGGER.info(\n 'Skip \"%s\" because warehouse task \"%s\" already got second '\n 'successful confirmation', name, wht['tanum'])\n return False\n\n return True\n\n def confirm_wht(self, wht: Dict) -> None:\n \"\"\"Notify order manager about current status of who + tasks.\"\"\"\n # Warehouse order CR name must be lower case\n name = '{lgnum}.{who}'.format(lgnum=wht['lgnum'], who=wht['who']).lower()\n # Get current status from custom resource of the warehouse order\n custom_res = self.get_cr(name)\n status = custom_res.get('status') if isinstance(custom_res.get('status'), dict) else {}\n # Append current wht confirmation to status\n if not status.get('data'):\n status['data'] = []\n # Check if confirmation was already sent\n for conf in status['data']:\n if conf == wht:\n _LOGGER.error('Confirmation already sent. Not doing anything.')\n return\n status['data'].append(wht)\n self.update_cr_status(name, status)\n\n def get_warehouseorder(\n self, lgnum: str, who: str,\n robot_name: Optional[str] = None) -> Optional[WarehouseOrderCRDSpec]:\n \"\"\"Get a warehouse order from CR.\"\"\"\n # Warehouse order CR name must be lower case\n name = '{}.{}'.format(lgnum, who).lower()\n\n if self.check_cr_exists(name):\n custom_res = self.get_cr(name)\n if self.warehouse_order_precheck(name, custom_res, robot_name):\n return structure(custom_res['spec'], WarehouseOrderCRDSpec)\n else:\n return None\n else:\n return None\n\n def add_who_finalizer(self, lgnum: str, who: str, robot: str) -> None:\n \"\"\"Add a finalizer to warehouse order CR.\"\"\"\n # Warehouse order CR name must be lower case\n name = '{}.{}'.format(lgnum, who).lower()\n\n finalizer = '{}.ewm-robot-controller.sap.com'.format(robot)\n\n if self.add_finalizer(name, finalizer):\n _LOGGER.info('Added finalizer %s to warehouse order CR %s', finalizer, name)\n\n def remove_who_finalizer(self, lgnum: str, who: str, robot: str) -> None:\n \"\"\"Add a finalizer from warehouse order CR.\"\"\"\n # Warehouse order CR name must be lower case\n name = '{}.{}'.format(lgnum, who).lower()\n\n finalizer = '{}.ewm-robot-controller.sap.com'.format(robot)\n\n if self.remove_finalizer(name, finalizer):\n _LOGGER.info('Removed finalizer %s from warehouse order CR %s', finalizer, name)\n","repo_name":"ep-infosec/34_sap_ewm-cloud-robotics","sub_path":"python-modules/robcoewmrobotcontroller/robcoewmrobotcontroller/ordercontroller.py","file_name":"ordercontroller.py","file_ext":"py","file_size_in_byte":5636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"4414391615","text":"import torch\nimport torch.nn as nn\nfrom transformers import AlbertModel\nfrom transformers.modeling_outputs import BaseModelOutputWithPooling\n\nclass AlbertModelForContrastiveLearning(AlbertModel):\n def __init__(self, config, generator, add_pooling_layer=True):\n super().__init__(config, add_pooling_layer)\n self.generator = generator\n\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n return_sentence_embedding=False\n ):\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if input_ids is not None and inputs_embeds is not None:\n raise ValueError(\"You cannot specify both input_ids and inputs_embeds at the same time\")\n elif input_ids is not None:\n input_shape = input_ids.size()\n elif inputs_embeds is not None:\n input_shape = inputs_embeds.size()[:-1]\n else:\n raise ValueError(\"You have to specify either input_ids or inputs_embeds\")\n\n batch_size, seq_length = input_shape\n device = input_ids.device if input_ids is not None else inputs_embeds.device\n\n if attention_mask is None:\n attention_mask = torch.ones(input_shape, device=device)\n if token_type_ids is None:\n if hasattr(self.embeddings, \"token_type_ids\"):\n buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]\n buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)\n token_type_ids = buffered_token_type_ids_expanded\n else:\n token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)\n\n extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)\n extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility\n extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0\n head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)\n\n embedding_output = self.embeddings(\n input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds\n )\n\n if not return_sentence_embedding:\n self.generator.dynamic_process(embedding_output)\n\n encoder_outputs = self.encoder(\n embedding_output,\n extended_attention_mask,\n head_mask=head_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = encoder_outputs[0]\n\n pooled_output = self.pooler_activation(self.pooler(sequence_output[:, 0])) if self.pooler is not None else None\n\n if not return_dict:\n return (sequence_output, pooled_output) + encoder_outputs[1:]\n\n return BaseModelOutputWithPooling(\n last_hidden_state=sequence_output,\n pooler_output=pooled_output,\n hidden_states=encoder_outputs.hidden_states,\n attentions=encoder_outputs.attentions,\n )","repo_name":"Lollipop/CRLT","sub_path":"modules/models/albert_model_for_contrastive_learning.py","file_name":"albert_model_for_contrastive_learning.py","file_ext":"py","file_size_in_byte":3591,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"77"}
+{"seq_id":"7344022082","text":"import shutil\r\nimport glob\r\nimport numpy as np\r\nfrom skimage import io, color,transform\r\nfrom sklearn.cluster import MiniBatchKMeans\r\nfrom sklearn import metrics\r\nimport random\r\nfrom sklearn import svm\r\nfrom sklearn.preprocessing import StandardScaler\r\n\r\nfrom scipy.stats import norm\r\nimport cv2\r\nimport time\r\n\r\nfrom sklearn.manifold import TSNE\r\nfrom matplotlib import pyplot as plt\r\n\r\nnp.random.seed(0)\r\n#---------------------------------画像をグレースケールベクトル行列に変換-------------------------------\r\ndef get_gray_scale(label_list,dataDir_list):\r\n\t\r\n\tlabels=[]\r\n\tdata_grayscales=[]\r\n\timg_list=[]\r\n\tfor label,dataDir in zip(label_list,dataDir_list):\r\n\t\t#ワイルドカードでdataディレクトリ内の全ファイル名を取得してリスト化\r\n\t\tfiles = glob.glob(dataDir + \"*\")\r\n\t\tfor file in files:\t\r\n\t\t\tlabels.append(label)\r\n\t\t\t#バイナリーデータとして読み込む\r\n\t\t\timg = io.imread(file)\r\n\t\t\timg_list.append(img)\r\n\t\t\t#元がgray_scaleであるため\r\n\t\t\t#gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n#\t\t\t大きさ統一\r\n\t\t\t#gray_resize = cv2.resize(gray,(32,32))\r\n\t\t\tgray_resize = cv2.resize(img,(32,32))\r\n\t\t\tdata_grayscales.append(gray_resize)\r\n\t\r\n\t#各画像のHOG特徴量行列を要素とするリスト\r\n\tlabels, data_grayscales = np.array(labels), np.array(data_grayscales)\r\n\treturn labels, data_grayscales,img_list\r\n\r\n\r\ncar0Dir = './car/img/0/'\r\ncar1Dir = './car/img/1/'\r\ncar2Dir = './car/img/2/'\r\ndataDir_list=[car1Dir,car2Dir]\r\nlabel_list=[1,2]\r\n\r\ncarsum1Dir = './car/sum/1/'\r\ncarsum2Dir = './car/sum/2/'\r\nsum_dataDir_list=[carsum1Dir,carsum2Dir]\r\nsum_label_list=[1,2]\r\n\r\nlabels, data_grayscales, img_list = get_gray_scale(sum_label_list,sum_dataDir_list)\r\n\r\nimglines_set =[]\r\nfor img in data_grayscales:\r\n\t#print(img.shape) (400,300)\r\n\timglines =[]\r\n\tfor imgline in img:\r\n\t\timglines.extend(imgline)\r\n\r\n\timglines_set.append(imglines)\r\n\r\nimglines_set_np = np.array(imglines_set)\t\r\n\t\r\nimg_sets = np.vstack(imglines_set_np)\r\n\r\n#-----------t-sne\r\nmodel = TSNE(n_components=2,perplexity=50,learning_rate=50)\r\ntsne_result = model.fit_transform(img_sets)\r\n\r\nprint(tsne_result)\r\n\r\n\"\"\"\r\n#---------data_processing\r\ntsne_result = np.array([j for label,j in zip(labels,tsne_result) if label ==0 or label ==1 or label==2])\r\nprint(tsne_result)\r\n\r\nunique_cluster = set(labels)\r\ncluster_dict={}\r\nfor cluster in unique_cluster:\r\n\tcluster_dict[cluster]=[x for index,x in enumerate(tsne_result) if labels[index]==cluster]\r\n\t\r\n\r\n\r\n#plt.xlabel('val x', fontsize=20) # x軸ラベル\r\n#plt.ylabel('val y', fontsize=20) # y軸ラベル\r\n#plt.grid(True) # 目盛線の表示\r\n\r\n# グラフの描画\r\n#k:cluster label y:data items():辞書に含まれるすべてのキーと組み合せを取得\r\nfor k, v in cluster_dict.items():\r\n\tx_array = np.array(v)\r\n\tplt.scatter(x_array[:,0],x_array[:,1],s=50,alpha=0.3,label=k)\r\n\r\nplt.title('No. of cluster :2')\t\r\nplt.legend(bbox_to_anchor=(1.15,1),loc=\"upper right\", fontsize=14) # (7)凡例表示\r\nplt.show()\r\n\"\"\"\r\n\r\n#pickle 保存\r\n#import pickle\r\n\r\n#with open('new_tsne_data.pickle', 'wb') as f:\r\n# pickle.dump(tsne_result, f)\r\n\t\r\n#with open('dbscan_obj.pickle', 'rb') as f:\r\n#\thoge = pickle.load(f)\r\n#print(hoge)","repo_name":"shuntakahashi08/dbscan_algorithm","sub_path":"cars/car_tsne_data.py","file_name":"car_tsne_data.py","file_ext":"py","file_size_in_byte":3201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"12874038002","text":"# -*- coding: utf-8 -*-\nfrom logzero import logger\n\n\ndef phonetic_wrapper(kana, kanji, marking):\n parts = marking.split(';')\n\n if not kanji:\n wrapped = '' \\\n '
%s
' % kana + \\\n '
'\n elif not marking:\n wrapped = '' \\\n '
%s
' % kana + \\\n '
%s
' % kanji + \\\n '
'\n else:\n wrapped = kanji\n for index, part in enumerate(parts):\n to_kanji, from_kana = part.split(':')\n\n replaced_by = extract_by_pos(kana, from_kana)\n html_snippet = '' \\\n '
%s
' % replaced_by + \\\n '
%s
' \\\n '
'\n wrapped = wrap_word2(wrapped, len(kanji), to_kanji, html_snippet)\n\n return wrapped\n\n\ndef extract_by_pos(words, pos):\n \"\"\"\n\n :param words:\n :param pos:\n pos is start-end, like (start, end]\n :return:\n \"\"\"\n if '-' in pos:\n start, end = pos.split('-')\n logger.info('extract_by_pos start: %s, end: %s', start, end)\n if end:\n return words[int(start): int(end) + 1]\n else:\n return words[int(start):]\n else:\n return words[int(pos)]\n\n\ndef wrap_word2(need_wrapped, origin_length, pos, to):\n \"\"\"\n\n :param need_wrapped:\n :param origin_length:\n :param pos:\n start-end\n :param to:\n :return:\n \"\"\"\n if '-' in pos:\n start, end = pos.split('-')\n logger.info('wrap_word2 start: %s, end: %s', start, end)\n return wrap_word(need_wrapped, origin_length, int(start), int(end) - int(start), to)\n else:\n return wrap_word(need_wrapped, origin_length, int(pos), 1, to)\n\n\ndef wrap_word(need_wrapped, origin_length, start, length, to):\n \"\"\"\n\n :param need_wrapped:\n 需要处理的字符串\n :param origin_length:\n 最原始字符串长度\n :param start:\n 替换的起始位置,基于原始字符串\n :param length:\n 需要替换的长度\n :param to:\n 替换为的部分,可包括 %s 引用被替换的部分\n :return:\n \"\"\"\n length_fix = len(need_wrapped) - origin_length\n need_wrapped_list = list(need_wrapped)\n if '%s' in to:\n need_replace = need_wrapped_list[length_fix + start:length_fix + start + length]\n wrapped_chars = to % ''.join(need_replace)\n else:\n wrapped_chars = to\n\n before = ''.join(need_wrapped_list[0:length_fix + start])\n after = ''.join(need_wrapped_list[length_fix + start + length:])\n return before + wrapped_chars + after\n","repo_name":"danielwii/benkyo","sub_path":"core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"27447965731","text":"N = int(input())\r\nA, B = [int(_) for _ in input().split()]\r\nK = int(input())\r\nP = [int(_) for _ in input().split()]\r\n\r\nfrom collections import defaultdict\r\n\r\ncs = defaultdict(int)\r\n\r\ncs[A] += 1\r\ncs[B] += 1\r\n\r\nresult = True\r\n\r\nfor x in P:\r\n cs[x] += 1\r\n if cs[x] >= 2:\r\n result = False\r\n\r\nif result:\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")\r\n","repo_name":"hirosuzuki/procon","sub_path":"atcoder/abc/abc021_b.py","file_name":"abc021_b.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"6373534711","text":"from albumentations.pytorch.transforms import ToTensorV2\nimport albumentations as A\n\n\nINFER_TRANSFORMS = A.Compose([\n A.JpegCompression(p=0.5),\n A.HorizontalFlip(p=0.8),\n A.VerticalFlip(p=0.3),\n A.CenterCrop(height=128, width=128, always_apply=True),\n A.Normalize(),\n ToTensorV2(),\n], p=1.0)\n","repo_name":"thepooons/melanoma-comp-2020","sub_path":"src/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"}
+{"seq_id":"29330600009","text":"#Aprobación de créditos\ningreso= int(input(\"Su ingreso en pesos: \"))\nano_naci= int(input(\"Año de nacimiento: \"))\nhi_jos= int(input(\"Ingrese el numero de hijos: \"))\nano_pert= int(input(\"Ingrese los años de pertenecia al banco: \"))\nestado_civil= str(input(\"Ingrese su estado civil: \")) \nrural_urban= str(input(\"Ingrese si vive en zona Urbana o Rural: \"))\n\nif (10 < ano_pert)and (2 <= hi_jos):\n print(\"APROBADO\")\nelif(estado_civil == \"C\")and (3 < hi_jos) and (1965 < ano_naci < 1977):\n print(\"APROBADO\")\nelif(2500000 < ingreso)and (estado_civil == \"S\")and (rural_urban == \"U\"):\n print(\"APROBADO\") \nelif (3500000 < ingreso) and (5 < ano_pert):\n print(\"APROBADO\")\nelif (rural_urban == \"R\") and (estado_civil == \"C\")and (hi_jos < 2):\n print(\"APROBADO\")\nelse:\n print(\"RECHAZADO\") ","repo_name":"pabloschwarzenberg/grader","sub_path":"hito1_ej3/hito1_ej3_b1d30b5d2a349bf0ed9610ff8195f951.py","file_name":"hito1_ej3_b1d30b5d2a349bf0ed9610ff8195f951.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"13729907231","text":"import tkinter\n\nequation_calculation = ''\nequation_text = ''\nequation_display_label = None\n\n\ndef button_press(num):\n global equation_calculation, equation_text, equation_display_label\n\n equation_calculation += num\n\n if num == '**':\n equation_text += '^'\n elif num == '*':\n equation_text += 'x'\n else:\n equation_text += num\n equation_display_label.set(equation_text)\n\n\ndef clear():\n global equation_calculation, equation_text, equation_display_label\n\n equation_calculation = ''\n equation_text = ''\n equation_display_label.set(equation_text)\n\n\ndef equal():\n global equation_calculation, equation_text, equation_display_label\n\n try:\n equation_calculation = str(eval(equation_calculation))\n equation_text = equation_calculation\n equation_display_label.set(equation_text)\n except SyntaxError:\n equation_display_label.set('Syntax error')\n except ZeroDivisionError:\n equation_display_label.set(\"Arithmetic error\")\n\n\ndef backspace():\n global equation_calculation, equation_text, equation_display_label\n equation_calculation = equation_calculation[:-1]\n equation_text = equation_text[:-1]\n equation_display_label.set(equation_text)\n\n\ndef main():\n window = tkinter.Tk()\n window.title(\"Calculator\")\n\n # Calculator icons created by Freepik - Flaticon \n icon_image = tkinter.PhotoImage(file=\"images/calculate.png\")\n window.iconphoto(True, icon_image)\n\n global equation_display_label\n\n equation_display_label = tkinter.StringVar()\n\n display_label = tkinter.Label(\n master=window,\n fg='red',\n bg='black',\n font=('Arial', 30),\n width=13,\n textvariable=equation_display_label\n )\n display_label.pack(pady=5)\n\n frame = tkinter.Frame(master=window)\n frame.pack()\n\n left_parenthesis = tkinter.Button(master=frame, text=\"(\", command=lambda: button_press(\"(\"), width=10, height=3)\n left_parenthesis.grid(row=0, column=0)\n\n right_parenthesis = tkinter.Button(master=frame, text=\")\", command=lambda: button_press(\")\"), width=10, height=3)\n right_parenthesis.grid(row=0, column=1)\n\n clear_b = tkinter.Button(master=frame, text=\"clear\", command=clear, width=10, height=3)\n clear_b.grid(row=0, column=2)\n\n power = tkinter.Button(master=frame, text=\"^\", command=lambda: button_press(\"**\"), width=10, height=3)\n power.grid(row=0, column=3)\n\n button7 = tkinter.Button(master=frame, text=\"7\", command=lambda: button_press(\"7\"), width=10, height=3)\n button7.grid(row=1, column=0)\n\n button8 = tkinter.Button(master=frame, text=\"8\", command=lambda: button_press(\"8\"), width=10, height=3)\n button8.grid(row=1, column=1)\n\n button9 = tkinter.Button(master=frame, text=\"9\", command=lambda: button_press(\"9\"), width=10, height=3)\n button9.grid(row=1, column=2)\n\n multiply = tkinter.Button(master=frame, text=\"x\", command=lambda: button_press(\"*\"), width=10, height=3)\n multiply.grid(row=1, column=3)\n\n button4 = tkinter.Button(master=frame, text=\"4\", command=lambda: button_press(\"4\"), width=10, height=3)\n button4.grid(row=2, column=0)\n\n button5 = tkinter.Button(master=frame, text=\"5\", command=lambda: button_press(\"5\"), width=10, height=3)\n button5.grid(row=2, column=1)\n\n button6 = tkinter.Button(master=frame, text=\"6\", command=lambda: button_press(\"6\"), width=10, height=3)\n button6.grid(row=2, column=2)\n\n minus = tkinter.Button(master=frame, text=\"-\", command=lambda: button_press(\"-\"), width=10, height=3)\n minus.grid(row=2, column=3)\n\n button1 = tkinter.Button(master=frame, text=\"1\", command=lambda: button_press(\"1\"), width=10, height=3)\n button1.grid(row=3, column=0)\n\n button2 = tkinter.Button(master=frame, text=\"2\", command=lambda: button_press(\"2\"), width=10, height=3)\n button2.grid(row=3, column=1)\n\n button3 = tkinter.Button(master=frame, text=\"3\", command=lambda: button_press(\"3\"), width=10, height=3)\n button3.grid(row=3, column=2)\n\n plus = tkinter.Button(master=frame, text=\"+\", command=lambda: button_press(\"+\"), width=10, height=3)\n plus.grid(row=3, column=3)\n\n button0 = tkinter.Button(master=frame, text=\"0\", command=lambda: button_press(\"0\"), width=10, height=3)\n button0.grid(row=4, column=0)\n\n point = tkinter.Button(master=frame, text=\".\", command=lambda: button_press(\".\"), width=10, height=3)\n point.grid(row=4, column=1)\n\n equal_b = tkinter.Button(master=frame, text=\"=\", command=equal, width=10, height=3)\n equal_b.grid(row=4, column=2)\n\n division = tkinter.Button(master=frame, text=\"/\", command=lambda: button_press(\"/\"), width=10, height=3)\n division.grid(row=4, column=3)\n\n backspace_b = tkinter.Button(master=frame, text=\"delete\", command=backspace, width=44, height=3)\n backspace_b.grid(row=5, column=0, columnspan=4)\n\n window.mainloop()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Ntobeko-Themba-Malinga/Calculator","sub_path":"calculator/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4982,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"}
+{"seq_id":"30251335853","text":"\n# Miguel Brito Barbosa, Lucas de Oliveira Maia, Agnes Vithória Santos bakos 2° FID\n\ntotalampadas = float()\n\nwhile True:\n print(\"Quarto(1)\\n\"\n \"Sala de TV(2)\\n\"\n \"Salas(3)\\n\"\n \"Cozinha(4)\\n\"\n \"Varandas(5)\\n\"\n \"Escritório(6)\\n\"\n \"Banheiro(7)\")\n nome = int(input(\"Digite o número do cômodo desejado:\"))\n while nome < 1 or nome > 7:\n nome = int(input(\"Digite um cômodo válido!\\n\"))\n if nome == 1 or nome == 2:\n classe = 1\n elif nome == 3 or nome == 4 or nome == 5:\n classe = 2\n else:\n classe = 3\n\n largura = float(input(f\"Digite a largura do cômodo em metros:\"))\n while largura <= 0:\n largura = float(input(f\"Digite uma largura válida!\\n\"))\n\n comprimento = float(input(f\"Digite o comprimento do cômodo em metros:\"))\n while comprimento <= 0:\n comprimento = float(input(f\"Digite um comprimento válido\\n\"))\n\n area = largura * comprimento\n if classe == 1:\n potencia = area * 15\n elif classe == 2:\n potencia = area * 18\n else:\n potencia = area * 20\n lampadas = potencia/60\n aux = int(lampadas)\n if (lampadas - aux) != 0:\n aux += 1\n lampadas = aux\n totalampadas += lampadas\n totalwats = totalampadas * 60\n\n if nome == 1:\n print(f\"A área do quarto é {area:.1f}m², a potência por m² necessária é 15W,\"\n f\"para isso são necessárias {lampadas:.0f} lampadas\")\n elif nome == 2:\n print(f\"A área da sala de TV é {area:.1f}m², a potência por m² necessária é 15W,\"\n f\"para isso são necessárias {lampadas:.0f} lampadas\")\n elif nome == 3:\n print(f\"A área da sala é {area:.1f}m², a potência por m² necessária é 18W,\"\n f\"para isso são necessárias {lampadas:.0f} lampadas\")\n elif nome == 4:\n print(f\"A área da cozinha é {area:.1f}m², a potência por m² necessária é 18W,\"\n f\"para isso são necessárias {lampadas:.0f} lampadas\")\n elif nome == 5:\n print(f\"A área da varanda é {area:.1f}m², a potência por m² necessária é 18W,\"\n f\"para isso são necessárias {lampadas:.0f} lampadas\")\n elif nome == 6:\n print(f\"A área do escritório é {area:.1f}m², a potência por m² necessária é 20W,\"\n f\"para isso são necessárias {lampadas:.0f} lampadas\")\n else:\n print(f\"A área do banheiro é {area:.1f}m², a potência por m² necessária é 20W,\"\n f\"para isso são necessárias {lampadas:.0f} lampadas\")\n\n resp = input(\"Deseja adicionar mais cômodos S/N:\").upper()\n while resp != \"S\" and resp != \"N\":\n resp = input(\"Digite uma resposta válida!\\n\")\n if resp == \"N\":\n break\n\n\nvalor = float(input(\"Digite o valor das lampadas:\"))\nwhile valor <= 0:\n valor = float(input(\"Digite um valor válido!\\n\"))\n\nprint(f\"Para casa serão necessárais {totalampadas:.0f} lampadas\")\nprint(f\"O que dá um total de {totalwats:.0f} Watts\")","repo_name":"MiguelBritoBarbosa/Python-Projects","sub_path":"Projeto 1°Bimestre.py","file_name":"Projeto 1°Bimestre.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"15651368849","text":"\"\"\"\r\n@author : Sriram Veturi \r\n@title : Text Preprocessing Template\r\n\"\"\"\r\n\r\nimport os\r\nimport re\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.stem import PorterStemmer\r\n\r\n# Function traverse and get the text from files\r\ndef traversal(directory):\r\n\r\n # To store the text of files\r\n contents = list()\r\n\r\n for file in os.listdir(directory):\r\n with open(os.path.join(directory, file)) as f:\r\n c = f.read()\r\n contents = contents + c.split(' ')\r\n\r\n return contents\r\n\r\n\r\n# Function to preprocess the text\r\ndef preprocessText(contents, task = 1):\r\n\r\n # To store the corpus of words\r\n corpus = list()\r\n\r\n # Create corpus, remove special chars and lowercase operation.\r\n for content in contents:\r\n content = re.sub('[^A-Za-z0-9]+', '', content).lower()\r\n corpus.append(content)\r\n\r\n # This runs in the case where Stop Words are removed and Porter Stemmer is integrated.\r\n if task == 2:\r\n # Remove Stopwords before stemming\r\n corpus = [word for word in corpus if word not in stopWords]\r\n # Integrate Porter Stemmer\r\n corpus = [ps.stem(word) for word in corpus]\r\n # Remove Stopwords after stemming\r\n corpus = [word for word in corpus if word not in stopWords]\r\n\r\n corpus = [word for word in corpus if word != '']\r\n\r\n return corpus\r\n\r\n\r\n# Function to calculate the frequency of words\r\ndef frequencyCalculate(corpus):\r\n\r\n # Hash table to store word frequencies.\r\n frequencyHash = {}\r\n\r\n for word in corpus:\r\n if word not in frequencyHash:\r\n frequencyHash[word] = 1\r\n else:\r\n frequencyHash[word] += 1\r\n\r\n # Sort the words frequencies\r\n sortedHash = sorted(frequencyHash.items(), key=lambda x: x[1])[::-1]\r\n top20 = [word for word in sortedHash]\r\n\r\n # Stop words in top 20 words\r\n stop20 = [w[0] for w in top20[:20] if w[0] in stopWords]\r\n\r\n return frequencyHash, top20, stop20\r\n\r\n\r\n# Function to calculate the number of unique words accounting\r\n# for 15% of the total words in the corpus\r\ndef uniqueAccountingFifteenPercent(top, corpus):\r\n\r\n threshold = 0.15 * len(corpus)\r\n\r\n numUniqueWords = 0\r\n counter = 0\r\n\r\n for x in top:\r\n if counter >= threshold:\r\n break\r\n else:\r\n counter += x[1]\r\n numUniqueWords += 1\r\n\r\n return numUniqueWords\r\n\r\n\r\n# Case 1 : Without applying Stop Words removal and Integrating Porter Stemmer.\r\ndef taskOne(contents):\r\n\r\n corpus = preprocessText(contents)\r\n print(\"Total Number of words in the collection : \\n{}\\n\".format(len(corpus)))\r\n print(\"Vocabulary Size : \\n{}\\n\".format(len(set(corpus))))\r\n\r\n d, top, stop = frequencyCalculate(corpus)\r\n print(\"Top 20 highest frequency words : \\n{}\\n\".format(top[:20]))\r\n print(\"Stop Words in the top 20 highest frequency words : \\n{}\\n\".format(stop))\r\n print(\"Number of stop words in top 20 highest frequency words : \\n{}\\n\".format(len(stop)))\r\n\r\n numUniqueWords = uniqueAccountingFifteenPercent(top, corpus)\r\n print(\"Number of unique words accounting 15% of total words in corpus : \\n{}\\n\".format(numUniqueWords))\r\n\r\n\r\n# Case 2 : After applying Stop Words removal and Integrating Porter Stemmer.\r\ndef taskTwo(contents):\r\n corpus = preprocessText(contents, 2)\r\n print(\"Total Number of words in the collection : \\n{}\\n\".format(len(corpus)))\r\n print(\"Vocabulary Size : \\n{}\\n\".format(len(set(corpus))))\r\n\r\n d, top, stop = frequencyCalculate(corpus)\r\n print(\"Top 20 highest frequency words : \\n{}\\n\".format(top[:20]))\r\n print(\"Number of stop words in top 20 highest frequency words : \\n{}\\n\".format(len(stop)))\r\n\r\n numUniqueWords = uniqueAccountingFifteenPercent(top, corpus)\r\n print(\"Number of unique words accounting 15% of total words in corpus : \\n{}\\n\".format(numUniqueWords))\r\n\r\ndef initializations():\r\n\r\n # nltk.download()\r\n stopWords = set(stopwords.words(\"english\"))\r\n ps = PorterStemmer()\r\n directory = 'citeseer/citeseer'\r\n\r\n return stopWords, ps, directory\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n # Some initializations\r\n stopWords, ps, directory = initializations()\r\n\r\n # Traverse the directory to retrieve text\r\n contents = traversal(directory)\r\n\r\n # Processing the text\r\n print(\"Case 1 : Without applying Stop Words removal and Integrating Porter Stemmer!\\n\")\r\n taskOne(contents)\r\n print(\"Case 2 : After applying Stop Words removal and Integrating Porter Stemmer!\\n\")\r\n taskTwo(contents)\r\n","repo_name":"VETURISRIRAM/Machine-Learning","sub_path":"Text Preprocessing/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"16385012669","text":"import logging\nimport os\n\n\ndef getABI(abiName):\n currPath = os.path.dirname(os.path.abspath(__file__))\n abiFile = \"{}/{}.json\".format(currPath, abiName, abiName)\n try:\n with open(abiFile) as file_object:\n return file_object.read()\n except Exception as e:\n logging.error(\"getABI error:\", e)\n return None\n","repo_name":"calmw/risk_control","sub_path":"abi/abi.py","file_name":"abi.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"74708591928","text":"# https://www.codecademy.com/courses/learn-python-3/projects/python-magic-8-ball\nimport random\n\nname = \"Mohamed\"\nquestion = \"Will I win the lottery?\"\nanswer = \"\"\nrandom_number = random.randint(1, 10)\n\nif random_number == 1:\n answer = \"Yes - definitely.\"\nelif random_number == 2:\n answer = \"It is decidedly so.\"\nelif random_number == 3:\n answer = \"Without a doubt.\"\nelif random_number == 4:\n answer = \"Reply hazy, try again.\"\nelif random_number == 5:\n answer = \"Ask again later.\"\nelif random_number == 6:\n answer = \"Better not tell you now.\"\nelif random_number == 7:\n answer = \"My sources say no.\"\nelif random_number == 8:\n answer = \"Outlook not so good.\"\nelif random_number == 9:\n answer = \"Very doubtful.\"\nelif random_number == 10:\n answer = \"Signs point to yes\"\nelse:\n answer = \"Error\"\n\n# All these three does the same\n# if name: \n# if name != \"\": \n# if len(name) > 0: \n\nif name:\n if question:\n print(name + \" asks: \" + question)\n else:\n print(\"Dear \" + name + \" The Magic 8-Ball cannot provide a fortune unless you ask it something.\")\nelse:\n print(\"Question: \" + question)\n\nif name and question:\n print(\"Magic 8-Ball's answer: \" + answer)\nelse:\n print(\"No name no answer for exclusive members only!\")","repo_name":"CustomHaven/Magic-8-Ball","sub_path":"magic8.py","file_name":"magic8.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"26031637687","text":"# -*- coding: utf-8 -*-\n\n#!pip3 install rdflib\n#!pip3 install treelib\n\n# https://github.com/openeduhub/oeh-metadata-vocabs/blob/master/oehTopics.ttl\n\nimport re, rdflib, sys, json\nfrom treelib import Node, Tree\nfrom rdflib.namespace import RDF, SKOS\nfrom rdflib import URIRef\nimport nltk\n#nltk.download('stopwords')\nfrom nltk.corpus import stopwords\nSTOPWORDS = set(stopwords.words('german')).union(set(stopwords.words('english')))\n\n\nclass TopicAssistant:\n\n def normalize(self, s):\n s = re.sub('[^A-Za-z0-9öüäÖÄÜß]+', ' ', s)\n return s.lower()\n\n def __init__(self):\n\n # collect discipline labels\n self.disciplineLabels={}\n gdis = rdflib.Graph()\n result = gdis.parse(\"https://raw.githubusercontent.com/openeduhub/oeh-metadata-vocabs/master/discipline.ttl\", format=\"ttl\")\n for s, p, o in gdis.triples((None, SKOS.prefLabel, None)):\n try:\n self.disciplineLabels[s].append(str(o))\n except:\n self.disciplineLabels[s]=[str(o)]\n for s, p, o in gdis.triples((None, SKOS.altLabel, None)):\n try:\n self.disciplineLabels[s].append(str(o))\n except:\n self.disciplineLabels[s]=[str(o)]\n\n #print (self.disciplineLabels)\n\n # create an RDF graph fo rthe topics\n g = rdflib.Graph()\n\n result = g.parse(\"https://raw.githubusercontent.com/openeduhub/oeh-metadata-vocabs/master/oehTopics.ttl\", format=\"ttl\")\n #result = g.parse(\"oehTopics.ttl\", format=\"ttl\")\n\n # collect discipline mappings\n self.disciplineMappings={}\n for s, p, o in g.triples((None, SKOS.relatedMatch, None)):\n for s2, p2, o2 in g.triples((s, SKOS.topConceptOf, None)): \n self.disciplineMappings[s]=o\n\n\n # build the topic tree\n tree = Tree()\n #find top level node\n for s, p, o in g.triples((None, RDF.type, SKOS.ConceptScheme)):\n #print (s, p, o)\n tree.create_node(\"WLO\", s, data={'w':0, 'uri': s})\n for s2, p2, o2 in g.triples((s, SKOS.hasTopConcept, None)):\n #print (s2, p2, o2)\n tree.create_node(o2, o2, parent=s, data={'w':0, 'uri': str(o2)})\n \n foundSth = True\n while foundSth:\n foundSth = False\n for node in tree.all_nodes():\n n = URIRef(node.tag)\n for s, p, o in g.triples((None, SKOS.broader, n)):\n if not tree.contains(s):\n tree.create_node(s, s, parent=node, data={'w':0, 'uri': str(s)})\n foundSth = True\n\n # collect the labels\n for node in tree.all_nodes():\n for s, p, o in g.triples(( URIRef(node.identifier) , SKOS.prefLabel, None)):\n node.tag=o\n node.data['label']=o\n\n\n # collect the \"index terms\" from keywords, preflabels, and discipline labels\n keywords={}\n for s, p, o in g.triples((None, URIRef(\"https://schema.org/keywords\"), None)):\n #print (s, o)\n for k in str(o).split(','):\n n = self.normalize(k)\n if len(n)>2:\n try:\n keywords[s].append(n)\n except:\n keywords[s]=[n]\n\n for s, p, o in g.triples(( None , SKOS.prefLabel, None)):\n n = self.normalize(o)\n if len(n)>2:\n try:\n if not n in keywords[s]:\n keywords[s].append(n)\n except:\n keywords[s]=[n]\n\n if s in self.disciplineMappings.keys():\n disciplines = self.disciplineLabels[self.disciplineMappings[s]]\n for d in disciplines:\n n = self.normalize(d)\n try:\n if not n in keywords[s]:\n keywords[s].append(n)\n except:\n keywords[s]=[n]\n\n\n \n self.keywords = keywords\n self.tree = tree\n #for k in keywords.keys():\n # print(k, keywords[k])\n\n #tree.show(key=lambda node: node.data[\"w\"], reverse=True, idhidden=True) \n #sys.exit()\n\n def go(self, exampleText):\n T = Tree(self.tree, deep=True)\n\n t=[]\n for tok in self.normalize(exampleText).split(' '):\n if not tok in STOPWORDS:\n t.append(tok)\n ntext = \" \" + \" \".join(t) + \" \"\n #print (ntext)\n for c in self.keywords.keys():\n for k in self.keywords[c]:\n \n if ntext.find(\" \" + k + \" \")>-1 : \n T.get_node(c).data['w']=T.get_node(c).data['w']+1\n try:\n T.get_node(c).data['match']=T.get_node(c).data['match'] + \", \" + k \n except:\n T.get_node(c).data['match']=k \n #print (c, k)\n\n # propagate data to the root\n for d in range (T.depth(), -1, -1): \n #print (\"L\", d)\n # für jeden knoten:\n for node in T.all_nodes():\n if d == T.depth(node):\n # wenn er data =0 hat, ermittle data aus seinen kindern\n if node.data!=None and node.data['w'] > 0: \n\n p = T.parent(node.identifier)\n if p:\n p.data['w'] = p.data['w'] + node.data['w']\n\n for node in T.all_nodes(): \n #print (node, node.is_root())\n if node and not node.is_root() and node.data!=None and node.data['w'] == 0:\n #print (node.data, T.parent(node.identifier).data)\n if (T.contains(node.identifier)):\n T.remove_node(node.identifier)\n else:\n if node and not node.is_root() and node.data!=None:\n node.tag = node.tag + \" (\" + str(node.data['w']) + \")\"\n if 'match' in node.data.keys():\n node.tag = node.tag + \" [\" + node.data['match'] + \"]\"\n T.show(key=lambda node: node.data[\"w\"], reverse=True, idhidden=True) \n\n return T.to_dict(with_data=True, key=lambda node: node.data[\"w\"], sort=True, reverse=True)\n\nif __name__ == '__main__':\t\n\n\ttext = sys.argv[1]\n\ta = TopicAssistant()\n\tprint(json.dumps(a.go(text)))\n\n","repo_name":"yovisto/wlo-topic-assistant","sub_path":"src/topic_assistant.py","file_name":"topic_assistant.py","file_ext":"py","file_size_in_byte":6526,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"8769520447","text":"import Image\nimport ImageDraw\nimport ImageFont\n\nclass TexttoImage(object):\n\n def __init__(self, text, dest):\n self.__text = text\n self.__dest = dest\n \n def getSize(txt, font):\n testImg = Image.new('RGB', (1, 1))\n testDraw = ImageDraw.Draw(testImg)\n return testDraw.textsize(self.__text, font)\n\n def getImage():\n fontname = \"Arial.ttf\"\n fontsize = 11 \n text = self.__text\n\n colorText = \"black\"\n\n font = ImageFont.truetype(fontname, fontsize)\n width, height = getSize(text, font)\n img = Image.new('RGB', (width+4, height+4), colorBackground)\n d = ImageDraw.Draw(img)\n d.text((2, height/2), text, fill=colorText, font=font)\n d.rectangle((0, 0, width+3, height+3), outline=colorOutline)\n\n dest = self.__dest\n img.save(dest+\"/image.png\")\n","repo_name":"marriema/SugarSugar","sub_path":"TextToImage.py","file_name":"TextToImage.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"2653310369","text":"\"\"\"\nUnix Domain Socket Client \n\n\"\"\"\n\nimport socket\nimport sys\n\n# Create a UDS socket\nsock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n\n# Connect the socket to the port where the server is listening\nserver_address = \"/tmp/caroloIPC.uds\"\nprint >>sys.stderr, 'connecting to %s' % server_address\n\ntry:\n sock.connect(server_address)\nexcept socket.error as msg:\n print(sys.stderr, msg)\n sys.exit(1)\n \ntry:\n while True: \n data = sock.recv(64)\n print >>sys.stderr, 'received \"%s\"' % data\n if data: \n msg = input (\"Nachricht an Server eingeben: \")\n print >>sys.stderr, 'sending \"%s\"' % msg\n sock.sendall(msg)\n else:\n print >>sys.stderr, 'server gone, no more data'\t\n break \n \nfinally:\n print >>sys.stderr, 'closing socket'\n sock.close()\n","repo_name":"robertrslr/ba-cnn-steering","sub_path":"Code/unused/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"13983402189","text":"import pymongo\nimport requests\nimport numpy as np\nimport pandas as pd\nfrom splinter import Browser\nfrom bs4 import BeautifulSoup\n\ndef init_browser():\n executable_path = {'executable_path': 'chromedriver.exe'}\n return Browser('chrome', **executable_path, headless=False)\n\ndef scarpe():\n browser = init_browser()\n mars_dict = {}\n news_url = \"https://mars.nasa.gov/news/\"\n response = requests.get(news_url)\n # Create BeautifulSoup object; parse with 'html.parser'\n news_soup = BeautifulSoup(response.text, 'html.parser')\n # Examine the results, then determine element that contains sought info\n news_title = news_soup.title.text\n news_p = news_soup.p.text\n mars_dict[\"news_title\"] = news_title\n mars_dict[\"news_p\"] = news_p\n\n image_url = \"https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars\"\n response_img = requests.get(image_url)\n #response_img\n # Create BeautifulSoup object; parse with 'html.parser'\n # soup_image = BeautifulSoup(response_img.text, 'html.parser')\n # # Examine the results, then determine element that contains sought info\n # featured_img_url_nosplinter = soup_image.article[\"style\"]\n # # Parse string, e.g. '47 comments' for possible numeric manipulation\n # comments_num = featured_img_url_nosplinter.split()[1]\n # # Access the href attribute with bracket notation\n\n browser.visit(image_url)\n xpath = '//*[@id=\"page\"]/section[1]/div/div/article'\n xpath_search = browser.find_by_xpath(xpath)\n featured_img_url = xpath_search[\"style\"].split()[1]\n featured_img_url = featured_img_url.strip(\"url\")\n featured_img_url = featured_img_url.strip('(\"')\n featured_img_url = featured_img_url.strip('\");')\n featured_img_url = featured_img_url.strip('/')\n\n mars_dict[\"featured_img_url\"] = featured_img_url\n\n weather_url = \"https://twitter.com/marswxreport?lang=en\"\n weather_response = requests.get(weather_url)\n browser.visit(weather_url)\n mars_xpath = '//*[@id=\"stream-item-tweet-1041843517113475075\"]/div[1]/div[2]/div[2]/p'\n mars_weather = browser.find_by_xpath(mars_xpath).text\n\n # for p in mars_weather:\n # p = mars_weather.text\n # p\n weather_soup = BeautifulSoup(weather_response.text, \"html.parser\")\n weather_soup = weather_soup.find_all(\n \"p\", class_=\"TweetTextSize TweetTextSize--normal js-tweet-text tweet-text\")[0]\n mars_weather_soup = weather_soup.text\n mars_dict[\"mars_weather\"] = mars_weather_soup\n\n mars_facts_url = 'http://space-facts.com/mars/'\n mars_facts_tables = pd.read_html(mars_facts_url)[0]\n\n mars_facts_tables_html = mars_facts_tables.to_html()\n\n mars_facts_tables_html_clean = mars_facts_tables_html.replace('\\n', '')\n\n mars_dict[\"mars_facts\"] = mars_facts_tables_html_clean\n\n hemisphere_url = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'\n browser.visit(hemisphere_url)\n #browser.click_link_by_text(\"Cerberus Hemisphere Enhanced\")\n hemisphere_image_urls = []\n hemisphere_html = browser.html\n\n hemisphere_html_soup = BeautifulSoup(hemisphere_html, \"html.parser\")\n for i in range(len(hemisphere_html_soup.find_all(\"h3\"))):\n titles = browser.find_by_tag(\"h3\").text\n browser.find_by_tag(\"h3\")[i].click()\n xpath_hem = '//*[@id=\"wide-image\"]/div/ul/li[2]/a'\n link = browser.find_by_xpath(xpath_hem)[\"href\"]\n browser.back()\n hem_dict = {\"title\": titles, \"img_url\": link}\n hemisphere_image_urls.append(hem_dict)\n\n mars_dict[\"Mars_Hemisphere\"] = hemisphere_image_urls\n print(mars_dict)\n return mars_dict\nscarpe()","repo_name":"Abe17/Homework","sub_path":"scrape_mars.py","file_name":"scrape_mars.py","file_ext":"py","file_size_in_byte":3620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"41134042935","text":"\nimport cv2\nimport numpy as np\n\n\nimg = cv2.imread('haro.jpg')\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # convert here, don't use cv2.imgread('', )\ncircles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1,20, param1=50, param2=80, minRadius=0, maxRadius=200)\n#circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,20,param1=50,param2=100,minRadius=0,maxRadius=200)\n\nif circles is not None: # in case nothing find will return None to circles\n for i in circles[0,:]:\n cv2.circle(img,(i[0],i[1]),i[2],(0,0,255),2)\n\n\ncv2.imshow('detected circles', img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n","repo_name":"cheng0560011/circle-detection","sub_path":"findCircle_static.py","file_name":"findCircle_static.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"22659095921","text":"from flask import Flask, render_template, request\r\nimport pickle\r\nimport pandas\r\nimport numpy as np\r\n\r\nfinal_req = pandas.read_pickle(open('final.pkl','rb'))\r\nsim = pandas.read_pickle(open('distance.pkl','rb'))\r\n\r\n\r\napp=Flask(__name__)\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html', chaptername = list(final_req['ChapterName'].values),)\r\n\r\n@app.route('/recommend_chapters', methods=['get'])\r\ndef recommend():\r\n user_input = request.form.get('user_input')\r\n index=final_req[final_req['ChapterName']== user_input].index[0]\r\n distance = sim[index]\r\n chapters_list = sorted(list(enumerate(distance)),reverse = True, key=lambda x:x[1])[1:6]\r\n data = []\r\n for i in chapters_list:\r\n x = final_req.iloc[i[0]].ChapterName\r\n data.append(x)\r\n print(data)\r\n return render_template('index.html',data=data)\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=False)\r\n","repo_name":"vishnuthumpudi/web","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"11091504187","text":"from math import ceil\nimport sys\n\n\nclass ListForBinarySearch(object):\n def __init__(self, number_array):\n self.lst = number_array\n self.target = None\n self.max = sys.maxsize\n self.min = -sys.maxsize - 1\n \n def get_occurence_range_for(self, target):\n self.target = target\n min_index = self.find_index(0, len(self.lst) - 1, min, self.max)\n max_index = self.find_index(0, len(self.lst) - 1, max, self.min)\n\n return (min_index, max_index)\n\n def find_index(self, first, last, func, extreme):\n if self.lst[first] > self.target:\n return extreme\n if self.lst[last] < self.target:\n return extreme\n if last - first == 0: # this call checks if there is only one list element remaining\n return first if self.lst[first] == self.target else extreme # if the last element is target return index, otherwise return extreme\n\n sublist_length = last - first + 1\n middle_index = ceil(sublist_length / 2) - 1 + first\n\n return func(self.find_index(first, middle_index, func, extreme), self.find_index(middle_index + 1, last, func, extreme))\n","repo_name":"dacho17/100algorithms","sub_path":"005SortedArrayElementIndices/BinarySearch.py","file_name":"BinarySearch.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"39151768484","text":"from math import ceil, floor, sqrt\nimport copy\nfrom math import cos, sin, tan, atan2, asin\nfrom math import pi as PI\nimport numpy\n\n\ndef distance(pose1, pose2):\n \"\"\" compute Euclidean distance for 2D \"\"\"\n return sqrt((pose1[0] - pose2[0])**2 + (pose1[1] - pose2[1])**2) + 0.001\n\n\ndef RVO_update(X, V_des, V_current, ws_model):\n \"\"\" compute best velocity given the desired velocity, current velocity and workspace model\"\"\"\n ROB_RAD = ws_model['robot_radius'] + 0.01 # kan 0.1\n V_opt = list(V_current)\n for i in range(len(X)):\n vA = [V_current[i][0], V_current[i][1]] # = V_current[i]\n pA = [X[i][0], X[i][1]] # = X[i]\n RVO_BA_all = []\n for j in range(len(X)):\n if i != j:\n vB = [V_current[j][0], V_current[j][1]] # = V_current[j]\n pB = [X[j][0], X[j][1]] # = X[j]\n # use RVO\n # transl_vB_vA = [pA[0] + 0.5 * (vB[0] + vA[0]), pA[1] + 0.5 * (vB[1] + vA[1])] # RVO apex\n dist_BA = distance(pA, pB) # get distance between the 2 agents\n theta_BA = atan2(pB[1] - pA[1], pB[0] - pA[0]) # get angle of the distance line at pA\n\n if dist_BA < 2 * ROB_RAD:\n dist_BA = 2 * ROB_RAD # Minimum -> two agents\n\n theta_BAort = asin(2 * ROB_RAD / dist_BA)\n theta_ort_left = theta_BA + theta_BAort\n theta_ort_right = theta_BA - theta_BAort\n # Collision Cone\n bound_left = [cos(theta_ort_left), sin(theta_ort_left)]\n bound_right = [cos(theta_ort_right), sin(theta_ort_right)]\n # use HRVO\n dist_dif = distance([0.5 * (vB[0] - vA[0]), 0.5 * (vB[1] - vA[1])], [0, 0])\n transl_vB_vA = [pA[0] + vB[0] + cos(theta_ort_left) * dist_dif, pA[1] + vB[1] + sin(theta_ort_left) * dist_dif]\n RVO_BA = [transl_vB_vA, bound_left, bound_right, dist_BA, 2 * ROB_RAD]\n RVO_BA_all.append(RVO_BA)\n\n for hole in ws_model['circular_obstacles'] + ws_model['hazard']:\n\n vB = [0, 0]\n pB = hole[0:2]\n R = hole[2] # slice notation [0,1]\n transl_vB_vA = [pA[0] + vB[0], pA[1] + vB[1]]\n theta_BA = atan2(pB[1] - pA[1], pB[0] - pA[0])\n dist_BA = distance(pA, pB)\n rad = hole[2]\n if (rad + ROB_RAD) > dist_BA:\n dist_BA = rad + ROB_RAD\n if (rad + ROB_RAD) > dist_BA:\n dist_BA = rad + ROB_RAD\n theta_BAort = asin((rad + ROB_RAD) / dist_BA)\n theta_ort_left = theta_BA + theta_BAort\n bound_left = [cos(theta_ort_left), sin(theta_ort_left)]\n theta_ort_right = theta_BA - theta_BAort\n bound_right = [cos(theta_ort_right), sin(theta_ort_right)]\n RVO_BA = [transl_vB_vA, bound_left, bound_right, dist_BA, rad + ROB_RAD]\n RVO_BA_all.append(RVO_BA)\n\n vA_post = intersect(pA, V_des[i], RVO_BA_all)\n V_opt[i] = vA_post[:]\n return V_opt\n\n\ndef hazard_update(X, V_current, V_des, V_max, ws_model):\n\n # V_current here is V_opt passed from the RVO function in the same t\n\n #hazard = ws_model['hazard']\n V_opt = list(V_current)\n p_all = panics(X, V_max, ws_model)\n hazard = ws_model['hazard']\n paniced = []\n for i in range(len(X)):\n add = 0\n for j in range(len(hazard)):\n add += p_all[j][i]\n paniced.append(add)\n\n V_post = []\n\n for i in range(len(X)):\n\n if paniced[i] != 0: # 0.28\n add = [V_des[i][0] * 0.07, V_des[i][1] * 0.07] # f(x) of panic exponential at x = R\n for j in range(len(hazard)):\n\n dif_x = [X[i][k] - hazard[j][k] for k in range(2)]\n norm = distance(dif_x, [0, 0]) # hypotenuse\n new_v = [dif_x[k] / norm * p_all[j][i] for k in range(2)]\n\n add[0] = add[0] + new_v[0]\n add[1] = add[1] + new_v[1]\n\n # to normalize the magnitude to v_max again\n theta = atan2(add[1], add[0])\n v = [cos(theta) * V_max[i], sin(theta) * V_max[i]]\n\n V_post.append(v)\n\n if paniced[i] == 0:\n V_post.append(V_opt[i])\n\n return V_post\n\n\ndef panics(X, V_max, ws_model):\n\n # could 've change V_max for paniced agents in a new list.\n r = ws_model['robot_radius']\n hazard = ws_model['hazard']\n dists_all = []\n for h in hazard:\n R = h[2]\n dists = []\n for a in X:\n dist = distance(a, h)\n dists.append(dist)\n dists_all.append(dists)\n\n panics_all = []\n for i in range(len(hazard)):\n panics = []\n pVmax = []\n for d in dists_all[i]:\n if d < r * 2:\n p = 1.0\n elif d < R * 1.5:\n p = numpy.exp(-1.2 * (d / R)**2)\n else:\n p = 0.0\n panics.append(p)\n panics_all.append(panics)\n return panics_all\n\n\ndef intersect(pA, vA, RVO_BA_all):\n # print '----------------------------------------'\n # print 'Start intersection test'\n norm_v = distance(vA, [0, 0])\n suitable_V = []\n unsuitable_V = [] # Radar different V's in diferent Angles\n for theta in numpy.arange(0, 2 * PI, 0.1): # [0, 0.1, 0.2, ...2*PI]\n for rad in numpy.arange(0.02, norm_v + 0.02, norm_v / 10.0): # min rad = 0.02\n new_v = [rad * cos(theta), rad * sin(theta)] # rad-theta new composite [x, y]\n suit = True\n freebound = True\n dif_b = [new_v[0] + pA[0], new_v[1] + pA[1]]\n for RVO_BA in RVO_BA_all:\n p_0 = RVO_BA[0]\n left = RVO_BA[1]\n right = RVO_BA[2]\n # Starting the new_v from pA (robot A) then drawing a traingle to get the relative angle (Theta)\n dif = [new_v[0] + pA[0] - p_0[0], new_v[1] + pA[1] - p_0[1]]\n theta_dif = atan2(dif[1], dif[0])\n theta_right = atan2(right[1], right[0])\n theta_left = atan2(left[1], left[0])\n\n if dif_b[1] > 11:\n freebound = False\n if in_between(theta_right, theta_dif, theta_left):\n suit = False\n break\n\n if freebound and suit:\n suitable_V.append(new_v)\n elif freebound and not suit:\n unsuitable_V.append(new_v)\n\n # ***** Checking to Add the current Velocity also\n new_v = vA[:]\n suit = True\n freebound = True\n dif_b = [new_v[0] + pA[0], new_v[1] + pA[1]]\n for RVO_BA in RVO_BA_all:\n p_0 = RVO_BA[0]\n left = RVO_BA[1]\n right = RVO_BA[2]\n dif = [new_v[0] + pA[0] - p_0[0], new_v[1] + pA[1] - p_0[1]]\n theta_dif = atan2(dif[1], dif[0])\n theta_right = atan2(right[1], right[0])\n theta_left = atan2(left[1], left[0])\n\n if dif_b[1] > 11:\n freebound = False\n if in_between(theta_right, theta_dif, theta_left):\n suit = False\n break\n\n if freebound and suit:\n suitable_V.append(new_v)\n elif freebound and not suit:\n unsuitable_V.append(new_v)\n # ***** Checking to Add the current Velocity also\n\n if suitable_V:\n # print 'Suitable found'\n vA_post = min(suitable_V, key=lambda v: distance(v, vA))\n\n # ***** making sure (\n new_v = vA_post[:]\n for RVO_BA in RVO_BA_all:\n p_0 = RVO_BA[0]\n left = RVO_BA[1]\n right = RVO_BA[2]\n dif = [new_v[0] + pA[0] - p_0[0], new_v[1] + pA[1] - p_0[1]]\n theta_dif = atan2(dif[1], dif[0])\n theta_right = atan2(right[1], right[0])\n theta_left = atan2(left[1], left[0])\n # ***** making sure )\n\n else:\n # print 'Suitable not found'\n tc_V = dict()\n for unsuit_v in unsuitable_V:\n tc_V[tuple(unsuit_v)] = 0\n tc = []\n for RVO_BA in RVO_BA_all:\n p_0 = RVO_BA[0] # RVO or HRVO apex\n left = RVO_BA[1] # left & right bounds\n right = RVO_BA[2] # [x, y] one unit\n dist = RVO_BA[3]\n rad = RVO_BA[4]\n dif = [unsuit_v[0] + pA[0] - p_0[0], unsuit_v[1] + pA[1] - p_0[1]] # V from pA, tran. back\n theta_dif = atan2(dif[1], dif[0]) # its angle\n theta_right = atan2(right[1], right[0]) # angle of right cone\n theta_left = atan2(left[1], left[0]) # angle of left cone\n\n # choose inside RVO with after calculating Tc\n if in_between(theta_right, theta_dif, theta_left):\n small_theta = abs(theta_dif - 0.5 * (theta_left + theta_right))\n if rad <= abs(dist * sin(small_theta)): # to calculate on-touch\n rad = abs(dist * sin(small_theta))\n big_theta = asin(abs(dist * sin(small_theta)) / rad)\n dist_tc = abs(dist * cos(small_theta)) - abs(rad * cos(big_theta))\n if dist_tc < 0:\n dist_tc = 0\n tc_v = dist_tc / distance(dif, [0, 0])\n tc.append(tc_v)\n # approximate\n\n tc_V[tuple(unsuit_v)] = min(tc) + 0.001\n # Aggressiveness & time to collison\n WT = 0.2\n vA_post = min(unsuitable_V, key=lambda v: ((WT / tc_V[tuple(v)]) + distance(v, vA)))\n\n return vA_post\n\n\ndef in_between(theta_right, theta_dif, theta_left):\n if abs(theta_right - theta_left) <= PI:\n if theta_right <= theta_dif <= theta_left:\n return True\n else:\n return False\n else:\n if (theta_left < 0) and (theta_right > 0):\n theta_left += 2 * PI\n if theta_dif < 0:\n theta_dif += 2 * PI\n if theta_right <= theta_dif <= theta_left:\n return True\n else:\n return False\n if (theta_left > 0) and (theta_right < 0):\n theta_right += 2 * PI\n if theta_dif < 0:\n theta_dif += 2 * PI\n if theta_left <= theta_dif <= theta_right:\n return True\n else:\n return False\n\n\ndef compute_V_des(X, goal, V_max):\n V_des = []\n rch = []\n for i in range(len(X)):\n # Cos(theta) is already the ratio dif_x / norm. to escape the goal the subtraction is reversed.\n dif_x = [goal[i][k] - X[i][k] for k in range(2)] # New Velocity to reach goal in one-step\n norm = distance(dif_x, [0, 0]) # watar\n norm_dif_x = [dif_x[k] / norm * V_max[i] for k in range(2)]\n # to get there in one step V_max should = hypotenuse or distance or norm\n '''\n theta = atan2(goal[i][1] - X[i][1], goal[i][0] - X[i][0])\n norm_dif_x = [cos(theta) * V_max[i], sin(theta) * V_max[i]]\n '''\n V_des.append(norm_dif_x[:])\n if reach(X[i], goal[i]):\n V_des[i][0] = 0\n V_des[i][1] = 0\n rch.append(True)\n else:\n rch.append(False)\n\n return V_des, rch\n\n\ndef plan_paths(X, goal, exits):\n count_1 = 0\n count_2 = 0\n for i in range(len(goal)):\n if goal[i] == exits[0]:\n count_1 += 1\n\n else:\n count_2 += 1\n\n dense_exit = None\n lite_exit = None\n if count_1 > count_2:\n dense_exit = exits[0]\n lite_exit = exits[1]\n\n else:\n dense_exit = exits[1]\n lite_exit = exits[0]\n\n heading_to_dense = [i for i, e in enumerate(goal) if e == dense_exit]\n dist_from_dense = [distance(X[i], dense_exit) for i in heading_to_dense]\n # sorting dist and sync index with it\n dist_from_dense, heading_to_dense = (list(t) for t in zip(*sorted(zip(dist_from_dense, heading_to_dense), reverse=True)))\n for i in range(abs(count_1 - count_2) // 2):\n goal[heading_to_dense[i]] = lite_exit\n\n\ndef reach(p1, p2, bound=0.2):\n if distance(p1, p2) < bound:\n return True\n else:\n return False\n","repo_name":"muhammadayman/Hazard-HRVO","sub_path":"HRVO.py","file_name":"HRVO.py","file_ext":"py","file_size_in_byte":12736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"10841194352","text":"# Matthew Cournoyer and Harrison Hennessy\nimport tkinter as tk\n# from turtle import bgcolor\nimport csi280_codec\n\nm = tk.Tk()\n\n\ndef move_window(event):\n m.geometry('+{0}+{1}'.format(event.x_root, event.y_root))\n\n\n# Sets window color\nm.configure(bg='grey10')\n\n# creates cyphers to be used for encoding/decoding\nsubst_cypher = csi280_codec.SubstitutionCypher.new_cypher()\nrot13_cypher = csi280_codec.SubstitutionCypher.Rot13()\n\n\ndef click_encrypt_button():\n \"\"\"command for when encrypt button is clicked, checks selected algorithm\n and text entry and encrypts accordingly\n \"\"\"\n print(\"en_str: \" + text_entry.get(1.0, 'end-1c'))\n if selected_algorithm.get() == 'Substitution':\n encoded_text = subst_cypher.encode(text_entry.get(1.0, 'end-1c'))\n output_box.delete(1.0, 'end')\n output_box.insert(1.0, encoded_text)\n elif selected_algorithm.get() == 'Permutation':\n encoded_text = csi280_codec.PermutationCypher.encode(\n text_entry.get(1.0, 'end-1c'))\n output_box.delete(1.0, 'end')\n output_box.insert(1.0, encoded_text)\n elif selected_algorithm.get() == 'Caesar':\n caesar_cypher = csi280_codec.SubstitutionCypher.Caeser(\n int(key_entry.get(1.0, 'end-1c')))\n encoded_text = caesar_cypher.encode(text_entry.get(1.0, 'end-1c'))\n output_box.delete(1.0, 'end')\n output_box.insert(1.0, encoded_text)\n elif selected_algorithm.get() == 'Rot13':\n encoded_text = rot13_cypher.encode(text_entry.get(1.0, 'end-1c'))\n output_box.delete(1.0, 'end')\n output_box.insert(1.0, encoded_text)\n elif selected_algorithm.get() == 'None':\n output_box.delete(1.0, 'end')\n output_box.insert(1.0, text_entry.get(1.0, 'end-1c'))\n\n\ndef click_decrypt_button():\n \"\"\"command for when decrypt button is clicked, checks selected algorithm\n and text entry and decrypts accordingly\n \"\"\"\n print(\"de_str: \" + text_entry.get(1.0, 'end-1c'))\n if selected_algorithm.get() == 'Substitution':\n decoded_text = subst_cypher.decode(text_entry.get(1.0, 'end-1c'))\n output_box.delete(1.0, 'end')\n output_box.insert(1.0, decoded_text)\n elif selected_algorithm.get() == 'Permutation':\n decoded_text = csi280_codec.PermutationCypher.decode(\n text_entry.get(1.0, 'end-1c'))\n output_box.delete(1.0, 'end')\n output_box.insert(1.0, decoded_text)\n elif selected_algorithm.get() == 'Caesar':\n caesar_cypher = csi280_codec.SubstitutionCypher.Caeser(\n int(key_entry.get(1.0, 'end-1c')))\n decoded_text = caesar_cypher.decode(text_entry.get(1.0, 'end'))\n output_box.delete(1.0, 'end')\n output_box.insert(1.0, decoded_text)\n elif selected_algorithm.get() == 'Rot13':\n decoded_text = rot13_cypher.decode(text_entry.get(1.0, 'end-1c'))\n output_box.delete(1.0, 'end')\n output_box.insert(1.0, decoded_text)\n elif selected_algorithm.get() == 'None':\n output_box.delete(1.0, 'end')\n output_box.insert(1.0, text_entry.get(1.0, 'end-1c'))\n\n\n# top bar set up\ntop_bar = tk.Frame(m, bg='grey10', relief='raised', bd=2)\ntop_bar_title = tk.Label(top_bar, text='Encryption/Decryption GUI',\n font=('courier', 10), bg='grey10', fg='grey80')\nclose_button = tk.Button(top_bar, text=\"X\", bg='grey15',\n fg='grey80', command=m.destroy)\n\n# creates main window\nmain_window = tk.Canvas(m, bg='grey10')\n\n# Selection box for user to select encryption algorithm\nalgorithm_selector_label = tk.Label(main_window, text='Select Algorithm: ',\n font=('courier', 8),\n bg='grey10', fg='grey80')\nalgorithm_selector_label.grid(row=1, column=0, columnspan=1, padx=10, pady=10)\n\nalgorithms = ['Substitution', 'Permutation (WIP)', 'Caesar', 'Rot13', 'None']\nselected_algorithm = tk.StringVar(m)\nselected_algorithm.set('Substitution')\nselection_box = tk.OptionMenu(main_window, selected_algorithm, *algorithms)\nselection_box.config(bg='grey15', fg='grey80', font=('courier', 8))\nselection_box_menu = main_window.nametowidget(selection_box.menuname)\nselection_box_menu.config(font=('courier', 8))\nselection_box.grid(row=1, column=1, columnspan=3, padx=10, pady=10)\n\n# Text and key entry fields\ntext_entry_label = tk.Label(main_window, text='Enter Text: ',\n bg='grey10', fg='grey80', font=('courier', 8))\ntext_entry_label.grid(row=2, column=0, columnspan=1, padx=5, pady=5)\n\ntext_entry = tk.Text(main_window, height=1, width=20, font=(\n 'courier', 8), bg='grey15', fg='grey80')\ntext_entry.grid(row=2, column=1, padx=5, pady=5)\n\nkey_entry_label = tk.Label(main_window, text='Key: ',\n bg='grey10', fg='grey80', font=('courier', 8))\nkey_entry_label.grid(row=2, column=2, columnspan=1, padx=5, pady=5)\n\nkey_entry = tk.Text(main_window, height=1, width=5, bg='grey15',\n fg='grey80', font=('courier', 8))\nkey_entry.grid(row=2, column=3, padx=5, pady=5)\n\n# Encrypt and Decrypt Buttons\nencrypt_button = tk.Button(main_window, text='Encrypt',\n command=click_encrypt_button,\n bg='grey15', fg='grey80', font=('courier', 8))\nencrypt_button.grid(row=3, column=1, padx=10, pady=10)\n\ndecrypt_button = tk.Button(main_window, text='Decrypt',\n command=click_decrypt_button,\n bg='grey15', fg='grey80', font=('courier', 8))\ndecrypt_button.grid(row=3, column=2, padx=10, pady=10)\n\n# Output Label and Box\noutput_label = tk.Label(main_window, text=\"Output: \",\n bg='grey10', fg='grey80', font=('courier', 8))\noutput_label.grid(row=4, column=0, padx=10, pady=10)\n\noutput_box = tk.Text(main_window, height=1, width=40,\n bg='grey15', fg='grey80', font=('courier', 8))\noutput_box.grid(row=4, column=1, columnspan=2, padx=10, pady=10)\n\n# Sets window geometry and title bar\nm.overrideredirect(True)\nm.geometry('550x210')\ntop_bar.pack(expand=1, fill=tk.X)\ntop_bar_title.pack(side=tk.LEFT)\nclose_button.pack(side=tk.RIGHT)\nmain_window.pack(expand=1, fill=tk.BOTH)\ntop_bar_title.bind('', move_window)\ntop_bar.bind('', move_window)\n\n# runs GUI\nm.mainloop()\n","repo_name":"Amor-Amor/CSI-281-encryption-decryption-software","sub_path":"frontend.py","file_name":"frontend.py","file_ext":"py","file_size_in_byte":6285,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"73348060409","text":"from django.urls import path\nfrom .views import (FAQView, FAQListView, AssistanceView, AssistanceCreateView,AssistanceListView, \n AssistanceUpdateView, FeedbackView)\n\napp_name=\"support\"\n\nurlpatterns = [\n \n path('faq/', FAQView.as_view(), name=\"faq\"),\n path('faq_list/', FAQListView.as_view(), name=\"faq_list\"),\n path('assistance/', AssistanceView.as_view(), name=\"assistance\"),\n path('assistance_list/', AssistanceListView.as_view(), name=\"assistance_list\"),\n path('assistance_create/', AssistanceCreateView.as_view(), name=\"assistance_create\"),\n path('assistance_update/', AssistanceUpdateView.as_view(), name=\"assistance_update\"),\n path('feedback/', FeedbackView.as_view(), name=\"feedback\"),#AJAX\n \n ]","repo_name":"gab98fra/curriculo.page-project","sub_path":"app/support/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"74970134327","text":"import time\nimport board\nimport digitalio\nimport supervisor\nfrom ledTask import toggle_leds,setup_leds\nfrom AD5391Task import AD5391\nfrom sine_wave_generator import SineWaveGenerator\nfrom square_wave_generator import SquareWaveGenerator\n# Set up the GPIO pins for the LEDs\n\n\nsetup_leds()\n\n# Initialize AD5391\nad5391 = AD5391()\n# Write DAC RAW Function (To Try and Activate the Internal Reference by setting the control register)\n# Writing Control Register\n# REG1=REG0=0\n# A3-A0 = 1100\n# DB13-DB0 Contains CR13 - CR0\n# This Setup gives the following\n# A/~B = 0\n# R/~W = 0\n# 00 (Always 0)\n# A3-A0 = 1100 (Control Register)\n# REG1-REG0 = 00 (Special Functions)\n# DB13 - DB12 = Doesn't apply to AD5391\n# CR11 = 1 Power Down Status. Configures the Amplifier Behavior in Power Down\n# CR10 = 0 REF Select (Sets the Internal Reference 1/2,5V 0/1.25V)\n# CR9 = 1 Current Boost Control (1 Maximizes the bias current to the output amplifier while in increasing power consumption)\n# CR8 = 1 Internal / External Reference (1 Uses Internal Reference)\n# CR7 = 1 Enable Channel Monitor Function (1 allows channels to be routed to the output)\n# CR6 = 0 Enable Thermal Monitor Function\n# CR5-CR2 = Don't CARE\n# CR1-CR0 = Toggle Function Enable\n\nsine_gen = SineWaveGenerator(channel=1, period=1, amplitude=4095, dac=ad5391)\nsquare_gen = SquareWaveGenerator(channel=0, period=1, amplitude=4095, dac=ad5391)\n\ndef process_command(command):\n if command == \"info\":\n response = \"This is a Basic 16 Channel Arbitrary Waveform Generator v0.01\"\n elif command == \"read_mon_out\":\n mon_out_value = ad5391.read_mon_out()\n response = f\"MON_OUT value: {mon_out_value}\"\n elif command == \"read_mon_out_voltage\":\n mon_out_voltage = ad5391.read_mon_out_voltage()\n response = f\"MON_OUT voltage: {mon_out_voltage:.4f} V\"\n elif command == \"read_busy_pin\":\n busy_state = ad5391.read_busy_pin()\n response = f\"BUSY pin state (False Means Busy): {busy_state}\"\n else:\n cmd_parts = command.split(' ')\n if cmd_parts[0] == \"set_ldac_pin\":\n if len(cmd_parts) != 2:\n response = \"Usage: set_ldac_pin [True|False]\"\n else:\n state = cmd_parts[1].lower() == \"true\"\n ad5391.set_ldac_pin(state)\n response = f\"LDAC pin state set to: {state}\"\n elif cmd_parts[0] == \"write_dac\":\n if len(cmd_parts) < 3:\n response = \"Usage: write_dac channel value [toggle_mode] [ab_select] [reg_select]\"\n else:\n channel = int(cmd_parts[1])\n value = int(cmd_parts[2])\n toggle_mode = cmd_parts[3].lower() == \"true\" if len(cmd_parts) > 3 else False\n ab_select = cmd_parts[4].lower() == \"true\" if len(cmd_parts) > 4 else False\n reg_select = int(cmd_parts[5]) if len(cmd_parts) > 5 else 0\n\n ad5391.write_dac(channel, value, toggle_mode, ab_select, reg_select)\n response = f\"Value {value} written to channel {channel} with toggle_mode={toggle_mode}, ab_select={ab_select}, reg_select={reg_select}\"\n else:\n response = \"Unknown command\"\n\n return response\n\n\nad5391.monitor_channel(0)\n\nnext_toggle = time.monotonic() + 1\n\nwhile True:\n now = time.monotonic()\n if now >= next_toggle:\n toggle_leds()\n next_toggle = now + 0.05\n control_register_value = ad5391.read_register(0b0001, 0b11)\n ad5391.write_dac_raw(0b0_0_00_1100_00_101111_0000_00_00)\n print(((control_register_value & 0x003FFF)>>2,))\n sine_gen.progress()\n square_gen.progress()\n\n\n if supervisor.runtime.serial_bytes_available:\n command = input().strip()\n response = process_command(command)\n print(response)\n","repo_name":"devinatkin/picoAWG","sub_path":"RP2040_Code/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":3778,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"}
+{"seq_id":"12324971410","text":"import sys\nimport os\nimport shutil\n\nsys.path.append( '../pymod' )\nsys.path.append( '../gcore' )\n\nfrom osgeo import gdal\nimport gdaltest\nimport test_cli_utilities\nimport tiff_ovr\n\n###############################################################################\n# Similar to tiff_ovr_1\n\ndef test_gdaladdo_1():\n if test_cli_utilities.get_gdaladdo_path() is None:\n return 'skip'\n\n shutil.copy('../gcore/data/mfloat32.vrt', 'tmp/mfloat32.vrt')\n shutil.copy('../gcore/data/float32.tif', 'tmp/float32.tif')\n\n (out, err) = gdaltest.runexternal_out_and_err(test_cli_utilities.get_gdaladdo_path() + ' tmp/mfloat32.vrt 2 4')\n if not (err is None or err == '') :\n gdaltest.post_reason('got error/warning')\n print(err)\n return 'fail'\n\n ds = gdal.Open('tmp/mfloat32.vrt')\n ret = tiff_ovr.tiff_ovr_check(ds)\n ds = None\n\n os.remove('tmp/mfloat32.vrt')\n os.remove('tmp/mfloat32.vrt.ovr')\n os.remove('tmp/float32.tif')\n\n return ret\n\n\n###############################################################################\n# Test -r average. Similar to tiff_ovr_5\n\ndef test_gdaladdo_2():\n if test_cli_utilities.get_gdaladdo_path() is None:\n return 'skip'\n\n shutil.copyfile( '../gcore/data/nodata_byte.tif', 'tmp/ovr5.tif' )\n\n gdaltest.runexternal(test_cli_utilities.get_gdaladdo_path() + ' -r average tmp/ovr5.tif 2')\n\n ds = gdal.Open('tmp/ovr5.tif')\n cs = ds.GetRasterBand(1).GetOverview(0).Checksum()\n exp_cs = 1130\n\n if cs != exp_cs:\n gdaltest.post_reason( 'got wrong overview checksum.' )\n print(exp_cs, cs)\n return 'fail'\n\n ds = None\n\n os.remove('tmp/ovr5.tif')\n\n return 'success'\n\n###############################################################################\n# Test -ro\n\ndef test_gdaladdo_3():\n if test_cli_utilities.get_gdaladdo_path() is None:\n return 'skip'\n\n shutil.copyfile( '../gcore/data/nodata_byte.tif', 'tmp/test_gdaladdo_3.tif' )\n\n gdaltest.runexternal(test_cli_utilities.get_gdaladdo_path() + ' -ro tmp/test_gdaladdo_3.tif 2')\n\n ds = gdal.Open('tmp/test_gdaladdo_3.tif')\n cs = ds.GetRasterBand(1).GetOverview(0).Checksum()\n exp_cs = 1152\n\n if cs != exp_cs:\n gdaltest.post_reason( 'got wrong overview checksum.' )\n print(exp_cs, cs)\n return 'fail'\n\n ds = None\n\n try:\n os.stat('tmp/test_gdaladdo_3.tif.ovr')\n except:\n gdaltest.post_reason( 'no external overview.' )\n return 'fail'\n\n return 'success'\n\n###############################################################################\n# Test -clean\n\ndef test_gdaladdo_4():\n if test_cli_utilities.get_gdaladdo_path() is None:\n return 'skip'\n\n gdaltest.runexternal(test_cli_utilities.get_gdaladdo_path() + ' -clean tmp/test_gdaladdo_3.tif')\n\n ds = gdal.Open('tmp/test_gdaladdo_3.tif')\n cnt = ds.GetRasterBand(1).GetOverviewCount()\n ds = None\n\n if cnt != 0:\n gdaltest.post_reason( 'did not clean overviews.' )\n return 'fail'\n\n try:\n os.stat('tmp/test_gdaladdo_3.tif.ovr')\n gdaltest.post_reason( '.ovr file still exists' )\n return 'fail'\n except:\n pass\n\n os.remove('tmp/test_gdaladdo_3.tif')\n\n return 'success'\n\ngdaltest_list = [\n test_gdaladdo_1,\n test_gdaladdo_2,\n test_gdaladdo_3,\n test_gdaladdo_4\n ]\n\n\nif __name__ == '__main__':\n\n gdaltest.setup_run( 'test_gdaladdo' )\n\n gdaltest.run_tests( gdaltest_list )\n\n gdaltest.summarize()\n\n\n\n\n\n","repo_name":"ryandavid/rotobox","sub_path":"3rd_party/gdal/autotest/utilities/test_gdaladdo.py","file_name":"test_gdaladdo.py","file_ext":"py","file_size_in_byte":3478,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"77"}
+{"seq_id":"43480850045","text":"import datamodel\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom datetime import datetime, timedelta\n\nengine = create_engine('sqlite:///C:\\\\Users\\\\Simon\\\\OneDrive\\\\Dokumente\\\\4AHIT\\\\SEW INSY\\\\WorkTimeTracker\\\\application\\\\app_db.sql')\nSession = sessionmaker(bind=engine)\nsession = Session()\n\n\nclass Database_Manager:\n def create_user(session, user_name):\n new_user = datamodel.Users(userName=user_name)\n session.add(new_user)\n session.commit()\n return new_user\n\n def create_time(session, start_value, stop_value, user_id):\n new_time = datamodel.Times(startValue=start_value, stopValue=stop_value, userID=user_id)\n session.add(new_time)\n session.commit()\n return new_time\n\n def read_user(session, user_id):\n return session.query(datamodel.Users).filter_by(userID=user_id).first()\n\n def read_times(session, user_id):\n return session.query(datamodel.Times).filter_by(userID=user_id).all()\n\n def update_user(session, user_id, user_name):\n user = session.query(datamodel.Users).filter_by(userID=user_id).first()\n user.userName = user_name\n session.commit()\n return user\n\n def update_time(session, time_id, start_value, stop_value, user_id):\n time = session.query(datamodel.Times).filter_by(timeID=time_id).first()\n time.startValue = start_value\n time.stopValue = stop_value\n time.userID = user_id\n session.commit()\n return time\n\n def delete_user(session, user_id):\n user = session.query(datamodel.Users).filter_by(userID=user_id).first()\n session.delete(user)\n session.commit()\n\n def delete_time(session, time_id):\n time = session.query(datamodel.Times).filter_by(timeID=time_id).first()\n session.delete(time)\n session.commit()\n\n def get_all_users(session):\n all_users = session.query(datamodel.Users).all()\n return all_users\n\n def get_last_time_id(session):\n last_time = session.query(datamodel.Times).order_by(datamodel.Times.timeID.desc()).first()\n if last_time:\n return last_time.timeID\n else:\n return 1\n\n def get_sum_of_year(session, user_id):\n year = datetime.now().year\n times = session.query(datamodel.Times).filter(datamodel.Times.userID == user_id).all()\n sum = timedelta()\n for time in times:\n if time.startValue.year == year:\n sum += (time.stopValue - time.startValue)\n return sum.total_seconds() / 3600\n\n def get_sum_of_month(session, user_id):\n year = datetime.now().year\n month = datetime.now().month\n times = session.query(datamodel.Times).filter(datamodel.Times.userID == user_id).all()\n sum = timedelta()\n for time in times:\n if time.startValue.year == year and time.startValue.month == month:\n sum += (time.stopValue - time.startValue)\n return sum.total_seconds() / 3600\n\n def get_sum_of_week(session, user_id):\n today = datetime.now().date()\n week_start = today - timedelta(days=today.weekday())\n week_end = week_start + timedelta(days=6)\n times = session.query(datamodel.Times).filter(datamodel.Times.userID == user_id).all()\n sum = timedelta()\n for time in times:\n if week_start <= time.startValue.date() <= week_end:\n sum += (time.stopValue - time.startValue)\n return sum.total_seconds() / 3600\n\n\nif __name__ == \"__main__\":\n dm = Database_Manager\n","repo_name":"schaff190163/WorkTimeTracker","sub_path":"application/database_manager.py","file_name":"database_manager.py","file_ext":"py","file_size_in_byte":3584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"725199076","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 10 13:34:58 2020\n\n@author: Administrator\n\"\"\"\n\n#TempConvert.py\nTempStr = input('请输入带有符号的温度值,如100C或者212F,这里输入:')\nif TempStr[-1] not in ['F','f','C','c']:\n print('输入格式错误,请重新输入')\nelse:\n if TempStr[-1] in ['F','f']:\n C = (eval(TempStr[:-1]) - 32)/1.8\n print('转换后的温度是{:.2f}C'.format(C))\n elif TempStr[-1] in ['C','c']:\n C = 1.8*eval(TempStr[:-1]) + 32\n print('转换后的温度是{:.2f}F'.format(C))\n","repo_name":"yukaixue/spyder","sub_path":"TempConvert.py","file_name":"TempConvert.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"15402377135","text":"# -*- coding:utf-8 -*-\n\ndef format_result(result, text, tag): \n entities = [] \n for i in result: \n begin, end = i \n entities.append({ \n \"start\":begin, \n \"stop\":end + 1, \n \"word\":text[begin:end+1],\n \"type\":tag\n }) \n return entities\n\ndef get_tags(path, tag, tag_map):\n begin_tag = tag_map.get(\"B_\" + tag)\n mid_tag = tag_map.get(\"I_\" + tag)\n tags = []\n\n for index_1 in range(len(path)):\n if path[index_1] == begin_tag:\n ner_index = 0\n for index_2 in range(index_1 + 1, len(path)):\n if path[index_2] == mid_tag:\n ner_index += 1\n else:\n break\n if ner_index != 0:\n tags.append([index_1, index_1 + ner_index])\n return tags\n\ndef f1_score(tar_path, pre_path, tag, tag_map):\n '''\n :param tar_path: real tag\n :param pre_path: predict tag\n :param tag: [ORG, PER, LOC, T]\n :param tag_map: { 'B_T': 0,\n 'I_T': 1,\n 'B_LOC': 2,\n 'I_LOC': 3,\n 'B_ORG': 4,\n 'I_ORG': 5,\n 'B_PER': 6,\n 'I_PER': 7,\n 'O': 8}\n :return:\n '''\n origin = 0.\n found = 0.\n right = 0.\n for fetch in zip(tar_path, pre_path):\n tar, pre = fetch\n tar_tags = get_tags(tar, tag, tag_map)\n pre_tags = get_tags(pre, tag, tag_map)\n\n origin += len(tar_tags)\n found += len(pre_tags)\n\n for p_tag in pre_tags:\n if p_tag in tar_tags:\n right += 1\n\n recall = 0. if origin == 0 else (right / origin)\n precision = 0. if found == 0 else (right / found)\n f1 = 0. if recall+precision == 0 else (2*precision*recall)/(precision + recall)\n print(\"\\t{}\\trecall {:.2f}\\tprecision {:.2f}\\tf1 {:.2f}\".format(tag, recall, precision, f1))\n return recall, precision, f1\n","repo_name":"jiangnanboy/albert_lstm_crf_ner","sub_path":"src/lstm_crf/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","stars":122,"dataset":"github-code","pt":"77"}
+{"seq_id":"25954429423","text":"def gerador_cpf(cpf):\n # Retira os 2 ultimos digitos do cpf\n cpf_teste01 = cpf[:-2]\n range_01 = 11\n soma_01 = 0\n\n for x in cpf_teste01:\n range_01 -= 1\n resultado_01 = int(x) * range_01\n soma_01 += resultado_01\n\n formula_01 = 11 - (soma_01 % 11)\n\n if formula_01 <= 9:\n digito_1 = str(formula_01)\n else:\n digito_1 = '0'\n\n cpf_teste02 = cpf_teste01 + digito_1\n range_02 = 12\n soma_02 = 0\n\n for y in cpf_teste02:\n range_02 -= 1\n resultado_02 = int(y)*range_02\n soma_02 += resultado_02\n\n formula_02 = 11 - (soma_02 % 11)\n\n if formula_02 <= 9:\n digito_2 = str(formula_02)\n else:\n digito_2 = '0'\n\n cpf_valido = cpf_teste02 + digito_2\n return cpf_valido\n","repo_name":"Code-gutemberg/Gerador_Validador_CPF","sub_path":"gerador.py","file_name":"gerador.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"73050946810","text":"from django.shortcuts import render\n\nfrom userAuth.models import User, userInfo\nfrom userAuth import models\nfrom .models import notice\n\nfrom .forms import addNotice, editNotice as editNotices\nfrom userAuth.forms import userformMoreinfo, userform\n\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.urls import reverse\n\n\n\n@login_required\ndef dashboardMainView(request):\n\n\n dict = {}\n\n if request.user.is_authenticated:\n\n currentUser = request.user\n\n dict.update({'myInfo' : currentUser})\n currentUserMoreInfo = userInfo.objects.get(user__pk = currentUser.id)\n dict.update({'myMoreInfo': currentUserMoreInfo})\n\n notices = notice.objects.filter(user=currentUserMoreInfo)\n dict.update({'notices': notices})\n\n\n if (currentUserMoreInfo.role == \"1\" or currentUserMoreInfo.role == \"2\"):\n\n notices = notice.objects.all()\n\n dict.update({'notices': notices})\n dict.update({\"noticeController\": True})\n\n\n if (currentUserMoreInfo.role == \"1\" or currentUserMoreInfo.role == \"2\" or currentUserMoreInfo.role == '3'):\n dict.update({\"employeeController\": True})\n \n \n if (currentUserMoreInfo.role == \"1\" or currentUserMoreInfo.role == \"4\"):\n dict.update({\"finaceController\": True})\n\n \n\n return render(request, 'dashboard/index.html', context=dict)\n\n\n\n\n\n@login_required\ndef editProfile(request, id):\n\n currentUser = request.user\n currentUserMoreInfo = models.userInfo.objects.get(user__pk = currentUser.id)\n currentRole = currentUserMoreInfo.role\n\n userForm = userform(instance=currentUser)\n userForm2 = userformMoreinfo(instance=currentUserMoreInfo)\n\n dict = {'userform': userForm, 'userform2': userForm2, 'alertMessage': \"Login back after changing personal data.\"}\n\n if (currentUserMoreInfo.role == \"1\" or currentUserMoreInfo.role == \"2\" or currentUserMoreInfo.role == \"3\" ):\n dict.update({\"employeeController\": True})\n\n if (currentUserMoreInfo.role == \"1\" or currentUserMoreInfo.role == \"4\" ):\n dict.update({\"finaceController\": True})\n \n if (currentUserMoreInfo.role == \"1\"):\n dict.update({\"fullEmployeeControler\": True})\n\n \n\n if (currentRole == '1') or (currentRole == '3'):\n currentUser = User.objects.get(pk=id)\n currentUserMoreInfo = models.userInfo.objects.get(user__pk = currentUser.id)\n currentRole = currentUserMoreInfo.role\n userForm = userform(instance=currentUser)\n userForm2 = userformMoreinfo(instance=currentUserMoreInfo)\n dict.update({\"changeRole\": True})\n dict.update({'userform': userForm})\n dict.update({'userform2': userForm2})\n\n\n if request.method == 'POST':\n\n userForm = userform(request.POST, instance=currentUser)\n userForm2 = userformMoreinfo(request.POST, instance=currentUserMoreInfo)\n\n if userForm.is_valid() and userForm2.is_valid():\n\n changedrole = userForm2.cleaned_data['role']\n\n requestUser = request.user\n requestUserMoreInfo = models.userInfo.objects.get(user__pk = requestUser.id)\n requestUserRole = requestUserMoreInfo.role\n\n if (changedrole != currentRole) and (requestUserRole != '1'):\n dict={'showMessage': True,'message': \"You can not change role\"}\n return render(request, 'showMessage.html', context=dict)\n \n \n user = userForm.save()\n user.set_password(user.password)\n user.save()\n\n userInfo = userForm2.save(commit=False)\n userInfo.user = user\n\n if 'proPic' in request.FILES:\n userInfo.proPic = request.FILES['proPic']\n\n userInfo.save()\n\n\n if user.id == requestUser.id:\n return HttpResponseRedirect(reverse('userAuth:loginApp'))\n \n \n dict={'showMessage': True,'message': \"Successfully Updated\" }\n return render(request, 'showMessage.html', context=dict)\n \n dict={'showMessage': True,'message': \"Invalid Submission.\"}\n return render(request, 'showMessage.html', context=dict)\n\n\n return render(request, 'authentication/editUser.html', context=dict)\n\n\n\n\n\n@login_required\ndef createNotice(request):\n\n dict = {'btnText': \"Add Notice\"}\n\n currentUser = request.user\n currentUserMoreInfo = userInfo.objects.get(user__pk = currentUser.id)\n\n if (currentUserMoreInfo.role == \"1\") or (currentUserMoreInfo.role == \"2\"):\n \n createNotice = addNotice\n dict.update({\"createNotice\": createNotice})\n\n dict.update({\"employeeController\": True})\n \n if (currentUserMoreInfo.role == \"1\"):\n dict.update({\"finaceController\": True})\n\n if request.method == \"POST\":\n\n noticeForm = addNotice(data=request.POST)\n\n if noticeForm.is_valid():\n noticeForm.save()\n dict.update({'message': \"Notice added successfully\"})\n return render(request, 'showMessage.html', context=dict)\n else:\n noticeForm = addNotice(request.POST)\n dict.update({\"createNotice\": noticeForm})\n\n return HttpResponseRedirect(reverse('dashboard:dashboard'))\n\n dict.update({'check': True})\n return render(request, 'notices/createNotice.html', context=dict)\n \n\n dict.update({'message': \"You do not have the authority to make a notice\"})\n return render(request, 'showMessage.html', context=dict)\n\n\n\n\n@login_required\ndef editNotice(request, id):\n\n dict = {'btnText': \"Edit Notice\"}\n\n currentUser = request.user\n currentUserMoreInfo = userInfo.objects.get(user__pk = currentUser.id)\n\n\n if (currentUserMoreInfo.role == \"1\") or (currentUserMoreInfo.role == \"2\"):\n \n getNotice = notice.objects.get(pk=id)\n noticeForm = editNotices(instance=getNotice)\n dict.update({\"createNotice\": noticeForm})\n\n users = models.User.objects.all()\n dict.update({\"users\": users})\n\n dict.update({\"employeeController\": True})\n \n if (currentUserMoreInfo.role == \"1\"):\n dict.update({\"finaceController\": True})\n\n if request.method == \"POST\":\n\n noticeForm = editNotices(request.POST, instance=getNotice)\n\n if noticeForm.is_valid():\n noticeForm.save()\n dict.update({'message': \"Notice Updated successfully\"})\n return HttpResponseRedirect(reverse('dashboard:dashboard'))\n \n else:\n noticeForm = editNotices(request.POST)\n dict.update({\"createNotice\": noticeForm})\n\n\n dict.update({'check': True})\n return render(request, 'notices/createNotice.html', context=dict)\n \n\n dict.update({'message': \"You do not have the authority to edit a notice\"})\n return render(request, 'showMessage.html', context=dict)\n\n\n\n@login_required\ndef deleteNotice(request, id):\n\n dict = {}\n\n currentUser = request.user\n currentUserMoreInfo = userInfo.objects.get(user__pk = currentUser.id)\n\n\n if (currentUserMoreInfo.role == \"1\") or (currentUserMoreInfo.role == \"2\"):\n \n notice.objects.get(pk=id).delete()\n return HttpResponseRedirect(reverse('dashboard:dashboard'))\n \n dict.update({'message': \"You do not have the authority to delete a notice\"})\n return render(request, 'showMessage.html', context=dict)\n\n\n\n@login_required\ndef makeComplete(request, id):\n\n currentUser = request.user\n \n getNotice = notice.objects.get(pk=id)\n \n if getNotice.completedBy:\n return HttpResponseRedirect(reverse('dashboard:dashboard'))\n \n \n getNotice.completedBy = currentUser.id\n getNotice.save(update_fields=['completedBy'])\n\n return HttpResponseRedirect(reverse('dashboard:dashboard'))\n\n\n\n@login_required\ndef makeIncomplete(request, id):\n\n getNotice = notice.objects.get(pk=id)\n \n \n getNotice.completedBy = \"\"\n getNotice.save(update_fields=['completedBy'])\n\n return HttpResponseRedirect(reverse('dashboard:dashboard'))\n\n\n\n\n\n\n\n@login_required\ndef seeAllEmployee(request):\n\n dict = {}\n\n currentUser = request.user\n currentUserMoreInfo = userInfo.objects.get(user__pk = currentUser.id)\n\n if currentUser.is_authenticated:\n\n users = User.objects.all()\n usersMoreInfo = userInfo.objects.order_by('role').select_related(\"user\")\n\n dict.update({'users' : users})\n dict.update({'userMoreInfo': usersMoreInfo})\n\n if (currentUserMoreInfo.role == \"1\" or currentUserMoreInfo.role == \"2\" or currentUserMoreInfo.role == \"3\" ):\n dict.update({\"employeeController\": True})\n\n if (currentUserMoreInfo.role == \"1\" or currentUserMoreInfo.role == \"4\" ):\n dict.update({\"finaceController\": True})\n \n if (currentUserMoreInfo.role == \"1\"):\n dict.update({\"fullEmployeeControler\": True})\n\n return render(request, 'seeAllEmployee/allUserDetails.html', context=dict)\n \n dict.update({'message': \"You does not have authority to see the employee\"})\n return render(request, 'showMessage.html', context=dict)\n\n\n","repo_name":"mahadirazib/erp_for_startup","sub_path":"dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"15264493049","text":"# 제한사항\n# record는 다음과 같은 문자열이 담긴 배열이며, 길이는 1 이상 100,000 이하이다.\n# 다음은 record에 담긴 문자열에 대한 설명이다.\n# 모든 유저는 [유저 아이디]로 구분한다.\n# [유저 아이디] 사용자가 [닉네임]으로 채팅방에 입장 - \"Enter [유저 아이디] [닉네임]\" (ex. \"Enter uid1234 Muzi\")\n# [유저 아이디] 사용자가 채팅방에서 퇴장 - \"Leave [유저 아이디]\" (ex. \"Leave uid1234\")\n# [유저 아이디] 사용자가 닉네임을 [닉네임]으로 변경 - \"Change [유저 아이디] [닉네임]\" (ex. \"Change uid1234 Muzi\")\n# 첫 단어는 Enter, Leave, Change 중 하나이다.\n# 각 단어는 공백으로 구분되어 있으며, 알파벳 대문자, 소문자, 숫자로만 이루어져있다.\n# 유저 아이디와 닉네임은 알파벳 대문자, 소문자를 구별한다.\n# 유저 아이디와 닉네임의 길이는 1 이상 10 이하이다.\n# 채팅방에서 나간 유저가 닉네임을 변경하는 등 잘못 된 입력은 주어지지 않는다.\n\n\t\nrecord=[\"Enter uid1234 Muzi\", \"Enter uid4567 Prodo\",\"Leave uid1234\",\"Enter uid1234 Prodo\",\"Change uid4567 Ryan\"]\t\n# 결과 값 : [\"Prodo님이 들어왔습니다.\", \"Ryan님이 들어왔습니다.\", \"Prodo님이 나갔습니다.\", \"Prodo님이 들어왔습니다.\"]\n\ndef solution(record):\n answer = []\n state_dic={\"Enter\":\"님이 들어왔습니다.\",\"Leave\":\"님이 나갔습니다.\"}\n # id:닉네임\n info_dic=dict()\n # 출력 상태 및 정보 저장할 리스트\n state_list=[]\n for r in record:\n print(r)\n info=r.split()\n state=info[0]\n id=info[1]\n if len(info)==3:\n nick=info[2]\n info_dic[id]=nick\n state_list.append((id,state))\n for s in state_list:\n if s[1]==\"Change\":continue\n word=info_dic[s[0]]+state_dic[s[1]]\n answer.append(word)\n print(answer)\n print(info_dic)\n \n return answer\n\nsolution(record)","repo_name":"commGom/pythonStudy","sub_path":"알고리즘withPy/카카오기출/2단계_level/오픈채팅방.py","file_name":"오픈채팅방.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"13880119521","text":"from oauth2client.service_account import ServiceAccountCredentials\nfrom googleapiclient.discovery import build\nfrom googleapiclient.http import MediaFileUpload\nimport io\nfrom googleapiclient.http import MediaIoBaseDownload\nimport json\nSERVICE_ACCOUNT = 'cred.json' # Please set the file of your credentials of service account.\nUPLOAD_FILE = 'b.txt' # Please set the filename with the path you want to upload.\nFOLDER_ID = '1BQY5YyGjRvG-FMP3PrEILu8NfD-JWXud' # Please set the folder ID that you shared your folder with the service account.\nFILENAME = 'b.txt' # You can set the filename of the uploaded file on Google Drive.\n\nSCOPES = ['https://www.googleapis.com/auth/drive']\ncredentials = ServiceAccountCredentials.from_json_keyfile_name(SERVICE_ACCOUNT, SCOPES)\ndrive = build('drive', 'v3', credentials=credentials)\n\n\ndef create_file(name,folder_id,filedir):\n metadata = {'name': name, \"parents\": [folder_id]}\n file = MediaFileUpload(filedir, resumable=True)\n\n response = drive.files().create(body=metadata, media_body=file).execute()\n fileId = response.get('id')\n print(fileId) # You can see the file ID of the uploaded file.\n return fileId\ndef delete_file(file_id):\n try:\n drive.files().delete(fileId=file_id).execute()\n return True\n except:\n return False\n\ndef download_file(name,file_id):\n request = drive.files().get_media(fileId=file_id)\n fh = io.FileIO(name, 'wb')\n downloader = MediaIoBaseDownload(fh, request)\n done = False\n while done is False:\n status, done = downloader.next_chunk()\n print (\"Download done\")\n f = open(name, \"r\")\n return (json.loads(f.read()))\n\n\ndef update_file(file,file_id):\n media_content = MediaFileUpload(file, mimetype='text/plain')\n print(drive.files().update(fileId=file_id,media_body=media_content).execute())\n#print(download_file('nn.txt','1K0g6A4VvqlKahRmm00MDiKk-fDVDK3U6')['text'])\n#create_file(\"gg2.txt\",FOLDER_ID,\"gg.txt\")\n#print(delete_file(\"1K0g6A4VvqlKahRmm00MDiKk-fDVDK3U6\"))\nfile_id = '13Cv0b6Veo9PSRr-kis9-V8Ml-DuiBZGY'\n#update_file(\"vv.txt\",file_id)","repo_name":"shasabbir/google-drive-python","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"42080772180","text":"import random\n\n# 使用dir函数查看random库中的函数和属性\nprint(dir(random))\n\n# 使用help函数获取特定函数的帮助信息\nhelp(random.random)\nhelp(random.randint)\n\n# 使用random库生成随机数\nrandom_number = random.random() # 生成0到1之间的随机浮点数\nrandom_integer = random.randint(1, 10) # 生成1到10之间的随机整数\n\nprint(\"Random number:\", random_number)\nprint(\"Random integer:\", random_integer)","repo_name":"biancaurendell/python-","sub_path":"program/experiment 1/import the random.py","file_name":"import the random.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"1160255465","text":"\nfrom pyspark.sql.types import StringType, FloatType\n\nCOLUMNS = [\n (\"winstate_inc\", FloatType()),\n (\"winstate_chal\", FloatType()),\n (\"voteshare_inc\", FloatType()),\n (\"voteshare_chal\", FloatType()),\n (\"win_EC_if_win_state_inc\", FloatType()),\n (\"win_EC_if_win_state_chal\", FloatType()),\n (\"margin\", FloatType()),\n (\"vpi\", FloatType()),\n (\"state\", StringType()),\n (\"tipping\", FloatType()),\n (\"modeldate\", StringType())\n]\n\nACCEPTER_BATCH_PERCENTAGE = 5","repo_name":"santiagoMeloMedina/Presidential_Polls_Prediction","sub_path":"streaming/predictor/constant/batch.py","file_name":"batch.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}
+{"seq_id":"27892657771","text":"from os.path import abspath, dirname, join\nfrom unittest import TestCase\n\nfrom freezegun import freeze_time\nimport pytest\n\nfrom iatikit.data.registry import Registry\nfrom iatikit.utils.exceptions import FilterError\nfrom iatikit.utils.config import CONFIG\n\n\nclass TestGenericSet(TestCase):\n def __init__(self, *args, **kwargs):\n super(TestGenericSet, self).__init__(*args, **kwargs)\n registry_path = join(dirname(abspath(__file__)),\n 'fixtures', 'registry')\n config_dict = {'paths': {'registry': registry_path}}\n CONFIG.read_dict(config_dict)\n\n @freeze_time(\"2015-12-02\")\n def setUp(self):\n self.registry = Registry()\n\n def test_set_get(self):\n org_dataset = self.registry.datasets.get('fixture-org-org')\n assert org_dataset.name == 'fixture-org-org'\n\n def test_set_get_unknown(self):\n unknown_dataset = self.registry.datasets.get('unknown')\n assert unknown_dataset is None\n\n def test_set_find(self):\n org_dataset = self.registry.datasets.find(name='fixture-org-org')\n assert org_dataset.name == 'fixture-org-org'\n\n def test_set_not_found(self):\n with pytest.raises(IndexError):\n self.registry.datasets.find(name='not-a-dataset')\n\n def test_set_first(self):\n first_dataset = self.registry.datasets.first()\n zero_index_dataset = self.registry.datasets[0]\n assert first_dataset.name == zero_index_dataset.name\n\n def test_set_count(self):\n datasets = self.registry.datasets\n assert datasets.count() == 5\n\n def test_set_all(self):\n dataset_names = [\n 'fixture-org-activities',\n 'fixture-org-activities2',\n 'fixture-org-org',\n 'old-org-acts',\n 'old-org-missing-acts',\n ]\n datasets = self.registry.datasets.all()\n assert isinstance(datasets, list)\n assert len(datasets) == 5\n for dataset in datasets:\n assert dataset.name in dataset_names\n\n def test_set_filter_chaining(self):\n act_datasets = self.registry.datasets.filter(filetype='activity')\n no_datasets = act_datasets.filter(name='fixture-org-org')\n assert no_datasets.count() == 0\n\n org_datasets = self.registry.datasets.filter(filetype='organisation')\n org_dataset = org_datasets.filter(name='fixture-org-org')\n assert org_dataset.count() == 1\n\n def test_set_where_chaining(self):\n act_datasets = self.registry.datasets.where(filetype='activity')\n no_datasets = act_datasets.where(name='fixture-org-org')\n assert no_datasets.count() == 0\n\n org_datasets = self.registry.datasets.where(filetype='organisation')\n org_dataset = org_datasets.where(name='fixture-org-org')\n assert org_dataset.count() == 1\n\n def test_set_unknown_filter(self):\n with pytest.raises(FilterError):\n self.registry.datasets.where(unknown_filter='unknown')\n","repo_name":"codeforIATI/iatikit","sub_path":"tests/test_generic_set.py","file_name":"test_generic_set.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"77"}
+{"seq_id":"33415529045","text":"# coding: utf-8\n\nimport os\nimport json\nimport time\nimport base64\nimport threading\nimport pkg_resources\nimport argparse\nimport urllib\nimport mimetypes\nimport posixpath\nimport traceback\nimport pathlib\nimport random\nfrom collections import OrderedDict\nimport xmltodict\n\nimport PIL\nimport numpy as np\nfrom concurrent.futures import ThreadPoolExecutor as Executor\nfrom concurrent.futures import ProcessPoolExecutor\nfrom concurrent.futures import CancelledError\nfrom signal import signal, SIGPIPE, SIG_DFL, SIG_IGN\nfrom bottle import HTTPResponse, default_app, route, static_file, request, error\n\nfrom renom.cuda import release_mem_pool\nfrom renom_img.server import create_dirs\ncreate_dirs()\n\nfrom renom_img.api.utility.load import parse_xml_detection\nfrom renom_img.server import wsgi_server\nfrom renom_img.server.train_thread import TrainThread\nfrom renom_img.server.prediction_thread import PredictionThread\nfrom renom_img.server.utility.storage import storage\n\n# Constants\nfrom renom_img.server import MAX_THREAD_NUM, DB_DIR_TRAINED_WEIGHT, GPU_NUM\nfrom renom_img.server import DATASRC_IMG, DATASRC_LABEL, DATASRC_DIR, DATASRC_PREDICTION_OUT\nfrom renom_img.server import STATE_FINISHED, STATE_RUNNING, STATE_DELETED, STATE_RESERVED\nfrom renom_img.server import WEIGHT_EXISTS, WEIGHT_CHECKING, WEIGHT_DOWNLOADING\n\nexecutor = Executor(max_workers=MAX_THREAD_NUM)\n\n# Thread(Future object) is stored to thread_pool as pair of \"thread_id:[future, thread_obj]\".\ntrain_thread_pool = {}\nprediction_thread_pool = {}\n\nconfirm_dataset = OrderedDict()\n\n\ndef get_train_thread_count():\n return len([th for th in train_thread_pool.values() if th[0].running()])\n\n\ndef create_response(body):\n r = HTTPResponse(status=200, body=body)\n r.set_header('Content-Type', 'application/json')\n return r\n\n\ndef strip_path(filename):\n if os.path.isabs(filename):\n raise ValueError('Invalid path')\n if '..' in filename:\n raise ValueError('Invalid path')\n if ':' in filename:\n raise ValueError('Invalid path')\n\n filename = filename.strip().strip('./\\\\')\n return filename\n\n\ndef _get_resource(path, filename):\n filename = strip_path(filename)\n body = pkg_resources.resource_string(__name__, posixpath.join('.build', path, filename))\n\n headers = {}\n mimetype, encoding = mimetypes.guess_type(filename)\n if mimetype:\n headers['Content-Type'] = mimetype\n if encoding:\n headers['encoding'] = encoding\n return HTTPResponse(body, **headers)\n\n\n@route(\"/\")\ndef index():\n return _get_resource('', 'index.html')\n\n\n@route(\"/static/\")\ndef static(file_name):\n return _get_resource('static', file_name)\n\n\n@route(\"/css/\")\ndef css(file_name):\n return _get_resource('static/css/', file_name)\n\n\n@route(\"/fonts/