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://img.shields.io/badge/POC%20Early%20Warning-GitHub-100000?logo=github&logoColor=white)](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'''
''' % (status_obj.color if status_obj else '#fff',\n status_obj.name if status_obj else '---'),\n u'''''' % tooth.mobility or u'---',\n u'''''' % svg,\n u'''''' % 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'
%s%s%sСтатусПодвижностьСостояниеНомерНомерСостояниеПодвижностьСтатус
%s
' %\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 半径は何cm? \n \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} \\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} \\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} \\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} \\n\")\n f.write(f'\\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 `\"\n\n return f\"\"\"\n
` will always use the caption.\"\"\"\n self.assert_header_from_table(\n \"Caption\",\n \"\"\"\n

Header

\n

Subheader

\n \n \n
Caption
\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 {caption}\n \n \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/\")\ndef font(file_name):\n return _get_resource('static/fonts/', file_name)\n\n\n@error(404)\ndef error404(error):\n print(error)\n body = json.dumps({\"error_msg\": \"Page Not Found\"})\n ret = create_response(body)\n return ret\n\n\n@route(\"/datasrc//\")\ndef datasrc(folder_name, file_name):\n file_dir = os.path.join('datasrc', folder_name)\n return static_file(file_name, root=file_dir, mimetype='image/*')\n\n\n@route(\"/api/renom_img/v1/projects/\", method=\"GET\")\ndef get_project(project_id):\n try:\n kwargs = {}\n kwargs[\"fields\"] = \"project_id,project_name,project_comment,deploy_model_id\"\n\n data = storage.fetch_project(project_id, **kwargs)\n data['gpu_num'] = GPU_NUM or 1\n body = json.dumps(data)\n except Exception as e:\n traceback.print_exc()\n body = json.dumps({\"error_msg\": e.args[0]})\n\n ret = create_response(body)\n return ret\n\n\n@route(\"/api/renom_img/v1/projects//models/\", method=\"GET\")\ndef get_model(project_id, model_id):\n try:\n kwargs = {}\n if request.params.fields != '':\n kwargs[\"fields\"] = request.params.fields\n\n data = storage.fetch_model(project_id, model_id, **kwargs)\n body = json.dumps(data)\n\n except Exception as e:\n traceback.print_exc()\n body = json.dumps({\"error_msg\": e.args[0]})\n\n ret = create_response(body)\n return ret\n\n\n@route(\"/api/renom_img/v1/projects//models\", method=\"GET\")\ndef get_models(project_id):\n try:\n data = storage.fetch_models(project_id)\n body = json.dumps(data)\n ret = create_response(body)\n return ret\n\n except Exception as e:\n traceback.print_exc()\n body = json.dumps({\"error_msg\": e.args[0]})\n ret = create_response(body)\n return ret\n\n\n@route(\"/api/renom_img/v1/projects//model/create\", method=\"POST\")\ndef create_model(project_id):\n try:\n model_id = storage.register_model(\n project_id=project_id,\n dataset_def_id=json.loads(request.params.dataset_def_id),\n hyper_parameters=json.loads(request.params.hyper_parameters),\n algorithm=request.params.algorithm,\n algorithm_params=json.loads(request.params.algorithm_params))\n\n if get_train_thread_count() >= MAX_THREAD_NUM:\n storage.update_model_state(model_id, STATE_RESERVED)\n else:\n storage.update_model_state(model_id, STATE_RUNNING)\n\n data = {\"model_id\": model_id}\n body = json.dumps(data)\n except Exception as e:\n traceback.print_exc()\n body = json.dumps({\"error_msg\": e.args[0]})\n ret = create_response(body)\n return ret\n\n\n@route(\"/api/renom_img/v1/projects//models//run\", method=\"GET\")\ndef run_model(project_id, model_id):\n \"\"\"\n Create thread(Future object) and submit it to executor.\n The thread is stored to train_thread_pool as a pair of thread_id and thread.\n \"\"\"\n try:\n fields = 'hyper_parameters,algorithm,algorithm_params,dataset_def_id'\n data = storage.fetch_model(project_id, model_id, fields=fields)\n thread_id = \"{}_{}\".format(project_id, model_id)\n th = TrainThread(thread_id, project_id, model_id,\n data['dataset_def_id'],\n data[\"hyper_parameters\"],\n data['algorithm'], data['algorithm_params'])\n ft = executor.submit(th)\n train_thread_pool[thread_id] = [ft, th]\n\n try:\n # This will wait for end of thread.\n ft.result()\n ft.cancel()\n except CancelledError as ce:\n # If the model is deleted or stopped,\n # program reaches here.\n pass\n error_msg = th.error_msg\n del train_thread_pool[thread_id]\n ft = None\n th = None\n\n model = storage.fetch_model(project_id, model_id, fields='state')\n if model['state'] != STATE_DELETED:\n storage.update_model_state(model_id, STATE_FINISHED)\n release_mem_pool()\n\n if error_msg is not None:\n body = json.dumps({\"error_msg\": error_msg})\n ret = create_response(body)\n return ret\n body = json.dumps({\"dummy\": \"\"})\n ret = create_response(body)\n return ret\n\n except Exception as e:\n release_mem_pool()\n traceback.print_exc()\n body = json.dumps({\"error_msg\": e.args[0]})\n ret = create_response(body)\n return ret\n\n\n@route(\"/api/renom_img/v1/projects//models//progress\", method=\"POST\")\ndef progress_model(project_id, model_id):\n try:\n try:\n req_last_batch = request.params.get(\"last_batch\", None)\n req_last_batch = int(req_last_batch) if req_last_batch is not None else 0\n req_last_epoch = request.params.get(\"last_epoch\", None)\n req_last_epoch = int(req_last_epoch) if req_last_epoch is not None else 0\n req_running_state = request.params.get(\"running_state\", None)\n req_running_state = int(req_running_state) if req_running_state is not None else 0\n except Exception as e:\n req_last_batch = 0\n req_last_epoch = 0\n req_running_state = 0\n\n thread_id = \"{}_{}\".format(project_id, model_id)\n for j in range(60):\n time.sleep(0.75)\n th = train_thread_pool.get(thread_id, None)\n model_state = storage.fetch_model(project_id, model_id, fields=\"state\")[\"state\"]\n if th is not None:\n th = th[1]\n # If thread status updated, return response.\n if isinstance(th, TrainThread) and th.nth_epoch != req_last_epoch and th.valid_loss_list:\n best_epoch = int(np.argmin(th.valid_loss_list))\n try:\n body = json.dumps({\n \"total_batch\": th.total_batch,\n \"last_batch\": th.nth_batch,\n \"last_epoch\": th.nth_epoch,\n \"batch_loss\": th.last_batch_loss,\n \"running_state\": th.running_state,\n \"state\": model_state,\n \"validation_loss_list\": th.valid_loss_list,\n \"train_loss_list\": th.train_loss_list,\n \"best_epoch\": best_epoch,\n \"best_epoch_iou\": th.valid_iou_list[best_epoch],\n \"best_epoch_map\": th.valid_map_list[best_epoch],\n \"best_epoch_validation_result\": th.valid_predict_box[best_epoch]\n })\n ret = create_response(body)\n return ret\n except Exception as e:\n traceback.print_exc()\n import pdb\n pdb.set_trace()\n\n elif isinstance(th, TrainThread) and (th.nth_batch != req_last_batch or\n th.running_state != req_running_state or\n th.weight_existance == WEIGHT_DOWNLOADING):\n body = json.dumps({\n \"total_batch\": th.total_batch,\n \"last_batch\": th.nth_batch,\n \"last_epoch\": th.nth_epoch,\n \"batch_loss\": th.last_batch_loss,\n \"running_state\": th.running_state,\n \"state\": model_state,\n \"validation_loss_list\": [],\n \"train_loss_list\": [],\n \"best_epoch\": 0,\n \"best_epoch_iou\": 0,\n \"best_epoch_map\": 0,\n \"best_epoch_validation_result\": []\n })\n ret = create_response(body)\n return ret\n\n except Exception as e:\n traceback.print_exc()\n body = json.dumps({\"error_msg\": e.args[0]})\n ret = create_response(body)\n return ret\n\n\n@route(\"/api/renom_img/v1/projects//models//stop\", method=\"GET\")\ndef stop_model(project_id, model_id):\n try:\n thread_id = \"{}_{}\".format(project_id, model_id)\n\n th = train_thread_pool.get(thread_id, None)\n if th is not None:\n if not th[0].cancel():\n th[1].stop()\n th[0].result() # Same as join.\n storage.update_model_state(model_id, STATE_FINISHED)\n\n except Exception as e:\n traceback.print_exc()\n body = json.dumps({\"error_msg\": e.args[0]})\n ret = create_response(body)\n return ret\n\n\n@route(\"/api/renom_img/v1/projects//models/\", method=\"DELETE\")\ndef delete_model(project_id, model_id):\n try:\n thread_id = \"{}_{}\".format(project_id, model_id)\n storage.update_model_state(model_id, STATE_DELETED)\n th = train_thread_pool.get(thread_id, None)\n if th is not None:\n if not th[0].cancel():\n th[1].stop()\n th[0].result()\n\n ret = storage.fetch_model(project_id, model_id, \"best_epoch_weight\")\n file_name = ret.get('best_epoch_weight', None)\n if file_name is not None:\n weight_path = os.path.join(DB_DIR_TRAINED_WEIGHT, file_name)\n if os.path.exists(weight_path):\n os.remove(weight_path)\n\n except Exception as e:\n traceback.print_exc()\n body = json.dumps({\"error_msg\": e.args[0]})\n ret = create_response(body)\n return ret\n\n\n@route(\"/api/renom_img/v1/projects//models/update/state\", method=\"GET\")\ndef update_models_state(project_id):\n try:\n # set running model information for polling\n for _ in range(60):\n body = {}\n models = storage.fetch_models(project_id)\n reserved_count = 0\n running_count = 0\n for k in list(models.keys()):\n model_id = models[k][\"model_id\"]\n running_state = models[k][\"running_state\"]\n state = models[k]['state']\n body[model_id] = {\n 'running_state': running_state,\n 'state': state\n }\n if state == STATE_RESERVED:\n reserved_count += 1\n if state == STATE_RUNNING:\n running_count += 1\n\n if reserved_count > 0 and running_count < MAX_THREAD_NUM:\n time.sleep(2)\n else:\n break\n\n body = json.dumps(body)\n ret = create_response(body)\n return ret\n except Exception as e:\n traceback.print_exc()\n body = json.dumps({\"error_msg\": e.args[0]})\n ret = create_response(body)\n return ret\n\n\n@route(\"/api/renom_img/v1/dataset_defs\", method=\"GET\")\ndef get_datasets():\n try:\n recs = storage.fetch_dataset_defs()\n ret = []\n for rec in recs:\n id, name, ratio, description, train_imgs, valid_imgs, class_map, class_tag_list, created, updated = rec\n valid_img_names = [os.path.join(\"datasrc/img/\", path) for path in valid_imgs]\n valid_imgs = []\n for img_name in valid_img_names:\n try:\n im = PIL.Image.open(img_name)\n width, height = im.size\n except Exception:\n traceback.print_exc()\n width = height = 50\n valid_imgs.append(dict(filename=img_name, width=width, height=height))\n\n ret.append(dict(id=id,\n name=name,\n ratio=ratio,\n description=description,\n train_imgs=len(train_imgs),\n valid_imgs=valid_imgs,\n class_map=class_map,\n class_tag_list=class_tag_list,\n created=created,\n updated=updated\n )\n )\n return create_response(json.dumps({'dataset_defs': ret}))\n\n except Exception as e:\n traceback.print_exc()\n body = json.dumps({\"error_msg\": e.args[0]})\n ret = create_response(body)\n return ret\n\n\n@route(\"/api/renom_img/v1/load_dataset_split_detail\", method=['POST', 'GET'])\ndef load_dataset_split_detail():\n import time\n try:\n start_t = time.time()\n datasrc = pathlib.Path(DATASRC_DIR)\n imgdirname = pathlib.Path(\"img\")\n xmldirname = pathlib.Path(\"label\")\n\n imgdir = (datasrc / imgdirname)\n xmldir = (datasrc / xmldirname)\n\n name = urllib.parse.unquote(request.params.name, encoding='utf-8')\n ratio = float(request.params.ratio)\n client_id = request.params.u_id\n description = urllib.parse.unquote(request.params.description, encoding='utf-8')\n\n start_t = time.time()\n\n # if 2nd time delete confirmdataset id\n if request.params.delete_id:\n del confirm_dataset[request.params.delete_id]\n\n # old cofirm_dataset delete\n if len(confirm_dataset) > 100:\n confirm_dataset.popitem(False)\n\n # search image files\n imgs = (p.relative_to(imgdir) for p in imgdir.iterdir() if p.is_file())\n\n # remove images without label\n imgs = set([img for img in imgs if (xmldir / img).with_suffix('.xml').is_file()])\n assert len(imgs) > 0, \"Image not found in directory. Please set images to 'datasrc/img' directory and xml files to 'datasrc/label' directory.\"\n\n # split files into trains and validations\n n_imgs = len(imgs)\n\n trains = set(random.sample(imgs, int(ratio * n_imgs)))\n valids = imgs - trains\n\n start_t = time.time()\n # build filename of images and labels\n train_imgs = [str(img) for img in trains]\n valid_imgs = [str(img) for img in valids]\n\n perm = np.random.permutation(int(n_imgs))\n perm_train, perm_valid = np.split(perm, [int(n_imgs * ratio)])\n imgs = list(imgs)\n\n parsed_train_imgs = []\n parsed_valid_imgs = []\n\n parsed_train_img_names = [str(imgs[perm]).split('.')[0] for perm in perm_train]\n parsed_valid_img_names = [str(imgs[perm]).split('.')[0] for perm in perm_valid]\n\n start_t = time.time()\n\n parsed_train, train_class_map = parse_xml_detection([str(path) for path in xmldir.iterdir() if str(\n path).split('/')[-1].split('.')[0] in parsed_train_img_names], num_thread=8)\n\n parsed_valid, valid_class_map = parse_xml_detection([str(path) for path in xmldir.iterdir() if str(\n path).split('/')[-1].split('.')[0] in parsed_valid_img_names], num_thread=8)\n\n start_t = time.time()\n # Insert detailed informations\n train_num = len(train_imgs)\n valid_num = len(valid_imgs)\n class_tag_list = []\n\n train_tag_count = {}\n for i in range(len(parsed_train)):\n for j in range(len(train_class_map)):\n if parsed_train[i][0].get('name') == train_class_map[j]:\n if train_class_map[j] not in train_tag_count:\n train_tag_count[train_class_map[j]] = 1\n else:\n train_tag_count[train_class_map[j]] += 1\n\n valid_tag_count = {}\n for i in range(len(parsed_valid)):\n for j in range(len(valid_class_map)):\n if parsed_valid[i][0].get('name') == valid_class_map[j]:\n if valid_class_map[j] not in valid_tag_count:\n valid_tag_count[valid_class_map[j]] = 1\n else:\n valid_tag_count[valid_class_map[j]] += 1\n\n for tags in sorted(train_tag_count.keys()):\n class_tag_list.append({\n \"tags\": tags,\n \"train\": train_tag_count.get(tags),\n \"valid\": valid_tag_count.get(tags)\n })\n\n # save datasplit setting\n confirm_dataset[client_id] = {\n \"name\": name,\n \"ratio\": ratio,\n \"description\": description,\n \"train_imgs\": train_imgs,\n \"valid_imgs\": valid_imgs,\n \"class_maps\": train_class_map,\n \"class_tag_list\": class_tag_list\n }\n\n body = json.dumps(\n {\"total\": n_imgs,\n \"id\": client_id,\n \"description\": description,\n \"train_image_num\": train_num,\n \"valid_image_num\": valid_num,\n \"class_tag_list\": class_tag_list,\n \"train_imgs\": train_imgs,\n \"valid_imgs\": valid_imgs,\n })\n\n ret = create_response(body)\n return ret\n\n except Exception as e:\n traceback.print_exc()\n body = json.dumps({\"error_msg\": e.args[0]})\n ret = create_response(body)\n return ret\n\n\n@route(\"/api/renom_img/v1/weights/progress/\", method=\"GET\")\ndef weight_download_progress(progress_num):\n try:\n for i in range(60):\n for th in train_thread_pool.values():\n if isinstance(th, TrainThread) and th[1].weight_existance == WEIGHT_CHECKING:\n pass\n elif th[1].weight_existance == WEIGHT_EXISTS:\n body = json.dumps({\"progress\": 100})\n ret = create_response(body)\n return ret\n elif th[1].weight_existance == WEIGHT_DOWNLOADING:\n if th[1].percentage > 10 * progress_num:\n body = json.dumps({\"progress\": th[1].percentage})\n ret = create_response(body)\n return ret\n time.sleep(1)\n\n except Exception as e:\n traceback.print_exc()\n body = json.dumps({\"error_msg\": e.args[0]})\n ret = create_response(body)\n return ret\n\n\n@route(\"/api/renom_img/v1/dataset_defs/\", method=\"POST\")\ndef create_dataset_def():\n try:\n # register dataset\n client_id = request.params.u_id\n name = urllib.parse.unquote(request.params.name, encoding='utf-8')\n description = urllib.parse.unquote(request.params.description, encoding='utf-8')\n\n id = storage.register_dataset_def(\n name,\n confirm_dataset[client_id].get('ratio'),\n description,\n confirm_dataset[client_id].get('train_imgs'),\n confirm_dataset[client_id].get('valid_imgs'),\n confirm_dataset[client_id].get('class_maps'),\n confirm_dataset[client_id].get('class_tag_list')\n )\n\n # Insert detailed informations\n\n del confirm_dataset[client_id]\n\n body = json.dumps({\"id\": id})\n ret = create_response(body)\n return ret\n\n except Exception as e:\n traceback.print_exc()\n body = json.dumps({\"error_msg\": e.args[0]})\n ret = create_response(body)\n return ret\n\n\n@route(\"/api/renom_img/v1/projects//models//run_prediction\", method=\"GET\")\ndef run_prediction(project_id, model_id):\n # 学習データ読み込み\n try:\n thread_id = \"{}_{}\".format(project_id, model_id)\n fields = 'hyper_parameters,algorithm,algorithm_params,best_epoch_weight,dataset_def_id'\n data = storage.fetch_model(project_id, model_id, fields=fields)\n (id, name, ratio, train_imgs, valid_imgs, class_map, created,\n updated) = storage.fetch_dataset_def(data['dataset_def_id'])\n # weightのh5ファイルのパスを取得して予測する\n with Executor(max_workers=MAX_THREAD_NUM) as prediction_executor:\n th = PredictionThread(thread_id, model_id, data[\"hyper_parameters\"], data[\"algorithm\"],\n data[\"algorithm_params\"], data[\"best_epoch_weight\"], class_map)\n ft = prediction_executor.submit(th)\n prediction_thread_pool[thread_id] = [ft, th]\n ft.result()\n\n if th.error_msg is not None:\n body = json.dumps({\"error_msg\": th.error_msg})\n else:\n data = {\n \"predict_results\": th.predict_results,\n \"csv\": th.csv_filename,\n }\n body = json.dumps(data)\n except Exception as e:\n traceback.print_exc()\n body = json.dumps({\"error_msg\": e.args[0]})\n\n ret = create_response(body)\n return ret\n\n\n@route(\"/api/renom_img/v1/projects//models//prediction_info\", method=\"GET\")\ndef prediction_info(project_id, model_id):\n try:\n # 学習データ読み込み\n thread_id = \"{}_{}\".format(project_id, model_id)\n while True:\n if thread_id in prediction_thread_pool:\n _, th = prediction_thread_pool[thread_id]\n break\n else:\n time.sleep(1)\n time.sleep(1)\n data = {\n \"predict_total_batch\": th.total_batch,\n \"predict_last_batch\": th.nth_batch,\n }\n body = json.dumps(data)\n ret = create_response(body)\n return ret\n except Exception as e:\n traceback.print_exc()\n body = json.dumps({\"error_msg\": e.args[0]})\n\n ret = create_response(body)\n return ret\n\n\n@route(\"/api/renom_img/v1/projects//models//export_csv/\", method=\"GET\")\ndef export_csv(project_id, model_id, filename):\n try:\n BASE_DIR = os.path.dirname(os.path.abspath(__file__))\n csv_dir = os.path.join(BASE_DIR, DATASRC_PREDICTION_OUT, 'csv')\n return static_file(filename, root=csv_dir, download=True)\n except Exception as e:\n traceback.print_exc()\n body = json.dumps({\"error_msg\": e.args[0]})\n ret = create_response(body)\n return ret\n\n\n@route(\"/api/renom_img/v1/projects//models//deploy\", method=\"GET\")\ndef deploy_model(project_id, model_id):\n try:\n storage.update_project_deploy(project_id, model_id)\n except Exception as e:\n traceback.print_exc()\n body = json.dumps({\"error_msg\": e.args[0]})\n ret = create_response(body)\n return ret\n\n\n@route(\"/api/renom_img/v1/projects//models//undeploy\", method=\"GET\")\ndef undeploy_model(project_id, model_id):\n try:\n storage.update_project_deploy(project_id, None)\n except Exception as e:\n traceback.print_exc()\n body = json.dumps({\"error_msg\": e.args[0]})\n ret = create_response(body)\n return ret\n\n\n@route(\"/api/renom_img/v1/projects//deployed_model\", method=\"GET\")\ndef pull_deployed_model(project_id):\n # This method will be called from python script.\n try:\n deployed_id = storage.fetch_deployed_model_id(project_id)[0]['deploy_model_id']\n ret = storage.fetch_model(project_id, deployed_id, \"best_epoch_weight\")\n file_name = ret['best_epoch_weight']\n path = DB_DIR_TRAINED_WEIGHT\n return static_file(file_name, root=path, download='deployed_model.h5')\n except Exception as e:\n traceback.print_exc()\n body = json.dumps({\"error_msg\": e.args[0]})\n ret = create_response(body)\n return ret\n\n\n@route(\"/api/renom_img/v1/projects//deployed_model_info\", method=\"GET\")\ndef get_deployed_model_info(project_id):\n # This method will be called from python script.\n try:\n deployed_id = storage.fetch_deployed_model_id(project_id)[0]['deploy_model_id']\n ret = storage.fetch_model(project_id, deployed_id, \"best_epoch_weight\")\n file_name = ret['best_epoch_weight']\n ret = storage.fetch_model(project_id, deployed_id,\n \"algorithm,algorithm_params,hyper_parameters\")\n ret[\"filename\"] = file_name\n body = json.dumps(ret)\n ret = create_response(body)\n return ret\n except Exception as e:\n traceback.print_exc()\n body = json.dumps({\"error_msg\": e.args[0]})\n ret = create_response(body)\n return ret\n\n\n@route(\"/api/renom_img/v1/projects//class_map\", method=\"GET\")\ndef get_class_map(project_id):\n try:\n ret = storage.fetch_class_map()\n body = json.dumps(ret)\n ret = create_response(body)\n return ret\n except Exception as e:\n body = json.dumps({\"error_msg\": e.args[0]})\n ret = create_response(body)\n return ret\n\n\ndef main():\n # Creates directory only if server starts.\n create_dirs()\n # Parser settings.\n parser = argparse.ArgumentParser(description='ReNomIMG')\n parser.add_argument('--host', default='0.0.0.0', help='Server address')\n parser.add_argument('--port', default='8080', help='Server port')\n\n args = parser.parse_args()\n\n wsgiapp = default_app()\n httpd = wsgi_server.Server(wsgiapp, host=args.host, port=int(args.port))\n httpd.serve_forever()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"DaikiOnodera/ReNomIMG","sub_path":"renom_img/server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":28043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"14992507265","text":"# 778. Swim in Rising Water\n# 🔴 Hard\n#\n# https://leetcode.com/problems/swim-in-rising-water/\n#\n# Tags: Array - Binary Search - Depth-First Search - Breadth-First Search\n# Union Find - Heap (Priority Queue) - Matrix\n\nimport timeit\nfrom heapq import heappop, heappush\nfrom typing import List\n\n\n# We can use a modified version of Dijkstra to solve this problem, we\n# start at 0, 0 and start visiting its neighbors, each time we visit a\n# neighbor, we compute the fastest time at which we can get there and\n# push it, together with its coordinates, into a min heap, once we have\n# visited all the neighbors of the current cell, we pop the next one\n# from the heap. Since we are always popping the cell that we can visit\n# fastest, we know that we will be updating their neighbors with the\n# fastest time possible to arrive at that cell.\n#\n# Time complexity: O(n^2*log(n)) - We may push and pop each cell into\n# the heap at a log(n^2) cost, equivalent to 2*log(n).\n# Space complexity: O(n^2) - Both the heap and the copy of the grid\n# can, or do, have n*n elements.\n#\n# Runtime: 110 ms, faster than 93.76%\n# Memory Usage: 14.3 MB, less than 97.32%\nclass Dijkstra:\n def swimInWater(self, grid: List[List[int]]) -> int:\n # The size of the square grid N == NUM_ROWS == NUM_COLS.\n N = len(grid)\n # Make a copy of the graph with current best distances.\n board = [[float(\"inf\")] * N for _ in range(N)]\n # Use a heap of tuples for nodes we need to visit.\n # (distance, row_idx, col_idx)\n # Push the first node and update the best time in which we can\n # get to it.\n heap = [(grid[0][0], 0, 0)]\n board[0][0] = grid[0][0]\n while heap:\n _, r, c = heappop(heap)\n # Mark this node as visited.\n # board[r][c] = dis\n # The 4 possible directions of travel.\n dir = ((0, 1), (0, -1), (1, 0), (-1, 0))\n for i, j in dir:\n # If still within boundaries and we haven't visited it\n # previously.\n if (\n 0 <= r + i < N\n and 0 <= c + j < N\n and board[r + i][c + j] == float(\"inf\")\n ):\n # The cost will be the max of the current cost and\n # the height of the cell we want to visit.\n cost = max(grid[r + i][c + j], board[r][c])\n # If we are at the target cell, return this value.\n if r + i == c + j == N - 1:\n return cost\n # Otherwise, push this cell into the heap to visit\n # it when its distance is the shortest in the heap.\n heappush(heap, (cost, r + i, c + j))\n board[r + i][c + j] = cost\n # For boards where we don't iterate over neighbors, return here.\n return board[-1][-1]\n\n\n# Optimize the previous solution getting rid of the copy grid and\n# mutating the input instead to mark visited nodes.\n#\n# Time complexity: O(n^2*log(n)) - We may push and pop each cell into\n# the heap at a log(n^2) cost, equivalent to 2*log(n).\n# Space complexity: O(n^2) - The heap can still grow to the same size\n# as the input.\n#\n# Runtime: 247 ms, faster than 32.54%\n# Memory Usage: 14.3 MB, less than 94.85%\nclass DijkstraOptimized:\n def swimInWater(self, grid: List[List[int]]) -> int:\n # The size of the square grid N == NUM_ROWS == NUM_COLS.\n N = len(grid)\n # Base case.\n if N == 1:\n return grid[0][0]\n # Use a heap of tuples for nodes we need to visit. Push 0,0.\n heap = [(grid[0][0], 0, 0)]\n grid[0][0] = -1\n while heap:\n dis, r, c = heappop(heap)\n # The 4 possible directions of travel.\n for i, j in ((0, 1), (0, -1), (1, 0), (-1, 0)):\n # If still within boundaries and we haven't visited it\n # previously.\n if (\n 0 <= r + i < N\n and 0 <= c + j < N\n and grid[r + i][c + j] != -1\n ):\n # The cost will be the max of the current cost and\n # the height of the cell we want to visit.\n cost = max(grid[r + i][c + j], dis)\n # If we are at the target cell, return this value.\n if r + i == c + j == N - 1:\n return cost\n # Otherwise, push this cell into the heap.\n heappush(heap, (cost, r + i, c + j))\n # Mark the cell as visited.\n grid[r + i][c + j] = -1\n\n\ndef test():\n executors = [\n Dijkstra,\n DijkstraOptimized,\n ]\n tests = [\n [[[0]], 0],\n [[[0, 2], [1, 3]], 3],\n [\n [\n [0, 1, 2, 3, 4],\n [24, 23, 22, 21, 5],\n [12, 13, 14, 15, 16],\n [11, 17, 18, 19, 20],\n [10, 9, 8, 7, 6],\n ],\n 16,\n ],\n [\n [\n [0, 1, 4, 3, 4],\n [24, 2, 22, 21, 5],\n [22, 23, 14, 15, 16],\n [11, 17, 18, 19, 20],\n [10, 9, 8, 7, 6],\n ],\n 18,\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.swimInWater(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/swim-in-rising-water.py","file_name":"swim-in-rising-water.py","file_ext":"py","file_size_in_byte":6011,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"39046180563","text":"from flask import Flask, render_template, url_for, request, send_file, Response\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom matplotlib.figure import Figure\nimport matplotlib.pyplot as plt\nimport io\nimport nltk\nimport textblob as tb\nfrom subprocess import check_output\nfrom wordcloud import WordCloud,STOPWORDS\nfrom tqdm import tqdm\nfrom bokeh.plotting import figure, show\nfrom bokeh.embed import components\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn.decomposition import NMF, LatentDirichletAllocation\n\nplt.rcParams[\"figure.figsize\"] = [20, 10]\nplt.rcParams[\"figure.autolayout\"] = True\nnews_feed = pd.read_csv('input/news-week-18aug24-mini.csv', dtype={'publish_time': object})\nnews_feed['publish_hour'] = news_feed.publish_time.str[:10]\nnews_feed['publish_date'] = news_feed.publish_time.str[:8]\nnews_feed['publish_hour_only'] = news_feed.publish_time.str[8:10]\nnews_feed['publish_time_only'] = news_feed.publish_time.str[8:12]\ndays = news_feed['publish_date'].unique().tolist()\n\nnews_feed['dt_time'] = pd.to_datetime(news_feed['publish_time'], format='%Y%m%d%H%M')\nnews_feed['dt_hour'] = pd.to_datetime(news_feed['publish_hour'], format='%Y%m%d%H')\nnews_feed['dt_date'] = pd.to_datetime(news_feed['publish_date'], format='%Y%m%d')\nfeed_count = news_feed['feed_code'].value_counts()\nfeed_count = feed_count[:10, ]\nnews_feed = news_feed.dropna()\nenglishStopWords = set(nltk.corpus.stopwords.words('english'))\nnonEnglishStopWords = set(nltk.corpus.stopwords.words()) - englishStopWords\nstopWordsDictionary = {lang: set(nltk.corpus.stopwords.words(lang)) for lang in nltk.corpus.stopwords.fileids()}\n\napp = Flask(__name__)\n\n@app.route('/', methods=['POST', 'GET'])\ndef index():\n return render_template(\"index.html\")\n\n@app.route('/statistics', methods=['GET'])\ndef statistics():\n return render_template('statistics.html')\n\n@app.route('/show-top-10-feeds')\ndef plot_top_10_feeds():\n fig = Figure()\n axis = fig.add_subplot(1, 1, 1)\n\n xs = feed_count.index\n ys = feed_count.values\n\n axis.bar(xs, ys)\n axis.set_title(\"TOP 10 FEEDS\")\n axis.set_xlabel(\"Feed Code\")\n axis.set_ylabel(\"No of Occurances\")\n\n output = io.BytesIO()\n FigureCanvas(fig).print_png(output)\n return Response(output.getvalue(), mimetype='image/png')\n\nnews_feed.headline_text.dropna()\n\ndef get_language(text):\n if type(text) is str:\n text = text.lower()\n words = set(nltk.wordpunct_tokenize(text))\n return max(((lang, len(words & stopwords)) for lang, stopwords in stopWordsDictionary.items()), key = lambda x: x[1])[0]\n\nnews_feed['language'] = news_feed['headline_text'].apply(get_language)\nlanguage_count = news_feed['language'].value_counts()\nlanguage_count = language_count[:10]\n\n@app.route('/show-top-10-languages')\ndef plot_top_10_languages():\n fig = Figure()\n axis = fig.add_subplot(1, 1, 1)\n\n xs = language_count.index\n ys = language_count.values\n\n axis.bar(xs, ys)\n axis.set_title(\"TOP 10 LANGUAGES\")\n axis.set_xlabel(\"Language\")\n axis.set_ylabel(\"No of Occurances\")\n\n output = io.BytesIO()\n FigureCanvas(fig).print_png(output)\n return Response(output.getvalue(), mimetype='image/png')\n \n@app.route('/cloud', methods=['GET'])\ndef cloud():\n news_feed_english_df = news_feed[news_feed['language'] == 'english']\n news_feed_english = news_feed_english_df['headline_text']\n words = ' '.join(news_feed_english)\n cleaned_word = \" \".join([word for word in words.split()])\n wordcloud = WordCloud(stopwords = STOPWORDS,\n background_color = 'black',\n width = 2500,\n height = 2500\n ).generate(cleaned_word)\n fig = Figure()\n axis = fig.add_subplot(1, 1, 1)\n axis.imshow(wordcloud)\n axis.axis('off')\n output = io.BytesIO()\n FigureCanvas(fig).print_png(output)\n return Response(output.getvalue(), mimetype='image/png')\n\nnews_feed.headline_text.dropna()\nnews_feed_english_df = news_feed[news_feed['language'] == 'english']\nnews_feed_english = news_feed_english_df['headline_text']\n \ndef display_topics(model, feature_names, no_top_words):\n output = \" \"\n for topic_idx , topic in enumerate(model.components_):\n output = output + \"\\nTopic %d:\" % (topic_idx) + \"\\n\"\n output = output + \" \".join([feature_names[i] for i in topic.argsort()[:-no_top_words -1:-1]]) \n return output\n\n@app.route('/nmf-results', methods=['GET', 'POST'])\ndef nmf():\n #non-negative matrix factorization NMF, \n #büyük miktardaki verileri, metin verilerini örneğin, \n #verilerin boyutsallığını azaltan daha küçük, daha seyrek gösterimleri azaltmak için kullanılabilir \n #(aynı bilgiler çok daha az değişken kullanılarak korunabilmektedir).\n \n no_features = (int) (request.form['no_of_features'])\n\n tfidf_vectorizer = TfidfVectorizer(max_df = 0.95, min_df = 2, max_features=no_features, stop_words = 'english')\n tfidf = tfidf_vectorizer.fit_transform(news_feed_english)\n tfidf_feature_names = tfidf_vectorizer.get_feature_names_out()\n\n no_topic = (int) (request.form['no_of_topics'])\n nmf = NMF(n_components=no_topic, random_state = 1, l1_ratio=.5, init = 'nndsvd').fit(tfidf)\n no_top_words = (int) (request.form['no_of_top_words'])\n\n #display_topics(nmf ,tfidf_feature_names, no_top_words)\n print(\"********************************************************\")\n #display_topics(lda , tf_feature_names , no_top_words)\n return render_template('nmf.html',output1=display_topics(nmf ,tfidf_feature_names, no_top_words))\n\n@app.route('/lda-results', methods=['GET', 'POST'])\ndef lda():\n #Latent Dirichlet allocation (LDA), doğal dil işlemede kullanılan her belgenin \n #bir konu koleksiyonu kabul edildiği ve belgedeki her kelimenin konulardan birine karşılık geldiği \n #en basit kabul edilen bir konu modelleme örneğidir.\n\n no_features = (int) (request.form['no_of_features'])\n\n tf_vectorizer = CountVectorizer(max_df = 0.95, min_df = 2, max_features=no_features, stop_words='english')\n tf = tf_vectorizer.fit_transform(news_feed_english)\n tf_feature_names = tf_vectorizer.get_feature_names_out()\n\n no_topic = (int) (request.form['no_of_topics'])\n lda = LatentDirichletAllocation(n_components=no_topic, max_iter = 5, learning_method = 'online', learning_offset=50., random_state=0).fit(tf)\n no_top_words = (int) (request.form['no_of_top_words'])\n\n #display_topics(nmf ,tfidf_feature_names, no_top_words)\n print(\"********************************************************\")\n #display_topics(lda , tf_feature_names , no_top_words)\n return render_template('lda.html',output2=display_topics(lda , tf_feature_names , no_top_words)\n)\n\n@app.route('/statistics', methods=['GET'])\ndef show_statistics():\n return render_template('statistics.html') \n\n@app.route('/time-polarities', methods=['GET'])\ndef show_time_polarities():\n news_feed.headline_text.dropna()\n news_feed_english_df = news_feed[news_feed['language'] == 'english']\n def sent(x):\n t = tb.TextBlob(x)\n return t.sentiment.polarity, t.sentiment.subjectivity\n tqdm.pandas(leave = False, mininterval = 25)\n vals = news_feed_english_df.headline_text.progress_apply(sent)\n\n news_feed_english_df['polarity'] = vals.str[0]\n news_feed_english_df['sub'] = vals.str[1]\n \n fig = Figure()\n mean_pol = list(dict(news_feed_english_df.groupby('dt_time')['polarity'].mean()).items())\n mean_pol.sort(key=lambda x: x[0])\n axis = fig.add_subplot(2, 2, 1)\n axis.plot([i[0] for i in mean_pol], [i[1] for i in mean_pol])\n axis.set_title(\"Mean polarity over time\")\n #----------------------------------------------------------------------------------------------------\n \n mean_pol = list(dict(news_feed_english_df.groupby('dt_time')['sub'].mean()).items())\n mean_pol.sort(key=lambda x: x[0])\n axis = fig.add_subplot(2, 2, 2)\n axis.plot([i[0] for i in mean_pol], [i[1] for i in mean_pol])\n axis.set_title(\"Mean subjectivity over time\")\n #----------------------------------------------------------------------------------------------------\n \n mean_pol = list(dict(news_feed_english_df.groupby('dt_time')['polarity'].std()).items())\n mean_pol.sort(key=lambda x: x[0])\n axis = fig.add_subplot(2, 2, 3)\n axis.plot([i[0] for i in mean_pol], [i[1] for i in mean_pol])\n axis.set_title(\"Std Dev of polarity over time\")\n #----------------------------------------------------------------------------------------------------\n \n mean_pol = list(dict(news_feed_english_df.groupby('dt_time')['sub'].std()).items())\n mean_pol.sort(key=lambda x: x[0])\n axis = fig.add_subplot(2, 2, 4)\n axis.plot([i[0] for i in mean_pol], [i[1] for i in mean_pol])\n axis.set_title(\"Std dev of subjectivity over time\")\n #----------------------------------------------------------------------------------------------------\n \n output = io.BytesIO()\n FigureCanvas(fig).print_png(output)\n return Response(output.getvalue(), mimetype='image/png')\n \n@app.route('/hour-polarities', methods=['GET'])\ndef show_hour_polarities():\n news_feed.headline_text.dropna()\n news_feed_english_df = news_feed[news_feed['language'] == 'english']\n def sent(x):\n t = tb.TextBlob(x)\n return t.sentiment.polarity, t.sentiment.subjectivity\n tqdm.pandas(leave = False, mininterval = 25)\n vals = news_feed_english_df.headline_text.progress_apply(sent)\n\n news_feed_english_df['polarity'] = vals.str[0]\n news_feed_english_df['sub'] = vals.str[1]\n \n fig = Figure()\n mean_pol = list(dict(news_feed_english_df.groupby('dt_hour')['polarity'].mean()).items())\n mean_pol.sort(key=lambda x: x[0])\n axis = fig.add_subplot(2, 2, 1)\n axis.plot([i[0] for i in mean_pol], [i[1] for i in mean_pol])\n axis.set_title(\"Mean polarity over time\")\n #----------------------------------------------------------------------------------------------------\n \n mean_pol = list(dict(news_feed_english_df.groupby('dt_hour')['sub'].mean()).items())\n mean_pol.sort(key=lambda x: x[0])\n axis = fig.add_subplot(2, 2, 2)\n axis.plot([i[0] for i in mean_pol], [i[1] for i in mean_pol])\n axis.set_title(\"Mean subjectivity over time\")\n #----------------------------------------------------------------------------------------------------\n \n mean_pol = list(dict(news_feed_english_df.groupby('dt_hour')['polarity'].std()).items())\n mean_pol.sort(key=lambda x: x[0])\n axis = fig.add_subplot(2, 2, 3)\n axis.plot([i[0] for i in mean_pol], [i[1] for i in mean_pol])\n axis.set_title(\"Std Dev of polarity over time\")\n #----------------------------------------------------------------------------------------------------\n \n mean_pol = list(dict(news_feed_english_df.groupby('dt_hour')['sub'].std()).items())\n mean_pol.sort(key=lambda x: x[0])\n axis = fig.add_subplot(2, 2, 4)\n axis.plot([i[0] for i in mean_pol], [i[1] for i in mean_pol])\n axis.set_title(\"Std dev of subjectivity over time\")\n #----------------------------------------------------------------------------------------------------\n \n output = io.BytesIO()\n FigureCanvas(fig).print_png(output)\n return Response(output.getvalue(), mimetype='image/png')\n \nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"cagataymnzl/Web-Crawling-App","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":11508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"9452850268","text":"# Sample Network\n#\n# (Input Layer)--fully-conn.-->(Single ReLU Layer)--fully-conn.-->(Output Layer)\n#\n# This version only uses numpy\nimport numpy as np\n\nNUM_ITERS = 500\nN = 64 # batch size\nD_in, H, D_out = 1000, 100, 10 # Input, hidden, output layer dimensions\n\n# Creating random data\nx = np.random.randn(N, D_in) # Creates N vectors of dimension D_in with random values.\ny = np.random.randn(N, D_out) # same but with D_out\n\n# Layer weights\nw1 = np.random.randn(D_in, H) # For each of the D_in nodes in the input layer, \n\t\t\t\t\t\t\t # we need H-many weights\nw2 = np.random.randn(H, D_out) # For each of the H nodes in the hidden layer, \n\t\t\t\t\t\t\t # we need D_out-many weights\n\nlearning_rate = 1e-6\nfor t in range(NUM_ITERS):\n\t# Forward Pass\n\th = x.dot(w1)\n\th_relu = np.maximum(h, 0)\n\ty_pred = h_relu.dot(w2)\n\n\t# Loss\n\tloss = np.square(y_pred - y).sum()\n\tprint(t, loss)\n\n\t# Backward Pass - Note, just manually here.\n\tgrad_y_pred = 2.0*(y_pred - y)\n\tgrad_w2 = h_relu.T.dot(grad_y_pred)\n\tgrad_h_relu = grad_y_pred.dot(w2.T)\n\tgrad_h = grad_h_relu.copy()\n\tgrad_h[h < 0] = 0 \t\t\t\t# Coooool\n\tgrad_w1 = x.T.dot(grad_h)\n\n\t# Update weights from gradients\n\tw1 -= learning_rate*grad_w1\n\tw2 -= learning_rate*grad_w2","repo_name":"wpower12/learningtorch","sub_path":"src/tut_numpy.py","file_name":"tut_numpy.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"14330955447","text":"from AllPiece import *\n\nclass identify(__pawn__.pawn,__rook__.rook,__bishop__.bishop,__knight__.knight,__queen__.queen,__king__.king):\n def __init__(self):\n return\n def pieceType(self,InfoList,BoardInfo):\n if (str(InfoList[8]) == \"B_pawn----|\"):\n bpawn=__pawn__.pawn()\n if (bpawn.BlackForward(InfoList,BoardInfo) == True):\n return True\n else:\n return False\n elif (str(InfoList[8]) == \"W_pawn----|\"):\n wpawn=__pawn__.pawn()\n if (wpawn.WhiteForward(InfoList,BoardInfo) == True):\n return True\n else:\n return False\n elif (str (InfoList[10])== \"_rook----|\"):\n rook=__rook__.rook()\n if (rook.move(InfoList,BoardInfo) == True):\n return True\n else:\n return False\n elif (str(InfoList[10])== \"_bishop--|\"):\n bishop=__bishop__.bishop()\n if (bishop.move(InfoList,BoardInfo)== True):\n return True\n else:\n return False\n elif (str(InfoList[10]) == \"_knight--|\"):\n knight=__knight__.knight()\n if (knight.move(InfoList) == True):\n return True\n else:\n return False\n elif (str(InfoList[10]) == \"_queen---|\"):\n queen=__queen__.queen()\n if (queen.move(BoardInfo,InfoList) == True):\n return True\n elif (queen.SlantMove(BoardInfo,InfoList) == True):\n return True\n else:\n return False \n elif (str(InfoList[10]) == \"_king----|\"):\n king=__king__.king()\n if (king.move(InfoList) == True):\n return True\n else:\n return False\n else:\n return False\n\"\"\"\nBoardInfo=['|w-----------|', '|b-----------|', '|b-----------|']\nInfoList=[1, 1, 1, 3, 'w', 'w', 'B', '-', 'B_rook----|', '----------|', '_rook----|', '----------|']\nx=identify()\nprint(x.pieceType(InfoList))\n\"\"\"\n","repo_name":"elimkwan/Python_ChessGame","sub_path":"identify.py","file_name":"identify.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"1656670868","text":"import csv\nfrom datetime import datetime, date\n\nfrom nmat.db import get_db_client\n\n\ndef make_insert(table, attributes):\n values = \", \".join([\"%s\"] * len(attributes))\n attributes = \", \".join(attributes)\n\n sql = f\"\"\"\n INSERT INTO dbo.{table} ({attributes})\n VALUES ({values})\"\"\"\n return sql\n\n\ndef make_select(attributes=\"*\", table=\"Location\", where=None, order=None):\n sql = f\"\"\"\n SELECT {attributes} FROM dbo.{table}\"\"\"\n\n if where:\n sql = f\"{sql} WHERE {where}\"\n if order:\n sql = f\"{sql} ORDER BY {order}\"\n\n return sql\n\n\ndef make_csv(p, records):\n with open(p, \"w\") as wfile:\n writer = csv.writer(wfile)\n header = [str(k) for k in records[0].keys()]\n writer.writerow(header)\n for record in records:\n writer.writerow(record)\n\n\ndef execute_fetch(sql, client=None, verbose=True, fetch=\"fetchall\"):\n if client is None:\n client = get_db_client()\n\n if verbose:\n print(\"executing query================\")\n print(\"sql: \", sql)\n print(\"===============================\")\n\n cursor = client.cursor(as_dict=True)\n cursor.execute(sql)\n func = getattr(cursor, fetch)\n return func()\n\n\ndef execute_insert(sql, values, client=None, verbose=True, dry=True):\n if verbose:\n print(\"executing insert================\")\n print(\"sql: \", sql)\n print(\"values: \", values)\n print(\"===============================\")\n\n cursor = client.cursor()\n cursor.execute(sql, tuple(values))\n if not dry:\n client.commit()\n\n\n# ============= EOF =============================================\n","repo_name":"DataIntegrationGroup/NMAquiferTool","sub_path":"nmat/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"29305098809","text":"#Cajero Automático\nmonto_cajero=1000000\nmonto_usuario=100000\nclave_invalida=0\nbilletes_veinte=20\nbilletes_diez=40\nbilletes_cinco=40\nwhile True:\n usuario=int(input('Ingrese numero de Usuario:'))\n clave=int(input('Ingrese Clave:'))\n if clave==1803 and usuario==10334151:\n monto_retirar=int(input('Ingrese monto a retirar:'))\n if monto_retirar<=100000:\n a=monto_retirar//100000\n print(a)\n b=monto_retirar%100000\n print(b)\n b=b//10000\n print(b)\n c=monto_retirar%10000\n print(c)\n c=c//1000\n print(c)\n if monto_usuario>=monto_retirar and monto_usuario>0:\n print('Se retira:',monto_retirar)\n monto_cajero=monto_cajero-monto_retirar\n monto_usuario=monto_usuario-monto_retirar\n print('saldo cuenta=',monto_usuario)\n print('saldo cajero=',monto_cajero)\n if a==1:\n print('billetes 20000=',5)\n print('billetes de 10000=',0)\n print('billetes 5000=',0)\n elif a==0 and b%2==0 and c==5:\n print('billetes 20000=',b//2)\n print('billetes 10000=',0)\n print('billetes 5000=',1)\n elif a==0 and b%2==0 and c==0:\n print('billetes 20000=',b//2)\n print('billetes 10000=',0)\n print('billetes 5000=',0)\n elif a==0 and b%2!=0:\n print('billetes 20000=',0)\n print('billetes 10000=',b)\n print('billetes 5000=',0)\n elif a==0 and b%2!=0 and c==5:\n print('billetes 20000=',0)\n print('billetes 10000=',b)\n print('billetes 5000=',1)\n \n salir=input('Desea salir(Digite N para continuar):')\n salir=salir.upper()\n if salir==\"N\":\n continue\n else:\n break\n else:\n print('No hay saldo suficiente') \n else:\n print('monto no permitido')\n elif clave!=1803:\n print('clave invalida')\n clave_invalida=clave_invalida+1\n if clave_invalida==3:\n print('tarjeta bloqueada')\n break\n else:\n continue\n else:\n break\n\n ","repo_name":"pabloschwarzenberg/grader","sub_path":"hito1_ej11/hito1_ej11_0f564944db4e29279097841f690b9b32.py","file_name":"hito1_ej11_0f564944db4e29279097841f690b9b32.py","file_ext":"py","file_size_in_byte":2482,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"1341330193","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n# Create your models here.\nclass News(models.Model):\n author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)\n title = models.CharField(max_length=50)\n content = models.CharField(max_length=250)\n created_at = models.TimeField(auto_now=True)\n\n def has_comments(self):\n return Comment.objects.filter(news=self).exists()\n\nclass Comment(models.Model):\n author = models.ForeignKey(User, on_delete=models.CASCADE,null=True)\n content = models.CharField(max_length=500)\n created_at = models.TimeField(auto_now=True)\n news = models.ForeignKey(News, on_delete=models.CASCADE)","repo_name":"nfactorial-python-backend/django-2-yerkennz","sub_path":"media/news/models.py","file_name":"models.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":"73170142010","text":"class Node:\n def __init__(self, name, parent=None):\n self.name = name\n self.parent = parent\n self.folders = []\n self.files = []\n def __str__(self) -> str:\n return f\"Node: {self.name}\"\n def __repr__(self) -> str:\n return f\"{self.name}\"\n\n\ndef searchTree(node, target, answer=None):\n if node.name == target:\n answer=node\n\n for folder in node.folders:\n answer=searchTree(folder, target, answer=answer)\n\n return answer\n\ndef readLines(input_path, cleanup=False):\n with open(input_path, 'r') as f:\n lines = f.readlines()\n\n if cleanup:\n clean_lines = list(map(lambda x: x.strip('\\n'), lines))\n return clean_lines\n else:\n return lines\n\n\ndef processInput(command_list) -> Node:\n root_node = None\n\n for line in command_list:\n if line.startswith(\"$\"):\n if \"cd\" in line:\n current_dir = line.split(' ')[2]\n if root_node:\n current_node = root_node\n if current_node.folders:\n current_node = searchTree(root_node, target=current_dir)\n else:\n current_node = Node(current_dir)\n else:\n root_node = Node(current_dir)\n current_node = root_node\n\n else:\n first, second = line.split(' ')\n if first == \"dir\":\n current_node.folders.append(Node(second, parent=current_node))\n else:\n current_node.files.append({\n \"name\": second,\n \"size\": int(first)\n })\n\n return root_node\n\n\nif __name__ == \"__main__\":\n command_list = readLines(\"test.txt\", cleanup=True)\n root_node = processInput(command_list)\n\n print(root_node)\n print('\\t', root_node.folders)\n for folder in root_node.folders:\n print('\\t', folder)\n print('\\t\\t', folder.folders)\n if folder.folders:\n for next_level_folder in folder.folders:\n print('\\t\\t', next_level_folder)\n print('\\t\\t\\t', next_level_folder.folders)\n print('\\t\\t\\t', next_level_folder.files)\n print('\\t\\t', folder.files)\n print('\\t', root_node.files)\n","repo_name":"AlexMuresan/AdventOfCode","sub_path":"7-NoSpaceLeftOnDevice/solution-part1-half_working.py","file_name":"solution-part1-half_working.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"19689298374","text":"from service import stock_service\nfrom model import stock_model\nimport time\n\n\ndef sync_stocks():\n # 每次数量\n page_size = 1\n # 开始页\n page = 1\n # 数据类型\n type = \"sh_sz\"\n while True:\n stocks = stock_service.get_list(page, page_size, type)\n print(stocks)\n return\n if not len(stocks) > 0:\n break\n\n new_stocks = []\n for stock in stocks:\n new_stocks.append({\n 'code': stock[0],\n 'name': stock[1],\n 'block': block,\n 'price': stock[2] * 0.01,\n 'updown_rate': stock[3] * 0.01,\n 'last_close': stock[4] * 0.01,\n 'open': stock[5] * 0.01,\n 'high': stock[6] * 0.01,\n 'low': stock[7] * 0.01,\n 'volume': stock[8] * 0.01,\n 'amount': stock[10] * 0.01,\n 'exchange_ratio': stock[11] * 0.01,\n 'vibration_ratio': stock[12] * 0.01,\n 'volume_ratio': stock[13] * 0.01\n })\n stock_obj = stock_model.StockModel()\n res = stock_obj.add_all(new_stocks)\n print(res)\n time.sleep(1)\n page += 1\n\n\ndef sync_net_data():\n stock_service.get_data()\n","repo_name":"hcjiange/fund","sub_path":"main/stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"5197582427","text":"hora = input(\"Que horas são? \")\n\nif hora.isdigit():\n hora = int(hora)\n\n# EU usei o and, mas o programa me smplificou para essa forma.\n# Ex: if hora >= 0 and hora <= 11\n\n if 0 <= hora <= 11:\n print(\"Bom Dia!\")\n elif 12 <= hora <= 17:\n print('Boa Tarde!')\n elif 18 <= hora <= 23:\n print('Boa Noite!')\n else:\n print('Insira um horario valido entre as 00h e as 23h.')","repo_name":"kamui-7/Curso-Python","sub_path":"Modulo 1 - Basico/Modulo 1 (Exercicio 2).py","file_name":"Modulo 1 (Exercicio 2).py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"17601917504","text":"\"\"\"\nGiven an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.\n\nFind all the elements that appear twice in this array.\n\"\"\"\n\nclass Solution:\n def findDuplicates(self, nums: List[int]) -> List[int]:\n d = {}\n r = []\n for x in nums:\n if d.get(x):\n d[x] += 1\n else :\n d[x] = 1\n \n for x in d.keys():\n if d[x] == 2:\n r.append(x)\n \n return r\n","repo_name":"VickyDhanwani/Reusable-Scripts","sub_path":"Python Programs/findArrayDuplicates.py","file_name":"findArrayDuplicates.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":"25472349099","text":"numero1 = int(input(\"Digite el primer número: \"))\nnumero2 = int(input(\"Escriba el segundo número: \"))\n\nif numero1 >= numero2:\n print(f\"El primer número debe ser menor que el segundo número.\")\nelse:\n for i in range(numero1, numero2 + 1):\n print(i)\n \n \n \n \n \n \n \n \n ","repo_name":"Estebanprada/TallerCiclos","sub_path":"Ciclo for/punto6.py","file_name":"punto6.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"37544665603","text":"def taskAssignment(k, tasks):\n \"\"\"\n The idea here is to simply pair the tasks that take the longest time with those that take the shortest time, since\n we have exactly k workers, and 2k tasks and the minimum amount of time to complete the 2k tasks is considered to be\n the length of time for the pair max(tasks[i] + tasks[j]) over all i != j. Thus, we want to pair tasks that take\n the longest time with those that take the shortest time to minimize the sum of any given pair (task[i], task[j])\n but we also need to keep track of the indices which we do with the initial dictionary prior to sorting the tasks\n list.\n :param k: number of workers\n :param tasks: list of tasks where task[i] is time taken to complete task[i]\n :return: list of k task assignments for the k workers.\n \"\"\"\n original_indices = {}\n for idx, task in enumerate(tasks):\n original_indices.setdefault(task, []).append(idx)\n\n tasks.sort()\n i, j = 0, len(tasks) - 1\n task_list = []\n while i <= j:\n # ensure to pop out indices because time for tasks need not be unique and we can't reuse index from orig. list\n task1idx, task2idx = original_indices[tasks[i]].pop(), original_indices[tasks[j]].pop()\n task_list.append([task1idx, task2idx])\n i += 1\n j -= 1\n return task_list\n","repo_name":"dalalsunil1986/Interview-Prep","sub_path":"Easy/task_assignment.py","file_name":"task_assignment.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"6380862197","text":"from mimetypes import guess_type\nfrom os import path\n\nfrom googleapiclient.errors import HttpError\nfrom googleapiclient.http import MediaFileUpload\n\nfrom .content_id import GoogleDriveContentId\n\n\nclass GoogleDriveUpload(GoogleDriveContentId):\n\n def upload(self, file):\n\n try:\n file_metadata = {\n 'name': path.basename(file),\n }\n media = MediaFileUpload(file, mimetype=guess_type(file)[0],\n resumable=True)\n # pylint: disable=maybe-no-member\n file = self.service.files().create(body=file_metadata,\n media_body=media,\n fields='id').execute()\n print(F'File with ID: \"{file.get(\"id\")}\" has added to My Drive')\n\n except HttpError as error:\n print(F'An error occurred: {error}')\n file = None\n\n return file.get('id')\n\n def upload_to_folder(self, file, folder_name):\n\n folder_id = self.folder_id(folder_name)\n if not folder_id:\n return\n try:\n file_metadata = {\n 'name': path.basename(file),\n 'parents': [folder_id]\n }\n media = MediaFileUpload(file,\n mimetype=guess_type(file)[0],\n resumable=True)\n # pylint: disable=maybe-no-member\n file = self.service.files().create(body=file_metadata,\n media_body=media,\n fields='id').execute()\n print(f\"\"\"File with ID: \"{file.get(\"id\")}\" has added to the folder\n with ID \"{folder_id}\".\"\"\")\n\n except HttpError as error:\n print(F'An error occurred: {error}')\n file = None\n\n return file.get('id')\n","repo_name":"barbieri97/google_drive_api","sub_path":"actions/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"9766291762","text":"import math\nimport numpy as np\nfrom typing import cast\nimport scipy.special as sp\nimport random\nimport matplotlib.pyplot as plt\n\nplt.style.use('fivethirtyeight')\nplt.grid(b=True)\n\nlambda_0 = 100 # ( lambda 0 )\nr = 45 * 10**(-9) # Receiver radius r\nd = 500 * 10**(-9) # Distance d\nD = 4.256 * 10**(-10) # Diffusion Coefficient D\ndelta_t = 9 * 10**(-6) # Discrete Time Length\nT = 30*delta_t # Slot Length\nL = 5 # Channel length\nT2 = 50*delta_t\n\nSNR = 30\n\ntau = np.arange(20, 121, 5)\n\n\ndef probablity(i, t):\n\n x1 = (d-r)/((4*D*i*t)**(1/2))\n try:\n x2 = (d-r)/((4*D*(i-1)*t)**(1/2))\n return (r/d)*(sp.erfc(x1) - sp.erfc(x2))\n except:\n return (r/d)*(sp.erfc(x1))\n\n\npj = np.array([probablity(i, T) for i in range(1, 7)])\npj2 = np.array([probablity(i, T2) for i in range(1, 7)])\n\nNtx = (2*lambda_0*T*(10**(SNR/10)))/pj[0]\nNtx2 = (2*lambda_0*T2*(10**(SNR/10)))/pj2[0]\n\n\ndef Cj(Ntx, j, t):\n return Ntx*probablity(j+1, t)\n\n\ncj = np.array([Cj(Ntx, j, T) for j in range(0, 6)]) # cj = Ntx*Pj\ncj1 = np.array([Cj(Ntx2, j, T2) for j in range(0, 6)])\n\nsij = np.array([random.randint(0, 1) for _ in range(50)])\n\n\ndef p_BER(i, tau, cj, t):\n\n y = np.flipud(cj[1:])*sij[i-L-1:i-1]\n x = lambda_0*t + y.sum()\n x1 = x + cj[0]\n\n ans = 1/2*(sp.gammaincc(x, math.ceil(tau)) +\n 1 - sp.gammaincc(x1, math.ceil(tau)))\n\n return ans\n\n\ndef BER(tau, cj, t):\n\n ans = (1/(2**L))*(sum([p_BER(i, tau, cj, t)\n for i in range(6, len(sij)-5)]))\n\n return ans\n\n\ndef plot_graph():\n ber = [BER(t, cj, T) for t in tau]\n ber2 = [BER(t, cj1, T2) for t in tau]\n # fig, ax = plt.subplots()\n plt.yscale('log')\n plt.yticks([1, 0.1, 0.01, 0.001, 0])\n\n # print(ber2)\n plt.plot(tau, ber, '.-', label='Solt lenght 30', linewidth=0.5)\n plt.plot(tau, ber2, '.-', label='Solt lenght 50', linewidth=0.5)\n plt.xlabel('Thresold Value')\n plt.ylabel('BER')\n plt.title(\"FIG-3\")\n plt.legend()\n plt.show()\n\n\nplot_graph()\n","repo_name":"dhruv-kabariya/MolecularCommunications","sub_path":"analyticas_model/fig3.py","file_name":"fig3.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"10471938008","text":"import time\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nimport re\n\nimport xlrd\nimport requests\n\nexcelPath = r'C:\\Users\\Danny\\Desktop\\20230827优酷网易云换绑.xls'\n\n# workbook = xlrd.open_workbook('/Users/danny/Desktop/common-documents/工作文档/采购入库/入库的编辑界面.xls') # 打开Excel\n# workbook = xlrd.open_workbook(r'C:\\Users\\Danny\\Desktop\\common-documents\\工作文档\\采购入库\\入库的编辑界面.xls') # 打开Excel\n\nchrome_options = Options()\n# chrome_options.add_argument('--incognito')\n# chrome_options.add_argument('--incognito')\n# chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])\n# chrome_options.add_experimental_option('useAutomationExtension', False)\n# chrome_options.add_argument('blink-settings=imagesEnabled=false')\nchrome_options.add_experimental_option(\"debuggerAddress\", \"127.0.0.1:9222\")\n# chrome_driver = r\"C:\\Users\\Danny\\Downloads\\chromedriver_win32 (1)\\chromedriver.exe\"\n# driver = webdriver.Chrome(options=chrome_options)\ndriver = webdriver.Chrome(options=chrome_options)\n\ndriver.get(\"https://www.youku.com/channel/webhome?spm=a2hcb.collection.app.5~5~5~5~5~5~5~5!2~1~3~A\")\n\n# 切换页面\nwindow_handles = driver.window_handles\ndriver.switch_to.window(window_handles[0])\n\nprint(driver.title)\n\n# 配置\nstartIndex = 1\nauthCodeCh = 10\n\n# 解析excel表格\n\n\nworkbook = xlrd.open_workbook(excelPath) # 打开Excel\nsheet = workbook.sheets()[0]\nrows = sheet.nrows\nprint(f\"一共{rows}个手机号\")\n\nusername = ord('A')\n\npassword = ord('B') - username\n\n# 网络请求\n# proxy = '192.168.3.220:7890'\n# proxies = {\n# 'http': 'http://' + proxy,\n# 'https': 'http://' + proxy\n# }\n\nheaders = {\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36',\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'accept-language': 'zh-CN,zh;q=0.9',\n 'cookie': ''\n # 'cookie':'rr=https%3A%2F%2Fcn1.at101.design%2F; iadult=1; hello=1; __cf_bm=p5gOpquFCoj5a8TQG4EXkJgz3Ex7FnsYEfEnocDLOvQ-1672239337-0-Aald4rPN3hah3kmMughmjJnSoAXumWxycfq63F5ZGSO30pHcwtAbqaAZLHGXuYc6q8I0nZgdiJR75WSZ20zsF7Fd02vMkSA7GKGU+aEdw5fSL4rGkP3QLsGEgxf04R5AkhrkKQTrbTGgNWCpGXKzTss=; XSRF-TOKEN=eyJpdiI6ImZObDlvclwvZjN4SnhtMHNyb2NkcTNBPT0iLCJ2YWx1ZSI6InlqNUp4V3dSN2ZucDZYN2h0OExBT2NBMlVFZVpVWXNSUTZuR1NvbVMwMlZhVVJJTDhLNTBnTHIrQUFrNTJJVDIiLCJtYWMiOiI2OGFmNDM5NzE5MDc5ZGFjMTJmODJmYjZkMTVkNWViOGI0YWUyN2JlZjUwZjg2YzEyOTVjZTVjNmZkNmE5NTYzIn0%3D; miao_ss=eyJpdiI6IlZUczhoMFJjN2VhUlRFYis1NXBYZ3c9PSIsInZhbHVlIjoiR2RWRDZncElnemNZa0poTnhGbHNcL1ZoTmlnVDhhNndYcVgxSHFTMCtcL3VnbUVZTXAyWGtCclloaURQR2dwMXVaIiwibWFjIjoiZjBlM2QzZDRjM2FmNzhmZjBmNjliMzgzNGI4NTZiZWEzZmY2MDg5YmJhZDBmNjI5NzJmYzcxMDc0OWNmN2U5YyJ9'\n}\n\n\ndef requestNet(url, proxies=None):\n return requests.get(url, headers=headers, proxies=proxies, verify=False)\n\n\n# 验证新手机使用\ndef getNewPhoneAuthCode(phone):\n print(f'等待查询{phone}的验证码')\n time.sleep(10)\n authcodecc = ''\n for i in range(authCodeCh):\n time.sleep(1)\n response = requestNet('http://sms.szfangmm.com:3000/api/smslist?token=cSuZgpUdwXxqWDCypT7kWB')\n jsons = response.json()\n for json in jsons:\n content = json['content']\n if ('优酷土豆' in content) & (phone[-4:] == json['simnum'][-4:]):\n # pattern = re.compile(r'[1-9]\\d*', )\n # authcodecc = pattern.search(content)\n authcodecc = ('0000'+str(re.search(r'[1-9]\\d*', content).group()))[-6:]\n print('查找到最近验证码:' + authcodecc)\n\n return authcodecc\n if authcodecc == '':\n return input('请手动输入验证码:')\n\n\n# 验证身份使用\ndef getYanzhengAuthCode(phone):\n print(f'等待查询{phone}的验证码')\n time.sleep(8)\n authcodecc = ''\n for i in range(authCodeCh):\n time.sleep(1)\n response = requestNet('http://sms.szfangmm.com:3000/api/smslist?token=ATCd4fakvTSzzovJfjcRGJ')\n jsons = response.json()\n for json in jsons:\n content = json['content']\n if ('优酷土豆】您正在进行修改手机' in content) & (phone[-4:] == json['simnum'][-4:]):\n authcodecc = ('0000'+str(re.search(r'[1-9]\\d*', content).group()))[-6:]\n print('查找到最近验证码:' + authcodecc)\n return authcodecc\n if authcodecc == '':\n return input('请手动输入验证码:')\n\n\n# 登录使用\ndef getAuthCode(phone):\n print(f'等待查询{phone}的验证码')\n time.sleep(8)\n authcodecc = ''\n for i in range(authCodeCh):\n time.sleep(1)\n response = requestNet('http://sms.szfangmm.com:3000/api/smslist?token=ATCd4fakvTSzzovJfjcRGJ')\n jsons = response.json()\n for json in jsons:\n content = json['content']\n\n if ('优酷土豆' in content) & (phone[-4:] == json['simnum'][-4:]):\n authcodecc = ('0000'+str(re.search(r'[1-9]\\d*', content).group()))[-6:]\n print('查找到最近验证码:' + authcodecc)\n return authcodecc\n if authcodecc == '':\n return input('请手动输入验证码:')\n\n\ndef loginUsernameOfAuthCode(usernameStr):\n window_handles = driver.window_handles\n driver.switch_to.window(window_handles[0])\n # 打开登录\n img = driver.find_element(By.CLASS_NAME, \"usercenter_avatar_img \")\n img.click()\n\n iframe = driver.find_element(By.ID, 'alibaba-login-box')\n driver.switch_to.frame(iframe)\n\n # amimadenglu = driver.find_element(By.CLASS_NAME, \"yk-login-title\")\n # amimadenglu = driver.find_element(By.XPATH, \"//a[@class='yk-login-title']\")\n # amimadenglu.click()\n\n driver.find_element(By.ID, \"fm-sms-login-id\").send_keys(usernameStr)\n\n # time.sleep(1)\n inputC = driver.find_element(By.ID, \"fm-agreement-checkbox\")\n driver.execute_script('arguments[0].click()', inputC)\n # inputCec = driver.find_element(By.XPATH, \"//label[@class='fm-agreement-text']\").value_of_css_property('::after')\n # driver.find_element(By.CLASS_NAME,\"fm-agreement-text\").click()\n\n # 点击发送验证码\n driver.find_element(By.CLASS_NAME, \"send-btn-link\").click()\n # 获取验证码输入\n authcodestr = getAuthCode(usernameStr)\n driver.find_element(By.ID, 'fm-smscode').send_keys(authcodestr)\n\n driver.find_element(By.CLASS_NAME, \"fm-btn\").click()\n print(f\"验证码登陆成功---{usernameStr}\")\n\n\ndef loginUsernameAndPassword(usernameStr, passwordStr):\n window_handles = driver.window_handles\n driver.switch_to.window(window_handles[0])\n # 打开登录\n img = driver.find_element(By.CLASS_NAME, \"usercenter_avatar_img \")\n img.click()\n\n iframe = driver.find_element(By.ID, 'alibaba-login-box')\n driver.switch_to.frame(iframe)\n\n # amimadenglu = driver.find_element(By.CLASS_NAME, \"yk-login-title\")\n amimadenglu = driver.find_element(By.XPATH, \"//a[@class='yk-login-title']\")\n amimadenglu.click()\n\n driver.find_element(By.ID, \"fm-login-id\").send_keys(usernameStr)\n driver.find_element(By.ID, \"fm-login-password\").send_keys(passwordStr)\n # time.sleep(1)\n inputC = driver.find_element(By.ID, \"fm-agreement-checkbox\")\n driver.execute_script('arguments[0].click()', inputC)\n # inputCec = driver.find_element(By.XPATH, \"//label[@class='fm-agreement-text']\").value_of_css_property('::after')\n # driver.find_element(By.CLASS_NAME,\"fm-agreement-text\").click()\n driver.find_element(By.CLASS_NAME, \"fm-btn\").click()\n print(f\"密码登陆成功---{usernameStr}\")\n\n\ndef startTask(startIndex):\n\n n = 0\n\n for i in range(startIndex - 1, sheet.nrows):\n\n driver.delete_all_cookies()\n driver.get(\"https://www.youku.com/channel/webhome?spm=a2hcb.collection.app.5~5~5~5~5~5~5~5!2~1~3~A\")\n driver.refresh()\n\n usernameStr = str(int(sheet.cell(i, 0).value))\n # passwordStr = sheet.cell(i, 1).value\n # loginUsernameAndPassword(i)\n print(f'第{i + 1}行----手机号:{usernameStr}开始换绑')\n\n loginUsernameOfAuthCode(usernameStr)\n\n # driver.switch_to.default_content()\n\n time.sleep(1)\n\n window_handles = driver.window_handles\n driver.switch_to.window(window_handles[0])\n\n print(\"打开个人信息\")\n img = driver.find_element(By.CLASS_NAME, \"usercenter_avatar_img \")\n img.click()\n # time.sleep(2)\n\n driver.close()\n\n # time.sleep(2)\n time.sleep(0.5)\n window_handles = driver.window_handles\n driver.switch_to.window(window_handles[0])\n WebDriverWait(driver, 20).until_not(EC.visibility_of_element_located((By.ID, 'nocaptcha')))\n\n spans = driver.find_elements(By.TAG_NAME, \"span\")\n\n # WebDriverWait(driver,10,0.1).until(EC.visibility_of_element_located((spans)))\n\n for span in spans:\n if span.text == '个人设置':\n span.click()\n print('个人设置点击')\n break\n aaas = driver.find_elements(By.TAG_NAME, \"a\")\n for span in aaas:\n if span.text == '账号设置':\n span.click()\n print('账号设置点击')\n break\n\n driver.close()\n time.sleep(0.5)\n window_handles = driver.window_handles\n driver.switch_to.window(window_handles[0])\n ass = driver.find_elements(By.CLASS_NAME, \"btn-link\")\n ass[2].click()\n try:\n iframe = driver.find_element(By.ID, 'iframe1')\n\n driver.switch_to.frame(iframe)\n\n try:\n print('等待刷新验证码')\n WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, 'J_GetCode')))\n except:\n print('没有找到元素')\n finally:\n # time.sleep(5)\n driver.find_element(By.ID, \"J_GetCode\").click()\n # yanzhengma111 = input('请输入验证码按回车结束:')\n authcodeOld = getYanzhengAuthCode(usernameStr)\n driver.find_element(By.ID, \"J_Phone_Checkcode\").send_keys(authcodeOld)\n time.sleep(0.5)\n driver.find_element(By.ID, \"submitBtn\").click()\n except:\n print('已经验证身份')\n exit()\n phoneStr = input('请输入手机号:')\n driver.find_element(By.ID, \"J_Mobile\").send_keys(phoneStr)\n time.sleep(0.3)\n driver.find_element(By.ID, \"J_GetCode\").click()\n\n # authcodeNew = getNewPhoneAuthCode(phoneStr)\n authcodeNew = input('请输入验证码:')\n driver.find_element(By.ID, \"J_Phone_Checkcode\").send_keys(authcodeNew)\n time.sleep(0.3)\n inputqueding = driver.find_element(By.XPATH, \"//input[@class='ui-button ui-button-lorange']\")\n inputqueding.click()\n print(f'{usernameStr}换绑为{phoneStr}成功!!!')\n print()\n print()\n exit()\n # n+=1\n # if n ==6:\n # driver.close()\n # exit()\n time.sleep(3)\n\n\nif __name__ == '__main__':\n\n index = input('从第几行开始:')\n startTask(int(index))\n","repo_name":"932755233/FormatID","sub_path":"喜马拉雅自动工具/自动登录优酷换绑手机.py","file_name":"自动登录优酷换绑手机.py","file_ext":"py","file_size_in_byte":11518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"73400163128","text":"\"\"\"Constants.\"\"\"\n\nimport configparser\nimport re\nfrom os import pardir\nfrom os.path import abspath, dirname, join\nfrom pathlib import Path\n\n__version__ = \"0.1.0\"\n# import pathlib\n\n# HERE = pathlib.Path(__file__).parent.resolve()\n\nDATA_DIR_NAME = \"data\"\nTERMS_DIR_NAME = \"terms\"\nSERIAL_DIR_NAME = \"serialized\"\nINPUT_DIR_NAME = \"input\"\nOUTPUT_DIR_NAME = \"output\"\nIMAGES_DIR_NAME = \"images\"\n\nPARENT_DIR = abspath(join(dirname(__file__), pardir))\nDATA_DIR = join(PARENT_DIR, DATA_DIR_NAME)\nIMAGE_DIR = join(DATA_DIR, IMAGES_DIR_NAME)\nOUTPUT_DIR = join(DATA_DIR, OUTPUT_DIR_NAME)\nSERIAL_DIR = join(DATA_DIR, SERIAL_DIR_NAME)\nONTO_TERMS_FILENAME = \"onto_termlist.tsv\"\nTERMS_PICKLED_FILENAME = \"terms.pickle\"\nPATTERN_LIST_PICKLED_FILENAME = \"patterns.pickle\"\nPHRASE_MATCHER_PICKLED_FILENAME = \"phrase_matcher.pickle\"\nSETTINGS_FILENAME = \"settings.ini\"\nSTOPWORDS_FILENAME = \"stopWords.txt\"\n\nSETTINGS_FILE_PATH = join(dirname(__file__), SETTINGS_FILENAME)\n\n\ndef _get_config(param: str, settings_file: Path = SETTINGS_FILE_PATH):\n read_config = configparser.ConfigParser()\n read_config.read(settings_file)\n main_section = dict(read_config.items(\"Main\"))\n if param == \"termlist\":\n return [\n v.split(\"/\")[-1]\n for k, v in main_section.items()\n if param in k and re.search(r\"\\d\", k)\n ]\n else:\n return [v.replace(\"data/\", \"\") for k, v in main_section.items() if param in k]\n","repo_name":"monarch-initiative/ontorunner","sub_path":"ontorunner/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"77"} +{"seq_id":"25004765162","text":"from flask import Flask, jsonify, request\nfrom datetime import date\nfrom datetime import datetime, timedelta\nimport requests\n\n\nurl_canteen = str('https://fenix.tecnico.ulisboa.pt/api/fenix/v1/canteen')\nurl_canteen_day = \"https://fenix.tecnico.ulisboa.pt/api/fenix/v1/canteen?day=\"\n\nnamespace = {'logs': 'http://127.0.0.1:5004/'}\n\ndef list_days_of_week():\n global days_of_week\n day = date.today().strftime(\"%d/%m/%Y\")\n dt = datetime.strptime(day, '%d/%m/%Y')\n start = dt - timedelta(days=dt.weekday())\n if start.strftime('%d/%m/%Y')[0:1] == '0':\n days_of_week.append(start.strftime('%d/%m/%Y')[1:])\n for i in range(4):\n days_of_week.append((start + timedelta(days=i + 1)).strftime('%d/%m/%Y')[1:])\n else :\n days_of_week.append(start.strftime('%d/%m/%Y'))\n for i in range(4):\n days_of_week.append((start + timedelta(days=i + 1)).strftime('%d/%m/%Y'))\n\n\nweekly_meal = {} # global list\ndays_of_week = []\nlist_days_of_week()\n\napp = Flask(__name__)\n\n@app.before_request\ndef before_request():\n requests.post(namespace['logs'] + 'addlog', json={'request': request.url,\n 'user': request.host,\n 'timestamp': datetime.now().isoformat()})\n@app.route('/canteen/', methods=['GET'])\n@app.route('/canteen', methods=['GET'])\ndef get_weekly_meal():\n global weekly_meal\n aux = {}\n #corrects to single digit day\n if date.today().strftime(\"%d/%m/%Y\")[0:1] == '0':\n date_today = date.today().strftime(\"%d/%m/%Y\")[1:]\n else:\n date_today = date.today().strftime(\"%d/%m/%Y\")\n # if data is cached\n if date_today in weekly_meal.keys():\n for item in days_of_week:\n try:\n aux[item] = weekly_meal[item]\n except KeyError:\n # This most likely means the menu doesn't have 5 days. getting information from FENIX again:\n aux = {}\n data = requests.get(url_canteen)\n for item2 in data.json():\n weekly_meal[item2['day']] = item2['meal']\n aux[item2['day']] = item2['meal']\n return jsonify(aux)\n\n return jsonify(aux)\n else:\n data = requests.get(url_canteen)\n if data.text == '[]':\n return jsonify({'errorCode': 404, 'message': 'Route not found'})\n for item in data.json():\n weekly_meal[item['day']] = item['meal']\n aux[item['day']] = item['meal']\n return jsonify(aux)\n\n\n@app.route('/canteen/', methods=['GET'])\ndef check_meal(day):\n global weekly_meal\n aux = {}\n\n if day[0:1] == '0':\n day = day[1:]\n if day[2:3] == '0':\n day = day[0:2]+day[3:]\n if date in weekly_meal.keys():\n aux[day] = weekly_meal[day]\n return jsonify(aux)\n else:\n data = requests.get(url_canteen_day + day)\n if data.text == '[]':\n return jsonify({'errorCode': 404, 'message': 'Route not found'})\n for item in data.json():\n weekly_meal[item['day']] = item['meal']\n try:\n aux[day] = weekly_meal[day]\n except KeyError:\n return jsonify({'errorCode': 404, 'message': 'Day not in system'})\n return jsonify(aux)\n\n\nif __name__ == '__main__':\n list_days_of_week()\n app.run(port=5001)\n","repo_name":"goncarvalho/Asint-Rest","sub_path":"canteen.py","file_name":"canteen.py","file_ext":"py","file_size_in_byte":3402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"31318679478","text":"import bpy\nfrom math import radians, degrees\n\nclass MPH_OT_adjust_rotation(bpy.types.Operator):\n \"\"\"Adjusts the rotation of the head by the specified amount\"\"\"\n bl_idname = \"mph.adjust_rotation\"\n bl_label = \"Adjust Rotation\"\n bl_options = {'REGISTER', 'UNDO'}\n\n rotation: bpy.props.FloatProperty(default = 0.0)\n\n @classmethod\n def poll(cls, context):\n if not context.active_object:\n return False\n test1 = True if 'Inner Skin' in context.active_object.name else False\n test2 = True if 'Outer Skin' in context.active_object.name else False\n test3 = True if context.object.mode == 'OBJECT' else False\n return ((test1 or test2) and test3)\n\n def execute(self, context):\n # get head iteration\n iteration = context.active_object.name[10:]\n\n inner_skin = bpy.data.objects['Inner Skin' + str(iteration)]\n outer_skin = bpy.data.objects['Outer Skin' + str(iteration)]\n\n inner_skin.rotation_euler.z += radians(self.rotation)\n outer_skin.rotation_euler.z += radians(self.rotation)\n\n if context.active_object.head_properties.cardinal_rotation == 'NONE':\n pass\n else:\n rotation = round(degrees(inner_skin.rotation_euler.z))\n \n # clamp values\n while rotation < 0:\n rotation += 360\n while rotation > 360:\n rotation -= 360\n \n # check if aligned cardinally\n if rotation == 0:\n inner_skin.head_properties.cardinal_rotation = 'EAST'\n outer_skin.head_properties.cardinal_rotation = 'EAST'\n elif rotation == 90:\n inner_skin.head_properties.cardinal_rotation = 'SOUTH'\n outer_skin.head_properties.cardinal_rotation = 'SOUTH'\n elif rotation == 180:\n inner_skin.head_properties.cardinal_rotation = 'WEST'\n outer_skin.head_properties.cardinal_rotation = 'WEST'\n elif rotation == 270:\n inner_skin.head_properties.cardinal_rotation = 'NORTH'\n outer_skin.head_properties.cardinal_rotation = 'NORTH'\n else:\n inner_skin.head_properties.cardinal_rotation = 'OTHER'\n outer_skin.head_properties.cardinal_rotation = 'OTHER'\n\n return {'FINISHED'}\n\nclass MPH_OT_set_rotation(bpy.types.Operator):\n \"\"\"Sets the rotation of the head to the specified amount\"\"\"\n bl_idname = 'mph.set_rotation'\n bl_label = 'Set Rotation'\n bl_options = {'REGISTER', 'UNDO'}\n\n rotation: bpy.props.FloatProperty(default = 0.0)\n\n @classmethod\n def poll(cls, context):\n if not context.active_object:\n return False\n test1 = True if 'Inner Skin' in context.active_object.name else False\n test2 = True if 'Outer Skin' in context.active_object.name else False\n test3 = True if context.object.mode == 'OBJECT' else False\n return ((test1 or test2) and test3)\n\n def execute(self, context):\n # get head iteration\n iteration = context.active_object.name[10:]\n\n inner_skin = bpy.data.objects['Inner Skin' + str(iteration)]\n outer_skin = bpy.data.objects['Outer Skin' + str(iteration)]\n\n inner_skin.rotation_euler.z = radians(self.rotation)\n\nclass MPH_OT_set_cardinal_rotation(bpy.types.Operator):\n \"\"\"Sets the cardinal rotation of the head to the cardinal_rotation property\"\"\"\n bl_idname = 'mph.set_cardinal_rotation'\n bl_label = 'Set Cardinal Rotation'\n bl_options = {'REGISTER', 'UNDO'}\n\n @classmethod\n def poll(cls, context):\n if not context.active_object:\n return False\n test1 = True if 'Inner Skin' in context.active_object.name else False\n test2 = True if 'Outer Skin' in context.active_object.name else False\n test3 = True if context.object.mode == 'OBJECT' else False\n return ((test1 or test2) and test3)\n\n def execute(self, context):\n # get head iteration\n iteration = context.active_object.name[10:]\n\n if 'Inner Skin' in context.active_object.name:\n obj_name = 'Inner Skin' + iteration\n update_obj = bpy.data.objects['Outer Skin' + iteration]\n if 'Outer Skin' in context.active_object.name:\n obj_name = 'Outer Skin' + iteration\n update_obj = bpy.data.objects['Inner Skin' + iteration]\n \n obj = bpy.data.objects[obj_name]\n\n rotation = obj.head_properties.cardinal_rotation\n if rotation != 'NONE':\n if rotation == 'EAST':\n rotation_amount = 0\n elif rotation == 'SOUTH':\n rotation_amount = 90\n elif rotation == 'WEST':\n rotation_amount = 180\n elif rotation == 'NORTH':\n rotation_amount = 270\n elif rotation == 'OTHER':\n rotation_amount = degrees(obj.rotation_euler.z)\n else:\n return {'CANCELLED'}\n \n obj.lock_rotation = (True, True, True)\n obj.rotation_euler.z = radians(rotation_amount)\n else:\n obj.lock_rotation = (False, False, False)\n \n if update_obj.head_properties.cardinal_rotation != rotation:\n bpy.context.view_layer.objects.active = update_obj\n update_obj.head_properties.cardinal_rotation = rotation\n else:\n bpy.context.view_layer.objects.active = update_obj\n return {'FINISHED'}\n \n def run_update(self, context):\n # this way, the function called (this one) returns none\n bpy.ops.mph.set_cardinal_rotation()","repo_name":"TheWeirdSquid/Minecraft-Player-Head-Tools","sub_path":"MPH_rotation.py","file_name":"MPH_rotation.py","file_ext":"py","file_size_in_byte":5666,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"} +{"seq_id":"40044065645","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nimport sys, os\nimport requests\n\ndef upload(fileName):\n url = 'http://127.0.0.1:3000'\n files = {fileName: open(fileName, 'rb')}\n return requests.post(url=url, files=files)\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n print(\"Usage: %s bitstream.bit\" % sys.argv[0])\n sys.exit(1)\n bitstream = sys.argv[1]\n try:\n res = upload(bitstream)\n print(\"Status code: %d\" % res.status_code)\n if res.status_code != 200:\n sys.exit(1)\n except Exception as e:\n print(\"Can't upload %s\" % bitstream)\n print(e)\n sys.exit(1)\n","repo_name":"sergpolkin/xilinx-upload-server","sub_path":"upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"3507525255","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom selenium.common.exceptions import (StaleElementReferenceException,\n MoveTargetOutOfBoundsException,\n WebDriverException)\nfrom selenium.common import exceptions as selenium_exceptions\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import Select\n\n\nclass seleniumBase():\n def __init__(self):\n self.driver = None\n self.__last_url_of_delayed_assert = \"data:,\"\n self.__last_page_load_url = \"data:,\"\n self.EXTREME_TIMEOUT = 30\n\n def open(self, url):\n self.__last_page_load_url = None\n self.driver.get(url)\n if True:\n self.wait_for_ready_state_complete()\n self.__demo_mode_pause_if_active()\n\n def open_url(self):\n pass","repo_name":"rhan812/pytest-yamltest","sub_path":"autotest/web/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"77"} +{"seq_id":"21303077795","text":"from setuptools import find_packages, setup\nfrom typing import List\n\nvar = \"-e.\"\n\ndef get_requirements(filepath:str) -> List[str]:\n\n requirements = []\n with open(filepath) as f:\n requirements = f.readlines()\n requirements = [req.replace(\"/n\", \"\") for req in requirements]\n\n if var in requirements:\n requirements.remove(var)\n\n return requirements\n\n\nsetup(\n name=\"Diamond_Price_Predition\",\n version=\"0.0.1\",\n author=\"Nishchal Jinturkar\",\n author_email=\"nishchaljinturkar30@gmail.com\",\n install_requires=get_requirements(\"requirements.txt\"),\n packages=find_packages()\n)","repo_name":"Nishchal30/End_to_End_Regression_Project","sub_path":"setup.py","file_name":"setup.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":"12397719770","text":"# importing packages\nimport pandas as pd\nimport pickle\nimport json\nimport argparse\nfrom IPython.display import display\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Define module')\n parser.add_argument('--module', help='1 or 2', required=True)\n parser.add_argument('--file_path', help='file path for test data')\n parser.set_defaults(file_path='data/online_shoppers_intention.csv')\n \n args = parser.parse_args()\n print(args.module)\n print(args.file_path)\n \n # importing test data\n df = pd.read_csv(args.file_path)\n\n # to drop revenus column if using default file\n if args.file_path == 'data/online_shoppers_intention.csv':\n df = df.drop(columns=['Revenue'])\n \n # loader transformer\n loaded_transformer = pickle.load(open('trained_models/transformer.sav', 'rb'))\n # reading config file\n transformer_config = open('trained_models/transformer.json',)\n all_cols = json.load(transformer_config)['columns']\n\n test_df = loaded_transformer.transform(df)\n test_df = pd.DataFrame(test_df, columns = all_cols)\n\n if args.module == '1':\n # reading config file\n config_file = open('trained_models/stay_duration_pred.json',)\n # load trained model\n loaded_model = pickle.load(open('trained_models/stay_duration_pred.sav', 'rb'))\n \n elif args.module == '2':\n # reading config file\n config_file = open('trained_models/transaction_pred.json',)\n # load trained model\n loaded_model = pickle.load(open('trained_models/transaction_pred.sav', 'rb'))\n \n else:\n raise ValueError('No such module.')\n\n data = json.load(config_file)\n columns = data['columns']\n result = pd.DataFrame({'results':loaded_model.predict(test_df[columns])})\n\n display(result)\n result.to_csv('result_{}'.format(args.module))","repo_name":"gracecms/dsa3101","sub_path":"prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"27578134894","text":"from __future__ import annotations\n\nimport dataclasses\n\nimport ddd\n\n\n@dataclasses.dataclass\nclass EmailSetEvent(ddd.AbstractEvent):\n user_id: str | None = None\n new_email: str | None = None\n old_email: str | None = None\n\n @property\n def name(self) -> str:\n return type(self).__name__\n\n","repo_name":"vklap/py_ddd_framework","sub_path":"demo/domain/command_model/email_set_event.py","file_name":"email_set_event.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"77"} +{"seq_id":"14927904110","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n初始化parser.\n\n设置以下内容:\n1. event schema loader\n2. 配置式parser列表\n3. 手工parser目录\n\"\"\"\n\nimport requests\nimport json\n\n_fn_load_event_schemas = None\n_fn_load_parsers = None\n\n\ndef init_parser(fn_load_event_schemas, fn_load_parsers):\n \"\"\"\n 初始化parser\n\n :param fn_load_event_schemas:\n :param fn_load_parsers:\n :return:\n \"\"\"\n global _fn_load_event_schemas\n global _fn_load_parsers\n\n _fn_load_event_schemas = fn_load_event_schemas\n _fn_load_parsers = fn_load_parsers\n\n\ndef get_fn_load_event_schemas():\n \"\"\"\n 获取event schema生成器,该回调返回evnet schema列表{eventname:{fieldname:fieldtype}}\n :return:\n \"\"\"\n return _fn_load_event_schemas\n\n\ndef get_fn_load_parsers():\n return _fn_load_parsers\n\n\n# some helper functions for building functions\ndef build_fn_load_event_schemas_on_web(event_url, auth):\n def result_fn():\n response = requests.get(event_url, params={\"auth\": auth})\n\n new_event_schema_dictionary = {}\n if response.status_code == 200:\n events = json.loads(response.text)[\"values\"]\n for event in events:\n properties = {p[\"name\"]: p[\"type\"] for p in event[\"properties\"]}\n new_event_schema_dictionary[event[\"name\"]] = properties\n\n if new_event_schema_dictionary:\n return new_event_schema_dictionary\n else:\n raise RuntimeError(u\"无法获取日志定义配置\")\n\n return result_fn\n\n\ndef build_fn_load_event_schemas_on_file(file_path):\n def result_fn():\n with file(file_path) as input:\n content = input.read()\n events = json.loads(content)[\"values\"]\n\n new_event_schema_dictionary = dict()\n for event in events:\n properties = {p[\"name\"]: p[\"type\"] for p in event[\"properties\"]}\n new_event_schema_dictionary[event[\"name\"]] = properties\n\n if new_event_schema_dictionary:\n return new_event_schema_dictionary\n else:\n raise RuntimeError(u\"无法获取日志定义配置\")\n\n return result_fn\n\n\ndef build_fn_load_event_schemas_on_dict(dict_data_container):\n def result_fn():\n content = dict_data_container.get()\n events = json.loads(content)[\"values\"]\n\n new_event_schema_dictionary = dict()\n for event in events:\n properties = {p[\"name\"]: p[\"type\"] for p in event[\"properties\"]}\n new_event_schema_dictionary[event[\"name\"]] = properties\n\n if new_event_schema_dictionary:\n return new_event_schema_dictionary\n else:\n raise RuntimeError(u\"无法获取日志定义配置\")\n\n return result_fn\n\n\ndef build_fn_load_parsers_on_web(parser_url, auth):\n def result_fn():\n response = requests.get(parser_url, params={\"auth\": auth})\n\n parsers = []\n if response.status_code == 200:\n parsers = json.loads(response.text)[\"values\"]\n\n if parsers:\n parsers = [p for p in parsers if p[\"status\"]]\n return parsers\n\n raise RuntimeError(u\"无法获取日志解析配置\")\n\n return result_fn\n\n\ndef build_fn_load_parsers_on_file(file_path):\n def result_fn():\n with file(file_path) as input:\n content = input.read()\n\n parsers = []\n parsers = json.loads(content)[\"values\"]\n\n if parsers:\n parsers = [p for p in parsers if p[\"status\"]]\n return parsers\n\n raise RuntimeError(u\"无法获取日志解析配置\")\n\n return result_fn\n","repo_name":"threathunterX/python_lib","sub_path":"nebula_parser/nebula_parser/parser_initializer.py","file_name":"parser_initializer.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"73024099127","text":"\"\"\"\nCreates a report about the inputs and outputs of a cwl workflow.\nNOTE: Copied from lando repo. Original History:\nhttps://github.com/Duke-GCB/lando/blob/075b08e9ae1801fe25ddeeb49ef43a0c968a5bcf/lando/worker/cwlreport.py\n\"\"\"\n\nimport os\nimport yaml\nimport jinja2\nimport humanfriendly\nimport markdown\nimport codecs\n\nREADME_TEMPLATE = \"\"\"\n# Summary\n\nJob: {{ workflow.documentation }}\nJob Id: {{ job.id }}\nStarted: {{ job.started }}\nFinished: {{ job.finished }}\nRun time: {{ job.run_time }}\nOutput: {{ job.num_output_files }} files ({{ job.total_file_size_str }})\n\"\"\"\n\n\nclass BaseReport(object):\n \"\"\"\n Base report class that assumes subclass will implement render_markdown() that returns markdown format\n \"\"\"\n def __init__(self, template_str):\n self.template = jinja2.Template(template_str)\n\n def render_markdown(self):\n \"\"\"\n This method should be overridden in a subclass\n :return: str: report contents\n \"\"\"\n return ''\n\n def render_html(self):\n \"\"\"\n Return README content in html format\n :return: str: report contents\n \"\"\"\n return markdown.markdown(self.render_markdown())\n\n\nclass ReadmeReport(BaseReport):\n \"\"\"\n Report detailing inputs and outputs of a cwl workflow that has been run.\n \"\"\"\n def __init__(self, workflow_info, job_data, template_str=README_TEMPLATE):\n \"\"\"\n :param workflow_info: WorkflowInfo: info derived from cwl input/output files\n :param job_data: dict: data used in report from non-cwl sources\n :param template_str: str: template to use for rendering\n \"\"\"\n super(ReadmeReport, self).__init__(template_str)\n self.workflow_info = workflow_info\n self.job_data = job_data\n\n def render_markdown(self):\n \"\"\"\n Return README content in markdown format\n :return: str: report contents\n \"\"\"\n return self.template.render(workflow=self.workflow_info, job=self.job_data)\n\n\ndef get_documentation_str(node):\n \"\"\"\n Retrieve the documentation information from a cwl formatted dictionary.\n If there is no doc tag return the id value.\n :param node: dict: cwl dictionary\n :return: str: documentation description or id\n \"\"\"\n documentation = node.get(\"doc\")\n if not documentation:\n documentation = node.get(\"id\")\n return documentation\n\n\ndef create_workflow_info(local_workflow_path):\n \"\"\"\n Create a workflow_info filling in data based on a cwl workflow.\n :param local_workflow_path: str: packed cwl workflow\n :return: WorkflowInfo\n \"\"\"\n doc = parse_yaml_or_json(local_workflow_path)\n cwl_version = doc.get('cwlVersion')\n if doc.get(\"class\") == 'Workflow':\n return WorkflowInfo(local_workflow_path, cwl_version, doc)\n else:\n graph = doc.get(\"$graph\")\n if graph:\n for node in graph:\n if node.get(\"id\") == \"#main\":\n return WorkflowInfo(local_workflow_path, cwl_version, node)\n if doc.get(\"id\") == \"#main\":\n return WorkflowInfo(local_workflow_path, cwl_version, doc)\n raise ValueError(\"Unable to read {} as CWL\".format(local_workflow_path))\n\n\ndef upconvert_to_list(list_or_dict):\n \"\"\"\n Packed CWL workflow inputs/outputs are structured as lists of dicts (e.g.\n [{'id': 'input_file', 'type': 'File'},...]). Unpacked workflows may have\n dicts (e.g. {'input_file': 'File'}. This function converts the dicts into\n lists of dicts or returns the list\n\n :param list_or_dict:\n :return:\n \"\"\"\n if isinstance(list_or_dict, list):\n return list_or_dict\n elif isinstance(list_or_dict, dict):\n return [{'id': k, 'type': v} for k,v in list_or_dict.items()]\n else:\n raise ValueError('Only list or dict are supported, not {}', type(list_or_dict))\n\n\nclass WorkflowInfo(object):\n \"\"\"\n Information about the workflow derived from cwl input/output files.\n \"\"\"\n def __init__(self, workflow_filename, cwl_version, workflow_node):\n \"\"\"\n :param workflow_filename: str: path to a packed cwl workflow\n :param cwl_version: str: version of cwl used in workflow_filename\n :param workflow_node: dict: cwl dictionary inside workflow_filename\n \"\"\"\n self.workflow_filename = workflow_filename\n self.job_order_filename = None\n self.job_output_filename = None\n self.cwl_version = cwl_version\n self.documentation = get_documentation_str(workflow_node)\n self.input_params = []\n self.output_data = []\n for input_param in upconvert_to_list(workflow_node.get('inputs')):\n self.input_params.append(InputParam(input_param))\n for output_param in upconvert_to_list(workflow_node.get(\"outputs\")):\n self.output_data.append(OutputData(output_param))\n\n def update_with_job_order(self, job_order_path):\n \"\"\"\n Updates internal state based on job order data\n :param job_order_path: str: path to the job_order file used with workflow_name\n \"\"\"\n self.job_order_filename = job_order_path\n doc = parse_yaml_or_json(job_order_path)\n for key in list(doc.keys()):\n val = doc.get(key)\n input_param = find_by_name(key, self.input_params)\n if input_param:\n input_param.set_value(self._create_str_value(val))\n\n @staticmethod\n def _create_str_value(val):\n \"\"\"\n Coerce cwl value into str.\n \"\"\"\n if type(val) == dict:\n if 'path' in val:\n return val['path']\n else:\n # may be a custom object containing files, extract\n parts = [val[part] for part in val if 'path' in val[part]]\n return WorkflowInfo._create_str_value(parts)\n if type(val) == list:\n return ','.join(sorted([WorkflowInfo._create_str_value(part) for part in val]))\n return str(val)\n\n def update_with_job_output(self, job_output_path):\n \"\"\"\n Updates internal state based on stdout (resulting json) from running cwl\n :param job_output_path: str: path to resulting json object from running cwl\n \"\"\"\n self.job_output_filename = job_output_path\n doc = parse_yaml_or_json(job_output_path)\n if doc:\n for key in list(doc.keys()):\n val = doc.get(key)\n out_data = find_by_name(key, self.output_data)\n self._add_files_recursive(out_data, val)\n\n def _add_files_recursive(self, out_data, node):\n \"\"\"\n Recursively adds files contained under node to out_data.\n :param out_data: OutputData: contains all files for a workflow output name.\n :param node: dict/array: either file location information or array(possibly nested)\n \"\"\"\n if type(node) == dict:\n if node.get('class') == 'File':\n out_data.add_file(OutputFile(node))\n secondaryFiles = node.get(\"secondaryFiles\")\n if secondaryFiles:\n self._add_files_recursive(out_data, secondaryFiles)\n elif node.get('class') == 'Directory':\n for listing_item in node.get(\"listing\", []):\n self._add_files_recursive(out_data, listing_item)\n else:\n for item in node:\n self._add_files_recursive(out_data, item)\n\n def count_output_files(self):\n return len(self.output_data)\n\n def total_file_size_str(self):\n \"\"\"\n Returns the total output file size as a human friendly string.\n \"\"\"\n number_bytes = 0\n for item in self.output_data:\n for file_data in item.files:\n number_bytes += file_data.size\n return humanfriendly.format_size(number_bytes)\n\n\ndef find_by_name(name, items):\n \"\"\"\n Find the object with the specified name attribute.\n :param name: str: name to look for\n :param items: [object]: list of objects to look for\n :return: first item matching name or None if not found\n \"\"\"\n for item in items:\n if item.name == name:\n return item\n return None\n\n\nclass InputParam(object):\n \"\"\"\n Input parameter for a cwl workflow.\n \"\"\"\n def __init__(self, data):\n self.name = os.path.basename(data.get('id'))\n self.documentation = get_documentation_str(data)\n self.value = None\n\n def set_value(self, value):\n \"\"\"\n Saves str_value and raises error if called more than once.\n :param value: str: user facing value\n \"\"\"\n if self.value:\n raise \"Duplicate value for {}\".format(self.name)\n self.value = value\n\n\nclass OutputData(object):\n \"\"\"\n Output file generated by a cwl workflow.\n \"\"\"\n def __init__(self, data):\n \"\"\"\n :param data: dict: cwl formatted output data dictionary\n \"\"\"\n self.name = os.path.basename(data.get('id'))\n self.documentation = get_documentation_str(data)\n self.files = []\n\n def add_file(self, output_file):\n \"\"\"\n Add an output file to the list associated with this output data.\n :param output_file: OutputFile: info about the file\n \"\"\"\n self.files.append(output_file)\n\n\nclass OutputFile(object):\n \"\"\"\n Single file created by a CWL workflow\n \"\"\"\n def __init__(self, data):\n \"\"\"\n :param data: dict: cwl formatted file info\n \"\"\"\n self.filename = os.path.basename(data.get('location'))\n self.checksum = data.get('checksum')\n self.size = data.get('size', 0)\n\n\ndef parse_yaml_or_json(path):\n \"\"\"\n Return parsed YAML or JSON for a path to a file.\n \"\"\"\n with codecs.open(path, mode='r', encoding='utf-8') as infile:\n doc = yaml.safe_load(infile)\n return doc\n","repo_name":"Duke-GCB/lando-util","sub_path":"lando_util/organize_project/reports.py","file_name":"reports.py","file_ext":"py","file_size_in_byte":9822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"16543822194","text":"# PerceptronLayer defines the layers in the network. This is where the Perceptron Class is used.\n\n# By default, all the Layers must be connected, so each perceptron in the network must have equally as many\n# weights as one another, and the amount of weights on all perceptrons should equal the amount of connections from one layer to the\n# other on a per-perceptron basis.\n\nfrom classes.Perceptron import Perceptron\nfrom typing import List, Union\n\nclass PerceptronLayer:\n \"\"\"Defines a layer in a PerceptronNetwork.\"\"\"\n def __init__(self, ID, perceptrons: List[Perceptron]):\n self.perceptrons = perceptrons\n self.outputs = []\n\n def activate(self, inputlist: List[Union[int, float]]):\n \"\"\"Runs the inputlist through all perceptrons of the network and saves the output.\"\"\"\n self.outputs = []\n for i in self.perceptrons:\n i.activate(inputlist)\n self.outputs.append(i.output[-1])","repo_name":"SwagLag/Perceptrons","sub_path":"classes/PerceptronLayer.py","file_name":"PerceptronLayer.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"4564439702","text":"#! /usr/local/bin/python2.7\n\n\"\"\"Create NetCDF or GDS files\"\"\"\n\nimport QCpipeline\nimport sys\nimport os\nimport subprocess\nfrom optparse import OptionParser\n\nusage = \"\"\"%prog [options] config\n\nCreate genotype, XY intensity, and BAF/LRR netCDF or GDS files.\n\nRequired config parameters:\nannot_scan_file scan annotation file\nannot_snp_file snp annotation file\narray_build genotyping build (e.g., hg19)\narray_name name of the genotyping array\nraw_path path to raw data\ngeno_file output genotype file\nxy_file output XY intensity file (quality score optional)\nbl_file output BAF/LRR file\n\nRequired for \"checkPlink\" option:\nplink_prefix prefix of PLINK file to check\n\nOptional config parameters [default]:\nannot_scan_fileCol [file] column of raw data file in scan annotation\nannot_scan_nameCol [Sample.Name] column of raw data sample name in scan annotation\nannot_snp_nameCol [rsID] column of raw data snp name in snp annotation\nannot_plink_alt [NA] file with data.frame of alternate SNP annotation to pass to plinkCheck\nraw_scanNameInFile [0] 1=repeated in column, -1=embedded in column heading, 0=none\nraw_sepType [,] column separator in raw data (e.g. \",\", \"\\t\")\nraw_skipNum [12] number of rows to skip (including header)\nraw_colTotal [14] total number of columns in raw data files\nraw_snpCol [1] column number with snp name\nraw_sampleCol [NA] column number with scan name\nraw_alleleCoding [nucleotide] whether genotypes are coded as \"nucleotide\" or \"AB\"\nraw_a1Col [13] column number with allele 1\nraw_a2Col [14] column number with allele 2\nraw_genoCol [NA] column number with diploid genotype of allele1 and alelle2\nraw_qCol [NA] column number with quality score (NA to omit)\nraw_xCol [7] column number with X intensity\nraw_yCol [8] column number with Y intensity\nraw_bafCol [11] column number with BAF\nraw_lrrCol [12] column number with LRR\ngeno_file_type [gds] type for genotype file (gds or ncdf)\ngeno_checkFile [geno_check.RData] output file for genotype check\ngeno_diagFile [geno_diag.RData] output file for genotype creation\nxy_file_type [gds] type for XY file (gds or ncdf)\nxy_checkFile [xy_check.RData] output file for XY check\nxy_diagFile [xy_diag.RData] output file for XY creation\nbl_file_type [gds] type for BAF/LRR file (gds or ncdf)\nbl_checkFile [bl_check.RData] output file for BAF/LRR check\nbl_diagFile [bl_diag.RData] output file for BAF/LRR creation\nout_plink_logfile [plink_check.log] output file for PLINK check\"\"\"\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(\"-t\", \"--test\", dest=\"test\",\n action=\"store_true\", default=False,\n help=\"test with first 5 scans only\")\nparser.add_option(\"--overwrite\", dest=\"overwrite\",\n action=\"store_true\", default=False,\n help=\"overwrite existing files\")\nparser.add_option(\"-b\", \"--batches\", dest=\"batches\", default=None, \n help=\"create GDS in this many batches\")\nparser.add_option(\"-c\", \"--combine_batches\", dest=\"combine\",\n action=\"store_true\", default=False, \n help=\"combine batches\")\nparser.add_option(\"--checkPlink\", dest=\"plink\",\n action=\"store_true\", default=False,\n help=\"check PLINK file\")\nparser.add_option(\"--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\ntest = options.test\noverwrite = options.overwrite\nqname = options.qname\nnbatch = options.batches\ncombine = options.combine\nplink = options.plink\nqsubOptions = options.qsubOptions\n\nif nbatch is None and combine:\n sys.exit(\"specify number of batches to combine\")\n\npipeline = os.path.dirname(os.path.abspath(sys.argv[0]))\n\nif test:\n testStr = \"test\"\nelse:\n testStr = \"\"\n\nconfigdict = QCpipeline.readConfig(config)\n\nif not overwrite:\n for file in (configdict['geno_file'], configdict['xy_file'], configdict['bl_file']):\n if os.path.exists(file):\n sys.exit(file + \" already exists; use -o flag to overwrite\")\n\ndriver = os.path.join(pipeline, \"runRscript.sh\")\ndriver_array = os.path.join(pipeline, \"runRscript_array.sh\")\n\njobid = dict()\nfor type in [\"geno\", \"xy\", \"bl\"]:\n job = \"create_\" + type\n rscript = os.path.join(pipeline, \"R\", job + \".R\")\n\n if nbatch is None:\n jobid[job] = QCpipeline.submitJob(job, driver, [rscript, config, testStr], queue=qname, email=email, qsubOptions=qsubOptions)\n else:\n if not combine:\n arrayRange = \"1:\" + nbatch\n jobid[job] = QCpipeline.submitJob(job, driver_array, [rscript, config, nbatch], queue=qname, email=email, qsubOptions=qsubOptions, arrayRange=arrayRange)\n else:\n #holdid = [jobid[job].split(\".\")[0]] \n rscript = os.path.join(pipeline, \"R\", \"create_from_batches.R\")\n jobid[job + \"_combine\"] = QCpipeline.submitJob(job + \"_combine\", driver, [rscript, config, nbatch, type], queue=qname, email=email, qsubOptions=qsubOptions)\n \nif plink:\n if nbatch is None:\n holdid = [jobid['create_geno']]\n else:\n holdid = [jobid['create_geno_combine']]\n\n # convert bed to ped\n prefix = configdict['plink_prefix']\n if not os.path.exists(prefix + \".ped\"):\n # if os.path.exists(prefix+\".fam\"):\n # subprocess.call([\"mv\", prefix+\".fam\", prefix+\".fam.orig\"])\n # subprocess.call([\"cp\", prefix+\".fam.unr\", prefix+\".fam\"])\n job = \"plink_bed2ped\"\n arglist = [\"--noweb\", \"--bfile\", prefix, \"--recode\", \"--out\", prefix]\n jobid[job] = QCpipeline.submitJob(job, \"plink\", arglist, qsubOptions=\"-b y -j y -cwd\", queue=qname, email=email)\n holdid.append(jobid['plink_bed2ped'])\n\n job = \"plink_check\"\n rscript = os.path.join(pipeline, \"R\", job + \".R\")\n jobid[job] = QCpipeline.submitJob(job, driver, [rscript, config], holdid=holdid, queue=qname, email=email, qsubOptions=qsubOptions)\n \n","repo_name":"UW-GAC/QCpipeline","sub_path":"create_datafiles.py","file_name":"create_datafiles.py","file_ext":"py","file_size_in_byte":7012,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"74615489207","text":"import os\nfrom datetime import datetime\n\nimport discord\nfrom discord import app_commands\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\n\n\nclass Moderation(commands.Cog, name=\"moderation\"):\n def __init__(self, bot) -> None:\n self.bot = bot\n\n @commands.hybrid_command(\n name=\"kick\",\n description=\"Kick a user out of the server.\",\n )\n @commands.has_permissions(kick_members=True)\n @commands.bot_has_permissions(kick_members=True)\n @app_commands.describe(\n user=\"The user that should be kicked.\",\n reason=\"The reason why the user should be kicked.\",\n )\n async def kick(\n self, context: Context, user: discord.User, *, reason: str = \"Not specified\"\n ) -> None:\n \"\"\"\n Kick a user out of the server.\n\n :param context: The hybrid command context.\n :param user: The user that should be kicked from the server.\n :param reason: The reason for the kick. Default is \"Not specified\".\n \"\"\"\n member = context.guild.get_member(user.id) or await context.guild.fetch_member(\n user.id\n )\n if member.guild_permissions.administrator:\n embed = discord.Embed(\n description=\"User has administrator permissions.\", color=0xE02B2B\n )\n await context.send(embed=embed)\n else:\n try:\n embed = discord.Embed(\n description=f\"**{member}** was kicked by **{context.author}**!\",\n color=0xBEBEFE,\n )\n embed.add_field(name=\"Reason:\", value=reason)\n await context.send(embed=embed)\n try:\n await member.send(\n f\"You were kicked by **{context.author}** from **{context.guild.name}**!\\nReason: {reason}\"\n )\n except:\n # Couldn't send a message in the private messages of the user\n pass\n await member.kick(reason=reason)\n except:\n embed = discord.Embed(\n description=\"An error occurred while trying to kick the user. Make sure my role is above the role of the user you want to kick.\",\n color=0xE02B2B,\n )\n await context.send(embed=embed)\n\n @commands.hybrid_command(\n name=\"nick\",\n description=\"Change the nickname of a user on a server.\",\n )\n @commands.has_permissions(manage_nicknames=True)\n @commands.bot_has_permissions(manage_nicknames=True)\n @app_commands.describe(\n user=\"The user that should have a new nickname.\",\n nickname=\"The new nickname that should be set.\",\n )\n async def nick(\n self, context: Context, user: discord.User, *, nickname: str = None\n ) -> None:\n \"\"\"\n Change the nickname of a user on a server.\n\n :param context: The hybrid command context.\n :param user: The user that should have its nickname changed.\n :param nickname: The new nickname of the user. Default is None, which will reset the nickname.\n \"\"\"\n member = context.guild.get_member(user.id) or await context.guild.fetch_member(\n user.id\n )\n try:\n await member.edit(nick=nickname)\n embed = discord.Embed(\n description=f\"**{member}'s** new nickname is **{nickname}**!\",\n color=0xBEBEFE,\n )\n await context.send(embed=embed)\n except:\n embed = discord.Embed(\n description=\"An error occurred while trying to change the nickname of the user. Make sure my role is above the role of the user you want to change the nickname.\",\n color=0xE02B2B,\n )\n await context.send(embed=embed)\n\n @commands.hybrid_command(\n name=\"ban\",\n description=\"Bans a user from the server.\",\n )\n @commands.has_permissions(ban_members=True)\n @commands.bot_has_permissions(ban_members=True)\n @app_commands.describe(\n user=\"The user that should be banned.\",\n reason=\"The reason why the user should be banned.\",\n )\n async def ban(\n self, context: Context, user: discord.User, *, reason: str = \"Not specified\"\n ) -> None:\n \"\"\"\n Bans a user from the server.\n\n :param context: The hybrid command context.\n :param user: The user that should be banned from the server.\n :param reason: The reason for the ban. Default is \"Not specified\".\n \"\"\"\n member = context.guild.get_member(user.id) or await context.guild.fetch_member(\n user.id\n )\n try:\n if member.guild_permissions.administrator:\n embed = discord.Embed(\n description=\"User has administrator permissions.\", color=0xE02B2B\n )\n await context.send(embed=embed)\n else:\n embed = discord.Embed(\n description=f\"**{member}** was banned by **{context.author}**!\",\n color=0xBEBEFE,\n )\n embed.add_field(name=\"Reason:\", value=reason)\n await context.send(embed=embed)\n try:\n await member.send(\n f\"You were banned by **{context.author}** from **{context.guild.name}**!\\nReason: {reason}\"\n )\n except:\n # Couldn't send a message in the private messages of the user\n pass\n await member.ban(reason=reason)\n except:\n embed = discord.Embed(\n title=\"Error!\",\n description=\"An error occurred while trying to ban the user. Make sure my role is above the role of the user you want to ban.\",\n color=0xE02B2B,\n )\n await context.send(embed=embed)\n\n @commands.hybrid_group(\n name=\"warning\",\n description=\"Manage warnings of a user on a server.\",\n )\n @commands.has_permissions(manage_messages=True)\n async def warning(self, context: Context) -> None:\n \"\"\"\n Manage warnings of a user on a server.\n\n :param context: The hybrid command context.\n \"\"\"\n if context.invoked_subcommand is None:\n embed = discord.Embed(\n description=\"Please specify a subcommand.\\n\\n**Subcommands:**\\n`add` - Add a warning to a user.\\n`remove` - Remove a warning from a user.\\n`list` - List all warnings of a user.\",\n color=0xE02B2B,\n )\n await context.send(embed=embed)\n\n @warning.command(\n name=\"add\",\n description=\"Adds a warning to a user in the server.\",\n )\n @commands.has_permissions(manage_messages=True)\n @app_commands.describe(\n user=\"The user that should be warned.\",\n reason=\"The reason why the user should be warned.\",\n )\n async def warning_add(\n self, context: Context, user: discord.User, *, reason: str = \"Not specified\"\n ) -> None:\n \"\"\"\n Warns a user in his private messages.\n\n :param context: The hybrid command context.\n :param user: The user that should be warned.\n :param reason: The reason for the warn. Default is \"Not specified\".\n \"\"\"\n member = context.guild.get_member(user.id) or await context.guild.fetch_member(\n user.id\n )\n total = await self.bot.database.add_warn(\n user.id, context.guild.id, context.author.id, reason\n )\n embed = discord.Embed(\n description=f\"**{member}** was warned by **{context.author}**!\\nTotal warns for this user: {total}\",\n color=0xBEBEFE,\n )\n embed.add_field(name=\"Reason:\", value=reason)\n await context.send(embed=embed)\n try:\n await member.send(\n f\"You were warned by **{context.author}** in **{context.guild.name}**!\\nReason: {reason}\"\n )\n except:\n # Couldn't send a message in the private messages of the user\n await context.send(\n f\"{member.mention}, you were warned by **{context.author}**!\\nReason: {reason}\"\n )\n\n @warning.command(\n name=\"remove\",\n description=\"Removes a warning from a user in the server.\",\n )\n @commands.has_permissions(manage_messages=True)\n @app_commands.describe(\n user=\"The user that should get their warning removed.\",\n warn_id=\"The ID of the warning that should be removed.\",\n )\n async def warning_remove(\n self, context: Context, user: discord.User, warn_id: int\n ) -> None:\n \"\"\"\n Warns a user in his private messages.\n\n :param context: The hybrid command context.\n :param user: The user that should get their warning removed.\n :param warn_id: The ID of the warning that should be removed.\n \"\"\"\n member = context.guild.get_member(user.id) or await context.guild.fetch_member(\n user.id\n )\n total = await self.bot.database.remove_warn(warn_id, user.id, context.guild.id)\n embed = discord.Embed(\n description=f\"I've removed the warning **#{warn_id}** from **{member}**!\\nTotal warns for this user: {total}\",\n color=0xBEBEFE,\n )\n await context.send(embed=embed)\n\n @warning.command(\n name=\"list\",\n description=\"Shows the warnings of a user in the server.\",\n )\n @commands.has_guild_permissions(manage_messages=True)\n @app_commands.describe(user=\"The user you want to get the warnings of.\")\n async def warning_list(self, context: Context, user: discord.User) -> None:\n \"\"\"\n Shows the warnings of a user in the server.\n\n :param context: The hybrid command context.\n :param user: The user you want to get the warnings of.\n \"\"\"\n warnings_list = await self.bot.database.get_warnings(user.id, context.guild.id)\n embed = discord.Embed(title=f\"Warnings of {user}\", color=0xBEBEFE)\n description = \"\"\n if len(warnings_list) == 0:\n description = \"This user has no warnings.\"\n else:\n for warning in warnings_list:\n description += f\"• Warned by <@{warning[2]}>: **{warning[3]}** () - Warn ID #{warning[5]}\\n\"\n embed.description = description\n await context.send(embed=embed)\n\n @commands.hybrid_command(\n name=\"purge\",\n description=\"Delete a number of messages.\",\n )\n @commands.has_guild_permissions(manage_messages=True)\n @commands.bot_has_permissions(manage_messages=True)\n @app_commands.describe(amount=\"The amount of messages that should be deleted.\")\n async def purge(self, context: Context, amount: int) -> None:\n \"\"\"\n Delete a number of messages.\n\n :param context: The hybrid command context.\n :param amount: The number of messages that should be deleted.\n \"\"\"\n await context.send(\n \"Deleting messages...\"\n ) # Bit of a hacky way to make sure the bot responds to the interaction and doens't get a \"Unknown Interaction\" response\n purged_messages = await context.channel.purge(limit=amount + 1)\n embed = discord.Embed(\n description=f\"**{context.author}** cleared **{len(purged_messages)-1}** messages!\",\n color=0xBEBEFE,\n )\n await context.channel.send(embed=embed)\n\n @commands.hybrid_command(\n name=\"hackban\",\n description=\"Bans a user without the user having to be in the server.\",\n )\n @commands.has_permissions(ban_members=True)\n @commands.bot_has_permissions(ban_members=True)\n @app_commands.describe(\n user_id=\"The user ID that should be banned.\",\n reason=\"The reason why the user should be banned.\",\n )\n async def hackban(\n self, context: Context, user_id: str, *, reason: str = \"Not specified\"\n ) -> None:\n \"\"\"\n Bans a user without the user having to be in the server.\n\n :param context: The hybrid command context.\n :param user_id: The ID of the user that should be banned.\n :param reason: The reason for the ban. Default is \"Not specified\".\n \"\"\"\n try:\n await self.bot.http.ban(user_id, context.guild.id, reason=reason)\n user = self.bot.get_user(int(user_id)) or await self.bot.fetch_user(\n int(user_id)\n )\n embed = discord.Embed(\n description=f\"**{user}** (ID: {user_id}) was banned by **{context.author}**!\",\n color=0xBEBEFE,\n )\n embed.add_field(name=\"Reason:\", value=reason)\n await context.send(embed=embed)\n except Exception:\n embed = discord.Embed(\n description=\"An error occurred while trying to ban the user. Make sure ID is an existing ID that belongs to a user.\",\n color=0xE02B2B,\n )\n await context.send(embed=embed)\n\n @commands.hybrid_command(\n name=\"archive\",\n description=\"Archives in a text file the last messages with a chosen limit of messages.\",\n )\n @commands.has_permissions(manage_messages=True)\n @app_commands.describe(\n limit=\"The limit of messages that should be archived.\",\n )\n async def archive(self, context: Context, limit: int = 10) -> None:\n \"\"\"\n Archives in a text file the last messages with a chosen limit of messages. This command requires the MESSAGE_CONTENT intent to work properly.\n\n :param limit: The limit of messages that should be archived. Default is 10.\n \"\"\"\n log_file = f\"{context.channel.id}.log\"\n with open(log_file, \"w\", encoding=\"UTF-8\") as f:\n f.write(\n f'Archived messages from: #{context.channel} ({context.channel.id}) in the guild \"{context.guild}\" ({context.guild.id}) at {datetime.now().strftime(\"%d.%m.%Y %H:%M:%S\")}\\n'\n )\n async for message in context.channel.history(\n limit=limit, before=context.message\n ):\n attachments = []\n for attachment in message.attachments:\n attachments.append(attachment.url)\n attachments_text = (\n f\"[Attached File{'s' if len(attachments) >= 2 else ''}: {', '.join(attachments)}]\"\n if len(attachments) >= 1\n else \"\"\n )\n f.write(\n f\"{message.created_at.strftime('%d.%m.%Y %H:%M:%S')} {message.author} {message.id}: {message.clean_content} {attachments_text}\\n\"\n )\n f = discord.File(log_file)\n await context.send(file=f)\n os.remove(log_file)\n\n\nasync def setup(bot) -> None:\n await bot.add_cog(Moderation(bot))\n","repo_name":"kkrypt0nn/Python-Discord-Bot-Template","sub_path":"cogs/moderation.py","file_name":"moderation.py","file_ext":"py","file_size_in_byte":14927,"program_lang":"python","lang":"en","doc_type":"code","stars":700,"dataset":"github-code","pt":"77"} +{"seq_id":"73941926329","text":"\"\"\"\nRackspace Cloud Files\n\"\"\"\nimport logging\nimport requests\nimport hashlib\n\nfrom rcbu.common.command import Command\n\n\nclass CloudFiles(Command):\n \"\"\"\n Primary Cloud Files API Class\n \"\"\"\n\n def __init__(self, sslenabled, authenticator):\n \"\"\"\n Setup the CloudFiles API Class in the same manner as rcbu.common.Command\n \"\"\"\n Command.__init__(self, sslenabled, 'localhost', '/')\n # save the ssl status for the various reinits done for each API call supported\n self.sslenabled = sslenabled\n self.authenticator = authenticator\n self.auth = authenticator\n self.log = logging.getLogger(__name__)\n\n def GetContainers(self, uri, limit=-1, marker=''):\n \"\"\"\n List all containers for the current account\n \"\"\"\n self.apihost = uri\n urioptions = '?format=json'\n if not limit is -1:\n urioptions += '&limit=%d' % limit\n if len(marker):\n urioptions += '&marker=%s' % marker\n self.ReInit(self.sslenabled, urioptions)\n self.headers['X-Auth-Token'] = self.authenticator.AuthToken\n self.headers['Content-Type'] = 'text/plain; charset=UTF-8'\n self.log.debug('uri: %s', self.Uri)\n self.log.debug('headers: %s', self.Headers)\n res = requests.get(self.Uri, headers=self.Headers)\n if res.status_code == 200:\n # We have a list in JSON format\n return res.json()\n elif res.status_code == 204:\n # Nothing left to retrieve\n return {}\n else:\n # Error\n self.log.error('Error retrieving list of containers: (code=' + str(res.status_code) + ', text=\\\"' + res.text + '\\\")')\n return {}\n\n def GetContainerObjects(self, uri, container, limit=-1, marker=''):\n \"\"\"\n List the objects in a container under the current account\n \"\"\"\n self.apihost = uri\n urioptions = '/' + container + '?format=json'\n if not limit is -1:\n urioptions += '&limit=%d' % limit\n if len(marker):\n urioptions += '&marker=%s' % marker\n self.ReInit(self.sslenabled, urioptions)\n self.headers['X-Auth-Token'] = self.authenticator.AuthToken\n self.headers['Content-Type'] = 'text/plain; charset=UTF-8'\n self.log.debug('uri: %s', self.Uri)\n self.log.debug('headers: %s', self.Headers)\n res = requests.get(self.Uri, headers=self.Headers)\n if res.status_code == 200:\n # We have a list in JSON format\n return res.json()\n elif res.status_code == 204:\n # Nothing left to retrieve\n return {}\n else:\n # Error\n self.log.error('Error retrieving list of containers: (code=' + str(res.status_code) + ', text=\\\"' + res.text + '\\\")')\n return {}\n\n def DownloadObject(self, uri, container, object_data, localpath):\n \"\"\"\n Download the object\n \"\"\"\n self.apihost = uri\n try:\n self.ReInit(self.sslenabled, '/' + container + '/' + object_data['name'])\n self.headers['X-Auth-Token'] = self.authenticator.AuthToken\n self.log.debug('uri: %s', self.Uri)\n self.log.debug('headers: %s', self.Headers)\n try:\n res = requests.get(self.Uri, headers=self.Headers)\n except request.exceptions.SSLError as ex:\n self.log.error('Request SSLError: {0}'.format(str(ex)))\n res = requests.get(self.Uri, headers=self.Headers, verify=False)\n\n if res.status_code == 404:\n raise UserWarning('Cloud Files did not find the object')\n\n elif res.status_code >= 300:\n raise UserWarning('Cloud Files responded unexpecteduing during download initiation (Code: ' + str(res.status_code) + ' )')\n else: \n meter = {}\n meter['bytes-remaining'] = int(res.headers['Content-Length'])\n meter['bar-count'] = 50\n meter['bytes-per-bar'] = meter['bytes-remaining'] // meter['bar-count']\n meter['block-size'] = min(2 ** 12, meter['bytes-per-bar'])\n meter['chunks-per-bar'] = meter['bytes-per-bar'] // meter['block-size']\n meter['chunks'] = 0\n meter['bars-remaining'] = meter['bar-count']\n meter['bars-completed'] = 0\n self.log.info('Downloading object: {0} bytes...'.format(meter['bytes-remaining']))\n self.log.info('[' + ' ' * meter['bar-count'] + ']')\n md5_hash = hashlib.md5()\n sha1_hash = hashlib.sha1()\n with open(localpath, 'wb') as target_file:\n for object_chunk in res.iter_content(chunk_size=meter['block-size']):\n target_file.write(object_chunk)\n md5_hash.update(object_chunk)\n sha1_hash.update(object_chunk)\n meter['chunks'] += 1\n if meter['chunks'] == meter['chunks-per-bar']:\n meter['chunks'] = 0\n meter['bars-completed'] += 1\n meter['bars-remaining'] -= 1\n self.log.info('[' + '-' * meter['bars-completed'] + ' ' * meter['bars-remaining'] + ']')\n object_data['md5'] = md5_hash.hexdigest().upper()\n object_data['sha1'] = sha1_hash.hexdigest().upper()\n self.log.info('VaultDB (' + object_data['name'] + ') was successfully downloaded to ' + localpath)\n return True\n except LookupError:\n raise UserWarning('Invalid Object Data provided.')\n","repo_name":"BenjamenMeyer/cloudfiles-viewer","sub_path":"src/rcbu/cloud/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":5752,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"8086784885","text":"from django.urls import path\n\nfrom . import views\nfrom MMcalendar import views as Calviews \n## Some thoughts on our view organization. I feel that since the site is meant to be extremely\n## user focused, we want to keep their urls to the point. So to land on a user's profile, we want\n## it to be marketme.com/username, to do so we're going to have to keep user off the list of available\n## names, and we might want to reserve a few more for expansion.\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"user/login\", views.login_view, name='login'),\n path('user/logout', views.logout_view, name='logout'),\n path('user/register', views.register, name='register'),\n path('user/settings', views.settings, name='settings'),\n path('user/profile_settings', views.profile_settings, name='profile settings'),\n path('user/createService', Calviews.create_service, name='create service'),\n path('user/myServices', Calviews.myServices, name='my services'),\n path('user/availability//new', Calviews.create_availability, name='create availability'),\n path('user/confirm/', Calviews.confirmEvent, name='confirm event'),\n path('user/export//', Calviews.exportCalendar, name='export calendar'),\n path('user/availability//rules/', Calviews.deleteAvailability, name='delete availability'),\n path('/Calendars/////book', Calviews.bookEvent, name='book event'),\n path('/myCalendars', Calviews.multiCalendar_view, name='multiCalendar'),\n path('/Calendars///', Calviews.calendar_view, name='single calendar'),\n path('/Calendars////', Calviews.dayDetails, name='day details'),\n path('user/profile/', views.profile, name='profile'),\n path('user/relations//upgrade', views.relationUpgrade , name='relation upgrade'),\n path('user/relations//revoke', views.relationRevoke, name='relation revoke'),\n path('user/relations//restore', views.relationRestore, name='relation restore'),\n ]","repo_name":"PhiloTFarnsworth/MarketMePostMortem","sub_path":"MMUX/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"72083738168","text":"import math\nimport matplotlib.pyplot as plt\nimport numpy\n\nBASS_P = 0.003 # p parameter for Bass model\nBASS_Q = 0.7 # q parameter for Bass model\nGROWTH = 0.007 # growth of the number of miles travelled\nMILES = 3130509 # millions of miles travelled from DOT\nREG_RATIO = 0.01054142011 # number of fatalities with regular miles travelled\nAV_FRACTION = 0.1 # the percentage of the ratio with automous vehicles\n\ndef bass_model(p, q, t):\n\t\"\"\"\n\tThis is the generic Bass model that takes p, q, and computes\n\tthe end result at time t periods from now\n\t\"\"\"\n\ta = q/p\n\tb = p+q\n\tx = math.exp(-1 * b * t)\n\ty = 1 + a * x\n\tbass = (b ** 2 * x) / (p * y ** 2)\n\treturn bass\n\ndef main():\n\t\"\"\"\n\tThe main script of the program.\n\t\"\"\"\n\ti = 0\n\tmiles = [MILES]\n\tnew = [0]\n\tavmiles = [0]\n\tregmiles = [(MILES - 1)]\n\twhile i < 30:\n\t\tmiles.append(miles[i]*(1 + GROWTH))\n\t\ti = i + 1\n\t\tnew.append(bass_model(BASS_P, BASS_Q, i))\n\t\tcumulative = numpy.sum(new)\n\t\tavmiles.append(cumulative * miles[i])\n\t\tregmiles.append(miles[i] - avmiles[i])\n\ttotaldeaths = numpy.sum(regmiles)*REG_RATIO + numpy.sum(avmiles)*REG_RATIO*AV_FRACTION\n\tprint (int(totaldeaths))\n\tplt.plot(avmiles)\n\tplt.show()\n\nif __name__ == \"__main__\":\n\tmain()\n\n","repo_name":"jpbailey/390","sub_path":"automodel2.py","file_name":"automodel2.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"37586914668","text":"import praw\nimport time\nimport datetime\nimport sqlite3\n\n'''USER CONFIGURATION'''\n\nAPP_ID = \"\"\nAPP_SECRET = \"\"\nAPP_URI = \"\"\nAPP_REFRESH = \"\"\n# https://www.reddit.com/comments/3cm1p8/how_to_make_your_bot_use_oauth2/\nUSERAGENT = \"\"\n#This is a short description of what the bot does. For example \"/u/GoldenSights' Newsletter Bot\".\nSUBREDDIT = \"GoldTesting\"\n#This is the sub or list of subs to scan for new posts. For a single sub, use \"sub1\". For multiple subreddits, use \"sub1+sub2+sub3+...\"\nMAXPOSTS = 30\n#This is how many posts you want to retrieve all at once. PRAW can download 100 at a time.\nWAIT = 30\n#This is how many seconds you will wait between cycles. The bot is completely inactive during this time.\nDELAY = 300\n#This is the time, IN SECONDS, the user has to make his comment. If he does not have a source by this time, post is removed.\nMESSAGE = \"You have not made a comment within the timelimit. Your post has been removed. Contact the moderators if you believe this was done in error\"\n#This is what the bot tells you when your post gets removed. Uses reddit's usual Markdown formatting\nIGNOREMODS = False\n#Do you want the bot to ignore posts made by moderators? Use True or False (With capitals! No quotations!)\nIGNORESELFPOST = True\n#Do you want the bot to ignore selfposts?\n'''All done!'''\n\n\n\n\n\n\nWAITS = str(WAIT)\ntry:\n import bot\n USERAGENT = bot.getaG()\nexcept ImportError:\n pass\n\nsql = sqlite3.connect('sql.db')\nprint('Loaded SQL Database')\ncur = sql.cursor()\ncur.execute('CREATE TABLE IF NOT EXISTS oldposts(id TEXT)')\nprint('Loaded Oldposts')\nsql.commit()\n\nr = praw.Reddit(USERAGENT)\nr.set_oauth_app_info(APP_ID, APP_SECRET, APP_URI)\nr.refresh_access_information(APP_REFRESH)\n\ndef getTime(bool):\n\ttimeNow = datetime.datetime.now(datetime.timezone.utc)\n\ttimeUnix = timeNow.timestamp()\n\tif bool is False:\n\t\treturn timeNow\n\telse:\n\t\treturn timeUnix\n\ndef scan():\n\tprint('Scanning ' + SUBREDDIT)\n\tsubreddit = r.get_subreddit(SUBREDDIT)\n\tmoderators = subreddit.get_moderators()\n\tmods = []\n\tfor moderator in moderators:\n\t\tmods.append(moderator.name)\n\tposts = subreddit.get_new(limit=MAXPOSTS)\n\tfor post in posts:\n\t\tfound = False\n\t\tpid = post.id\n\t\ttry:\n\t\t\tpauthor = post.author.name\n\t\texcept AttributeError:\n\t\t\tpauthor = '[deleted]'\n\t\tptime = post.created_utc\n\t\tcurtime = getTime(True)\n\n\t\tcur.execute('SELECT * FROM oldposts WHERE id=\"%s\"' % pid)\n\t\tif not cur.fetchone():\n\t\t\tif post.is_self is False or IGNORESELFPOST is False:\n\t\t\t\tif pauthor not in mods or IGNOREMODS is False:\n\t\t\t\t\tdifference = curtime - ptime\n\t\t\t\t\tif difference > DELAY:\n\t\t\t\t\t\tprint(pid + ', ' + pauthor + ': Finding comments')\n\t\t\t\t\t\tcomments = praw.helpers.flatten_tree(post.comments)\n\t\t\t\t\t\tfor comment in comments:\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tcauthor = comment.author.name\n\t\t\t\t\t\t\texcept AttributeError:\n\t\t\t\t\t\t\t\tcauthor = '[deleted]'\n\t\t\t\t\t\t\tif cauthor == pauthor and found is False:\n\t\t\t\t\t\t\t\tprint('\\tFound comment by OP')\n\t\t\t\t\t\t\t\tfound = True\n\t\t\t\t\t\tif found is False:\n\t\t\t\t\t\t\tprint('\\tComments were empty, or OP was not found. Post will be removed.')\n\t\t\t\t\t\t\tresponse = post.add_comment(MESSAGE)\n\t\t\t\t\t\t\tresponse.distinguish()\n\t\t\t\t\t\t\tpost.remove(spam=False)\n\t\t\t\t\t\t\tprint('\\tPost removed')\n\t\t\t\t\t\t\ttime.sleep(5)\n\n\t\t\t\t\t\tcur.execute('INSERT INTO oldposts VALUES(\"%s\")' % pid)\n\t\t\t\t\telse:\n\t\t\t\t\t\tdifferences = str('%.0f' % (DELAY - difference))\n\t\t\t\t\t\tprint(pid + ', ' + pauthor + ': Still has ' + differences + 's.')\n\t\t\t\t\n\t\t\t\tif pauthor in mods and IGNOREMODS is True:\n\t\t\t\t\tprint(pid + ', ' + pauthor + ': Ignoring Moderator')\n\t\t\t\t\tcur.execute('INSERT INTO oldposts VALUES(\"%s\")' % pid)\n\n\t\t\tif post.is_self is True and IGNORESELFPOST is True:\n\t\t\t\tprint(pid + ', ' + pauthor + ': Ignoring Selfpost')\n\t\t\t\tcur.execute('INSERT INTO oldposts VALUES(\"%s\")' % pid)\n\n\t\tsql.commit()\n\n\n\nwhile True:\n\ttry:\n\t\tscan()\n\texcept Exception as e:\n\t\tprint('An error has occured:', e)\n\tprint('Running again in ' + WAITS + ' seconds.\\n')\n\ttime.sleep(WAIT)","repo_name":"voussoir/reddit","sub_path":"_old/SourceIt/s.py","file_name":"s.py","file_ext":"py","file_size_in_byte":3905,"program_lang":"python","lang":"en","doc_type":"code","stars":478,"dataset":"github-code","pt":"77"} +{"seq_id":"13135000399","text":"from django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.db import models\nfrom django.shortcuts import reverse\n\nclass Item(models.Model):\n name = models.CharField(max_length=200)\n price = models.FloatField(null=True)\n description = models.TextField(blank=True,null=True)\n image = models.ImageField(upload_to='item_images',blank=True,null=True)\n\n def __str__(self):\n return self.name\n \n\nclass Cart(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n item = models.ForeignKey(Item, on_delete= models.CASCADE)\n quantity = models.PositiveIntegerField(default=1)\n\n @property\n def total_cost(self):\n return self.quantity * self.item.price\n\nSTATUS_CHOICE = (\n ('Preparing', 'Preparing'),\n ('On the way', 'On the way'),\n ('Delievered','Delievered')\n)\n\nclass OrderDetails(models.Model):\n order_number = models.IntegerField(null=True)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n name = models.CharField(max_length=200)\n email = models.EmailField()\n address = models.CharField(max_length=250)\n zipcode = models.IntegerField()\n\nclass Order(models.Model):\n order_number = models.IntegerField(null=True)\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)\n item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True)\n quantity = models.PositiveIntegerField(default=1)\n ordered_date = models.DateTimeField(auto_now_add=True)\n ordered = models.BooleanField(default=False)\n status = models.CharField(max_length=50, choices=STATUS_CHOICE, default='Preparing')\n\n @property\n def total_cost(self):\n return self.quantity * self.item.price\n\n","repo_name":"elliehkim/django-foodapp","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"28908834859","text":"import sys\nfrom compares import ComparesInterface\nfrom heap import BinaryHeap\n\n# Entry in table for use in Dijkstra's Algorithm\nclass DijkstraEntry(ComparesInterface):\n\n def __init__(self, entry):\n\n self.key = list(entry.keys())[0]\n self.entry = entry[self.key]\n\n # For use with the binary heap\n def compare(self, object):\n result = None\n\n if self.entry[\"total_distance\"] > object.entry[\"total_distance\"]:\n result = 1\n elif self.entry[\"total_distance\"] == object.entry[\"total_distance\"]:\n result = 0\n else:\n result = -1\n\n return result\n\n def get_key(self):\n return self.key\n\n\"\"\"\nClass implementation of a directed graph\n1. The graph object has a two-level dictionary structure of:\n graph = { vertex_1 : { adj_vertex : distance, adj_vertex : distance}, \n vertex_2 : { adj_vertex : distance } }\n\n where the adjacent vertices is a 1st level key in our graph dictionary\n eg) an 'adj_vertex' could be 'vertex_2' or 'vertex_3'\n\"\"\"\nclass Graph:\n\n BIG_NUMBER = sys.maxsize * 2 + 1\n\n def __init__(self):\n self.graph = {}\n\n def add_vertex(self, vertex_id):\n if vertex_id in self.graph.keys():\n return False\n else:\n self.graph[vertex_id] = {}\n return True\n\n def remove_vertex(self, vertex_id):\n if vertex_id in self.graph.keys():\n del self.graph[vertex_id]\n return True\n else:\n return False\n\n def add_edge(self, vertex_from, vertex_to, weight):\n if vertex_from in self.graph.keys():\n if vertex_to in self.graph[vertex_from].keys():\n return False\n else:\n self.graph[vertex_from][vertex_to] = weight\n return True\n else:\n return False\n\n def remove_edge(self, vertex_from, vertex_to):\n if vertex_from in self.graph.keys():\n if vertex_to in self.graph[vertex_from].keys():\n del self.graph[vertex_from][vertex_to]\n return True\n else:\n return False\n else:\n return False\n\n \"\"\"\n ALGORITHMS - Algorithms associated with graphs\n \"\"\"\n\n \"\"\"\n Prim's Algorithm - Minimum Spanning Tree\n\n Notes: End of algorithm determination implementations\n 1. Determine whether the number of vertices in our MST are\n the same as those in our original graph\n 2. Determine whether we can no longer find an unconnected vertex to add\n to our MST\n \n The output is in the form of a symmetric directed graph\n \"\"\"\n\n def prim(self):\n \n # Store our minimum spanning tree\n mst_graph = {}\n\n # Let's use the first vertex in our original graph as the starting point\n first_key = list(self.graph.keys())[0]\n mst_graph[first_key] = {}\n\n while len(mst_graph.keys()) < len(self.graph.keys()):\n\n # source = source vertex, dest = destination vertex\n shortest_edge = {\"value\" : None, \"source\" : None, \"dest\" : None}\n\n for vertex_from in mst_graph.keys():\n for vertex_to in self.graph[vertex_from].keys():\n if not (vertex_to in mst_graph.keys()):\n current_edge_value = self.graph[vertex_from][vertex_to]\n if (shortest_edge[\"value\"] == None) or (current_edge_value < shortest_edge[\"value\"]):\n shortest_edge[\"value\"] = current_edge_value\n shortest_edge[\"source\"] = vertex_from\n shortest_edge[\"dest\"] = vertex_to\n\n # Add the edge to our MST\n mst_graph[shortest_edge[\"source\"]][shortest_edge[\"dest\"]] = shortest_edge[\"value\"]\n\n # Reverse connection of vertices (as our output is a symmetric graph)\n # New 1st-level key must be added, since our 'vertex_to' vertex must be unconnected\n mst_graph[shortest_edge[\"dest\"]] = {shortest_edge[\"source\"] : shortest_edge[\"value\"]}\n \n return mst_graph\n\n\n \"\"\"\n Dijkstra's Algorithm - Shortest path (from a vertex)\n \"\"\"\n\n def dijkstra(self, vertex):\n entry_dict = {}\n\n if vertex in self.graph.keys():\n\n vertex_heap = BinaryHeap(BinaryHeap.MIN_HEAP)\n\n \"\"\"\n Add each vertex and their data (total distance, previous node) as an entry\n to a table. Use both a heap and list -> Heap: For sorting the entries by total distance,\n List: For accessing other entries.\n \"\"\"\n for i in self.graph.keys():\n\n # Tabel entry setup\n entry = { i : { \"previous\" : \"\", \"total_distance\" : Graph.BIG_NUMBER} }\n\n if i == vertex:\n entry[i][\"total_distance\"] = 0\n\n dijkstra_entry = DijkstraEntry(entry)\n vertex_heap.add(dijkstra_entry)\n entry_dict.update(entry)\n\n \"\"\"\n The vertex with the smallest total distance will be processed first, then\n removed from the table. This is repeated until there are no more vertices\n in the table.\n \"\"\"\n while not vertex_heap.is_empty():\n current_vertex = vertex_heap.pop().get_key()\n\n for i in self.graph[current_vertex].keys():\n\n if entry_dict[i][\"total_distance\"] == Graph.BIG_NUMBER:\n entry_dict[i][\"total_distance\"] = entry_dict[current_vertex][\"total_distance\"] + self.graph[current_vertex][i]\n entry_dict[i][\"previous\"] = current_vertex\n\n elif (entry_dict[current_vertex][\"total_distance\"] + self.graph[current_vertex][i] < entry_dict[i][\"total_distance\"]):\n entry_dict[i][\"total_distance\"] = entry_dict[current_vertex][\"total_distance\"] + self.graph[current_vertex][i]\n entry_dict[i][\"previous\"] = current_vertex\n\n else:\n pass\n\n return entry_dict\n\n # Return a string of vertices and their edges\n def get_string(self):\n\n graph_string = \"\"\n\n for i in self.graph.keys():\n for j in self.graph[i].keys():\n graph_string += str(i) + \"->\" + str(j) + \":\" + str(self.graph[i][j]) + \"\\n\"\n\n return graph_string","repo_name":"OmelettePastry/data-structure-implementations","sub_path":"graph/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":6422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"27578019224","text":"from celery import Celery\n\nfrom app.application.services import handle_set_tags_for\n\nBROKER_URL = 'redis://localhost:6379/0'\n\napp = Celery('app.presentation.tasks', broker=BROKER_URL)\n\n@app.task\ndef set_tags(entry_id):\n handle_set_tags_for(entry_id)\n\n\nif __name__ == '__main__':\n # workon demoddd\n # celery -A app.presentation.tasks worker --loglevel=info\n set_tags.delay(1)\n set_tags.delay(2)\n","repo_name":"vklap/demo-ddd-python","sub_path":"app/presentation/tasks/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"77"} +{"seq_id":"69851341370","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 4 16:26:42 2019\n\n@author: JBG\n\"\"\"\n\nfrom numpy import *\nimport pandas as pd\nfrom sklearn import preprocessing \n\nimport matplotlib.pyplot as plt\n\n\ndef preprocessingTrain(pathFile):\n #pathFile is the path of the dataset\n #returns X and Y, after deleting useless attributes\n \n # Load data\n csv_file_object = pd.read_csv(pathFile, delimiter=',') # Load in the csv file\n XX=array(csv_file_object.values) # Create a variable to hold the data, type array\n \n n= XX.shape[0]\n\n y = zeros((n-1,1))\n x = zeros((n-1,4))\n for i in range(2,n-3):\n y[i,0] = XX[i+3,5]\n x[i,0] = XX[i,5]\n x[i,1] = XX[i-1,5]\n x[i,2] = XX[i,6]\n x[i,3] = XX[i-1,6]\n \n return x, y\n\n \n","repo_name":"jbgour/ML_Challenges","sub_path":"ML_Wind_Power_Prediction/preprocessingModule.py","file_name":"preprocessingModule.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"32464718959","text":"import numpy as np\nimport pandas as pd\nimport os \nimport time\n\n\ndef get_immediate_subdirectories(a_dir):\n return [name for name in os.listdir(a_dir)\n if os.path.isdir(os.path.join(a_dir, name))]\n\n\ndirectory = os.getcwd()\n# Unzipped data is put in the following path\ndata_path = directory + '\\\\Voice\\\\data\\\\unzipped\\\\train'\n\n# Create a file with file description and labels (gender and accent)\ndf = pd.DataFrame()\nsubdirs = get_immediate_subdirectories(data_path)\nfor subdir in subdirs:\n filenames = os.listdir(data_path + \"\\\\\" + subdir)\n gender = subdir.split(\"_\")[0]\n accent = subdir.split(\"_\")[1]\n df1 = pd.DataFrame({\n 'Filename' : filenames,\n 'Foldername' : subdir,\n 'Gender' : gender,\n 'Accent' : accent\n\n })\n print(df1.head())\n df = df.append(df1, ignore_index=True)\n \n\nprint(df)\ndf.to_csv(\"description.csv\")\n \n\n","repo_name":"nhnminh/zalochallenge","sub_path":"Voice/src/data_loading.py","file_name":"data_loading.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"41998283396","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom pymongo import MongoClient\nimport requests\nfrom bs4 import BeautifulSoup\nimport datetime\n\ndef scrapping_worknet(max_page=10, keyword='AI'):\n # 드라이버 옵션\n options = webdriver.ChromeOptions()\n options.add_argument('headless') # headless mode\n options.add_argument('window-size=1920x1080')\n options.add_argument(\"disable-gpu\")\n\n # 드라이버 연결\n driver = webdriver.Chrome(executable_path='./datas/chromedriver', chrome_options=options)\n driver.get(url='https://www.work.go.kr')\n print('start chrome driver')\n\n # 검색 및 더보기\n search_box = driver.find_element(By.NAME, 'topQuery')\n search_box.send_keys(keyword)\n print(f'keyword: {keyword}')\n driver.find_element(By.CLASS_NAME, 'btn-search').click()\n btn1 = driver.find_elements(By.XPATH, '//*[@id=\"contents\"]/div/div[1]/div[1]/div[2]/div[3]/a')\n btn1[0].click()\n print(f'more click')\n\n # 몽고디비 연결\n with MongoClient('mongodb://127.0.0.1:27017/') as client:\n mydb = client.mydb\n print('MongoDB connect')\n page = 1\n while True:\n for page_num in range(3,13): # page a tag number\n titles = driver.find_elements_by_class_name('link') \n companies = driver.find_elements_by_class_name('txt')\n data = []\n for title, company in zip(titles, companies[2:12]):\n href = title.find_element(By.TAG_NAME,'a').get_attribute('href')\n data.append({'title': title.text, 'company':company.text, 'link':href, \"create_date\": datetime.datetime.now()}) \n mydb.worknet.insert_many(data)\n print(f'{page} page completion')\n\n # 종료 조건\n if page==max_page:\n print('system exit')\n driver.quit()\n return\n else:\n page = page + 1\n driver.find_element(By.XPATH, f'//*[@id=\"contents\"]/div/div[1]/div[1]/nav/a[{page_num}]').click()\n\ndef scrapping_jobkorea(max_page=10, keyword='AI'):\n for page in range(max_page):\n res = requests.get(f'http://www.jobkorea.co.kr/Search/?stext={keyword}&tabType=recruit&Page_No={str(page)}')\n if res.status_code == 200:\n soup = BeautifulSoup(res.content, 'lxml')\n links = soup.find_all('a', class_='title dev_view')\n companies = soup.find_all('a', class_='name dev_view')\n data = []\n for link, company in zip(links, companies):\n title = link.get_text()\n link = 'http://www.jobkorea.co.kr' + link.get('href')\n company_name = company.get_text()\n dic = {\"title\": title, \"link\": link, \"company\":company_name, \"create_date\": datetime.datetime.now()}\n data.append(dic)\n\n with MongoClient('mongodb://127.0.0.1:27017/') as client:\n mydb = client.mydb\n res = mydb.jobkorea.insert_many(data)\n\nif __name__ == \"__main__\":\n scrapping_jobkorea()\n scrapping_worknet()","repo_name":"aimingh/hello_web","sub_path":"datas/scraping_jobsearch.py","file_name":"scraping_jobsearch.py","file_ext":"py","file_size_in_byte":3180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"22246786287","text":"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\ndef diameterOfBinaryTree(root):\n max_diameter = 0 # Variable to track the maximum diameter\n\n def calculate_height_and_diameter(node):\n nonlocal max_diameter\n\n # Base case: an empty tree has height -1 and diameter 0\n if node is None:\n return -1, 0\n\n # Recursively calculate the height and diameter of the left and right subtrees\n left_height, left_diameter = calculate_height_and_diameter(node.left)\n right_height, right_diameter = calculate_height_and_diameter(node.right)\n\n # Calculate the height of the current node\n height = max(left_height, right_height) + 1\n\n # Calculate the diameter passing through the current node\n diameter = left_height + right_height + 2\n\n # Update the maximum diameter if necessary\n max_diameter = max(max_diameter, diameter)\n\n # Return the height and diameter of the current node\n return height, diameter\n\n calculate_height_and_diameter(root) # Start the calculation from the root\n\n return max_diameter","repo_name":"Rakesh-git-2/patterns","sub_path":"60_DAY_DSA/16_binary_tree_diameter.py","file_name":"16_binary_tree_diameter.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"10614138","text":"import DataVisualizer\nimport GlobalConfigs\nimport numpy as np\nimport pandas as pd\nfrom sklearn import neighbors, tree\nfrom sklearn.model_selection import StratifiedKFold, cross_val_score\nfrom scipy.stats import chi2_contingency, pearsonr\n\nclass LearnedModels():\n stateValue:int = 616\n KnnModel = None\n KnnModelScore = 0\n DecisionTree = None\n DecisionTreeScore = 0\n Columns = [str]\n\n def __init__(self):\n self.KnnModel = neighbors.KNeighborsClassifier()\n self.DecisionTree = tree.DecisionTreeClassifier(max_depth=5)\n\n\ndef LearnAndTest(data:pd.DataFrame) -> dict[str, LearnedModels]:\n print(\"Beginning the process of learning and testing the data...\")\n\n retLearnedModels = {}\n caseTypes = data['CASE DESC'].unique()\n caseTypes.sort()\n\n for caseType in caseTypes:\n retLearnedModels[caseType] = __learningAndTesting(data, caseType)\n\n # Find average model scores\n knnAverageScore = sum(model.KnnModelScore for model in retLearnedModels.values()) / len(retLearnedModels)\n dtAverageScore = sum(model.DecisionTreeScore for model in retLearnedModels.values()) / len(retLearnedModels)\n print(f\"Average KNN Score: {knnAverageScore}\\nAverage Decision Tree Score: {dtAverageScore}\")\n\n print(\"Completed the process of learning and testing the data.\")\n return retLearnedModels\n\ndef Graph(models:dict[str, LearnedModels]) -> None:\n print(\"Beginning the process of graphing the models...\")\n\n caseTypes = models.keys()\n for caseType in caseTypes:\n DataVisualizer.DecisionTree(models[caseType].Columns, models[caseType].DecisionTree, caseType)\n\n print(\"Completed the process of graphing the models.\")\n\ndef CorrelationAnalysis(data:pd.DataFrame) -> None:\n print(\"Beginning the process of finding correlations in the data...\")\n\n caseTypes = data['CASE DESC'].unique()\n caseTypes.sort()\n\n correlationTable = pd.DataFrame(columns=data.columns)\n correlationTable['CASE DESC'] = caseTypes\n correlationTable.set_index('CASE DESC', inplace=True)\n correlationTable.drop(columns=['Count Category'], inplace=True)\n\n for caseType in caseTypes:\n __correlationAnalysis(data, caseType, correlationTable)\n\n correlationTable.to_csv(GlobalConfigs.CORRELATION_ANALYSIS_FILEPATH)\n\n print(\"Completed the process of finding correlations in the data.\")\n\n# Previously planned on using info gain, but realize since I want the tree anyways then using the decision tree model makes more sense.\ndef __learningAndTesting(dataToLearn:pd.DataFrame, caseType:str) -> LearnedModels:\n print(f\"Performing KNN and Decision Tree learning for '{caseType}'...\")\n data = dataToLearn.copy()\n data = data.loc[data['CASE DESC'] == caseType].reset_index(drop=True)\n retModels = LearnedModels()\n\n # Setup K-folds\n skf = StratifiedKFold(n_splits=4, shuffle=True, random_state=retModels.stateValue)\n y = data['Count Category']\n X = data.drop(columns=['Count Category', 'CASE DESC']) # Includes more cleaning that had to come later\n retModels.Columns = X.columns\n\n # Begin training models \n for train_index, test_index in skf.split(X, y):\n X_train = X.loc[train_index]\n y_train = y.loc[train_index]\n\n retModels.KnnModel.fit(X_train, y_train)\n retModels.DecisionTree.fit(X_train, y_train)\n\n # Test the trained models\n print(f\"Performing KNN and Decision Tree testing for '{caseType}'...\")\n\n # Change scoring since classes will be in-balanced\n retModels.KnnModelScore = np.mean(cross_val_score(retModels.KnnModel, X, y, cv=skf.get_n_splits(), scoring='f1_micro'))\n retModels.DecisionTreeScore = np.mean(cross_val_score(retModels.DecisionTree, X, y, cv=skf.get_n_splits(), scoring='f1_micro'))\n\n print(f\"Scores for {caseType} -> KNN = {retModels.KnnModelScore}; Decision Tree = {retModels.DecisionTreeScore}\")\n\n return retModels\n\ndef __correlationAnalysis(data:pd.DataFrame, caseType:str, correlationTable:pd.DataFrame) -> None:\n print(f\"Performing correlation analysis for {caseType}...\")\n \n thisData = data.copy()\n thisData = thisData.loc[data['CASE DESC'] == caseType].reset_index(drop=True)\n\n __continuousWeatherCorrelationAnalysis(thisData, caseType, correlationTable)\n __weatherTypeCorrelationAnalysis(thisData, caseType, correlationTable)\n \ndef __continuousWeatherCorrelationAnalysis(data:pd.DataFrame, caseType:str, correlationTable:pd.DataFrame):\n thisData = data.copy()\n thisData['Count Category'] = thisData['Count Category'].astype('category').cat.codes\n significanceThreshold = 0.05\n\n # Continuous values will use Pearson for correlation analysis\n for weatherColumn in ['AWND', 'PRCP','SNOW','SNWD', 'TAVG']:\n correlation, pValue = pearsonr(thisData[weatherColumn], thisData['Count Category'])\n\n if (pValue <= significanceThreshold):\n correlationTable.at[caseType, weatherColumn] = 'X'\n print(f'Results suggest a significant relationship between {caseType} and {weatherColumn}. | {pValue} <= {significanceThreshold}')\n\ndef __weatherTypeCorrelationAnalysis(data:pd.DataFrame, caseType:str, correlationTable:pd.DataFrame):\n significanceThreshold = 0.05\n\n # Weather Type columns will use chi2 test for correlation analysis since they have binary outputs\n for weatherType in ['WT01', 'WT02', 'WT03', 'WT04', 'WT05', 'WT06', 'WT08', 'WT09', 'WT10', 'WT13', 'WT14', 'WT16', 'WT18', 'WT21', 'WT22']:\n contingencyTable = pd.crosstab(data['Count Category'], data[weatherType])\n chi2Result = chi2_contingency(observed=contingencyTable)\n\n if (chi2Result.pvalue <= significanceThreshold):\n correlationTable.at[caseType, weatherType] = 'X'\n print(f'Results suggest a significant relationship between {caseType} and {weatherType}. | {chi2Result.pvalue} <= {significanceThreshold}')\n","repo_name":"NWEenglish/GVSU-CIS635-DataMiningTermProject","sub_path":"Code/DataLearning.py","file_name":"DataLearning.py","file_ext":"py","file_size_in_byte":5851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"17087328575","text":"class gamer:\r\n def __init__(self, NAME, LEVEL, SEVER):\r\n self.NAME = NAME\r\n self.LEVEL = LEVEL\r\n self.SEVER = SEVER\r\n\r\nNAME = input('닉네임은? :')\r\nLEVEL = int(input('레벨은? :'))\r\nSEVER = input('서버는? :')\r\n\r\nG = gamer(NAME, LEVEL, SEVER)\r\n\r\nprint('NAME : %s'%G.NAME)\r\nprint('LEVEL : %d'%G.LEVEL)\r\nprint('SEVER : %s'%G.SEVER)\r\n","repo_name":"zombiecode12/python","sub_path":"class2 - 2.py","file_name":"class2 - 2.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"16053973149","text":"# -*- coding: utf-8 -*-\nfrom vkapp.bot.logic.user_filters import StatsFilter, ProposeNewsFilter, AdminChatFilter\n\nclass StateMachine(object):\n def __init__(self):\n self.state = None\n self.user_struct = None\n self.filters = [StatsFilter(), ProposeNewsFilter(), AdminChatFilter()]\n\n def fire(self, trigger, uid, update):\n # trigger.user = self.user\n trigger.current_uid = uid\n self.user_struct = trigger.queue_machine.get_user_struct(uid)\n self.state = self.user_struct.state\n\n self.user_struct.push(update)\n\n print('STATE=',self.state)\n\n for f in self.filters:\n filtered_state = f._on_process(self.state, trigger)\n if filtered_state:\n self.to_state(filtered_state, trigger)\n trigger.queue_machine.get_user_struct(uid).state = self.state\n return\n\n new_state = self.state._on_trigger(trigger)\n self.to_state(new_state, trigger)\n trigger.queue_machine.get_user_struct(uid).state = self.state\n\n def to_state(self, new_state, trigger):\n if not new_state:\n return self.state\n\n if new_state == self.state:\n reenter_state = self.state._on_enter(trigger)\n self.to_state(reenter_state, trigger)\n return\n\n exit_state = self.state._on_exit(trigger)\n if exit_state:\n self.to_state(exit_state, trigger)\n return\n\n self.state = new_state\n\n enter_state = self.state._on_enter(trigger)\n if enter_state:\n self.to_state(enter_state, trigger)\n return\n\n#global_state_machine = StateMachine()\n\n\n","repo_name":"ParuninPavel/lenta4_hack","sub_path":"vkapp/bot/logic/core/StateMachine.py","file_name":"StateMachine.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"72232392570","text":"from functions import *\n\n################################\n# PAGINA: \"Cardmarket\"\n\nwith st.form(key = 'cardmarket_seller_carte'):\n st.subheader(\"Seleziona venditori\")\n\n Extimate_Cards = st.checkbox(\"Extimate-cards\")\n Jinzo81 = st.checkbox(\"Jinzo81\")\n Jlter94 = st.checkbox(\"Jolter94\")\n KalosGames = st.checkbox(\"KalosGames\")\n TCGEmpire = st.checkbox(\"TCGEmpire\")\n Zuzu_fantasia = st.checkbox(\"Zuzu-Fantasia\")\n CardsMania = st.checkbox('CardsMania')\n Goatinho = st.checkbox(\"goatinho\")\n ChronikTM = st.checkbox(\"ChronikTM\")\n Galactus_roma = st.checkbox(\"galactus-roma\")\n Lop_vi = st.checkbox(\"lop-vi\")\n Fbgame = st.checkbox(\"Fbgame\")\n Blastercards = st.checkbox(\"Blastercards\")\n Angeli_e_draghi = st.checkbox(\"Angeli_e_draghi\")\n\n carta_input = st.text_input(\"Carta da cercare:\")\n\n button_cardmarket = st.form_submit_button(\"Ottieni prezzi di vendita\")\n\nif button_cardmarket:\n lista_seller = []\n if Extimate_Cards:\n lista_seller.append(\"Extimate-cards\")\n if Jinzo81:\n lista_seller.append(\"Jinzo81\")\n if Jlter94:\n lista_seller.append(\"Jolter94\")\n if KalosGames:\n lista_seller.append(\"KalosGames\")\n if TCGEmpire:\n lista_seller.append(\"TCGEmpire\")\n if Zuzu_fantasia:\n lista_seller.append(\"Zuzu-Fantasia\")\n if CardsMania:\n lista_seller.append('CardsMania')\n if Goatinho:\n lista_seller.append(\"goatinho\")\n if ChronikTM:\n lista_seller.append(\"ChronikTM\")\n if Galactus_roma:\n lista_seller.append(\"galactus-roma\")\n if Lop_vi:\n lista_seller.append(\"lop-vi\")\n if Fbgame:\n lista_seller.append(\"Fbgame\")\n if Blastercards:\n lista_seller.append(\"Blastercards\")\n if Angeli_e_draghi:\n lista_seller.append(\"Angeli-e-Draghi\")\n\n carta = carta_input.replace(' ', '+')\n\n with st.spinner('Recuperando i prezzi da CardMarket...'):\n\n # Print card name and image\n get_image_from_api(carta_input)\n\n for index, venditore in enumerate(lista_seller):\n url = \"https://www.cardmarket.com/it/YuGiOh/Users/\" + venditore + '/Offers/Singles?name=' + carta\n page = requests.get(url)\n content = html.fromstring(page.content)\n prezzo_minore = 99999\n nome_carta = \"\"\n for i in range(1,21):\n xpath = \"/html/body/main/section/div[3]/div[2]/div[\" + str(i) + \"]/div[5]/div[1]/div/div/span\"\n xpath_nome = \"/html/body/main/section/div[3]/div[2]/div[\" + str(i) + \"]/div[4]/div/div[1]/a\"\n xpath_condizione = \"/html/body/main/section/div[3]/div[2]/div[\" + str(i) + \"]/div[4]/div/div[2]/div/div[1]/a[2]/span\"\n xpath_disponibilita = \"/html/body/main/section/div[3]/div[2]/div[\" + str(i) + \"]/div[5]/div[2]/span\"\n \n try:\n prezzo_str = content.xpath(xpath)\n prezzo_str = prezzo_str[0].text[:-2]\n prezzo = float(prezzo_str.replace(',','.'))\n if prezzo < prezzo_minore: \n nome_riga = content.xpath(xpath_nome)[0].text\n if nome_carta == \"\":\n nome_carta = nome_riga\n prezzo_minore = prezzo\n condizione_carta = content.xpath(xpath_condizione)[0].text\n disponibilita = content.xpath(xpath_disponibilita)[0].text\n elif nome_riga == nome_carta:\n prezzo_minore = prezzo\n condizione_carta = content.xpath(xpath_condizione)[0].text\n disponibilita = content.xpath(xpath_disponibilita)[0].text\n except:\n continue\n if prezzo_minore != 99999:\n if condizione_carta in (\"PO\", \"PL\"): condizione_carta = '' + condizione_carta + ''\n if condizione_carta in (\"LP\", \"GD\"): condizione_carta = '' + condizione_carta + ''\n if condizione_carta in (\"EX\", \"NM\", \"MT\"): condizione_carta = '' + condizione_carta + ''\n output = f'{venditore}: **{prezzo_minore}** € - '\n output = output + f'*{nome_carta}* - {condizione_carta} - '\n output = output + f'qta: {disponibilita} - 🌍 [link]({url})'\n st.markdown(output, unsafe_allow_html=True)\n else:\n st.write(f\"{venditore}: -\")","repo_name":"FGrattoni/ELO-YGO","sub_path":"Deprecated pages/07_🛒 Cardmarket.py","file_name":"07_🛒 Cardmarket.py","file_ext":"py","file_size_in_byte":4553,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"28470050174","text":"for a in range(1, 10):\n print(\"? A\", a, flush=True)\n resp = int(input())\n if resp == 1:\n for b in range(1, 10):\n print(\"? B\", b, flush=True)\n resp = int(input())\n if resp == 1:\n print(\"!\", a + b)\n break\n break\n\n\"\"\"\n인터랙티브는 처음인데 생소하고 신기하네 ㅋㅋㅋ\n\"\"\"\n","repo_name":"909ma/Repository-for-Study","sub_path":"백준/Python BOJ Bundle in Math. Vol 1 H번 A+B - 10.py","file_name":"Python BOJ Bundle in Math. Vol 1 H번 A+B - 10.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"40546154152","text":"import torch.nn as nn\nimport torch.nn.functional as F\nimport torch\n\n\ndef get_target_tensor(input_tensor, mode):\n # Source tensor = 0.0\n # Target tensor = 1.0\n source_tensor = torch.FloatTensor(1).fill_(0.0)\n target_tensor = torch.FloatTensor(1).fill_(1.0)\n source_tensor = source_tensor.expand_as(input_tensor)\n target_tensor = target_tensor.expand_as(input_tensor)\n if mode == 'source':\n return source_tensor\n elif mode == 'target':\n return target_tensor\n\n\nclass PixAdvLoss(nn.Module):\n\n def __init__(self, args, reduction='none', ignore_index=255, size_average=True):\n super(PixAdvLoss, self).__init__()\n self.args = args\n self.reduction = reduction\n self.ignore_index = ignore_index\n self.size_average = size_average\n self.criterion_d = nn.BCEWithLogitsLoss(reduction=self.reduction)\n\n def forward(self, parser_prediction, discriminator_pred, labels, fool=\"source\", name=None):\n def get_balance(target_labels):\n balance = target_labels.clone()\n balance = balance.type(torch.FloatTensor)\n\n for i, label in enumerate(target_labels):\n classes = label.unique(sorted=True)\n pixels_count = torch.stack([(label == c).sum() for c in classes])\n tot_pixels = sum(pixels_count)\n for cl, px_count in zip(classes, pixels_count):\n balance[i][balance[i] == float(cl.item())] = 1 - (px_count.item() / tot_pixels.item())\n return balance\n\n # Get fool tensor\n fool_tensor = get_target_tensor(discriminator_pred, fool).to(self.args.gpu_ids[0])\n # Compute discriminator loss (domain prediction) with fooling tensor\n fooling_loss = self.criterion_d(discriminator_pred, fool_tensor).squeeze()\n # Exploit target prediction and target labels to compute domain shift\n domain_shift = F.cross_entropy(parser_prediction, labels, reduction=self.reduction, ignore_index=self.ignore_index)\n # Exploit target ground truth to compute classes balances (for each pixel b = 1 - #pc/#totp)\n classes_balance = get_balance(labels).to(self.args.gpu_ids[0])\n # Compute final loss\n loss = fooling_loss * domain_shift * classes_balance\n\n # Return loss\n if self.size_average:\n return loss.mean()\n else:\n return loss.sum()\n\n\nclass KnowledgeDistillationLoss(nn.Module):\n\n def __init__(self, reduction='mean', alpha=1.):\n super().__init__()\n self.reduction = reduction\n self.alpha = alpha\n\n def forward(self, inputs, targets, gt, mask=None):\n inputs = inputs.narrow(1, 0, targets.shape[1])\n outputs = torch.log_softmax(inputs, dim=1)\n labels = torch.softmax(targets * self.alpha, dim=1)\n loss = (outputs * labels).mean(dim=1)\n\n if mask is not None:\n loss = loss * mask.float()\n if self.reduction == 'mean':\n outputs = -torch.mean(loss)\n elif self.reduction == 'sum':\n outputs = -torch.sum(loss)\n else:\n outputs = -loss\n return outputs\n\n\n# Cross Entropy loss used for the semantic segmentation model\nclass CrossEntropy2d(nn.Module):\n\n def __init__(self, reduction='mean', ignore_label=255):\n super(CrossEntropy2d, self).__init__()\n self.reduction = reduction\n self.ignore_label = ignore_label\n\n def forward(self, predict, target, weight=None):\n \"\"\"\n Args:\n predict:(n, c, h, w)\n target:(n, h, w)\n weight (Tensor, optional): a manual rescaling weight given to each class.\n If given, has to be a Tensor of size \"nclasses\"\n \"\"\"\n assert not target.requires_grad\n assert predict.dim() == 4\n assert target.dim() == 3\n assert predict.size(0) == target.size(0), \"{0} vs {1} \".format(predict.size(0), target.size(0))\n assert predict.size(2) == target.size(1), \"{0} vs {1} \".format(predict.size(2), target.size(1))\n assert predict.size(3) == target.size(2), \"{0} vs {1} \".format(predict.size(3), target.size(3))\n\n n, c, h, w = predict.size()\n target_mask = (target >= 0) * (target != self.ignore_label)\n target = target[target_mask]\n predict = predict.transpose(1, 2).transpose(2, 3).contiguous()\n predict = predict[target_mask.view(n, h, w, 1).repeat(1, 1, 1, c)].view(-1, c)\n loss = F.cross_entropy(predict, target, weight=weight, reduction=self.reduction)\n\n return loss\n\n\nclass FocalLoss(nn.Module):\n \"\"\"\n This is a implementation of Focal Loss with smooth label cross entropy supported which is proposed in\n 'Focal Loss for Dense Object Detection. (https://arxiv.org/abs/1708.02002)'\n Focal_Loss= -1*alpha*(1-pt)*log(pt)\n :param num_class:\n :param alpha: (tensor) 3D or 4D the scalar factor for this criterion\n :param gamma: (float,double) gamma > 0 reduces the relative loss for well-classified examples (p>0.5) putting more\n focus on hard misclassified example\n :param smooth: (float,double) smooth value when cross entropy\n :param size_average: (bool, optional) By default, the losses are averaged over each loss element in the batch.\n \"\"\"\n\n def __init__(self, num_class, alpha=0.25, gamma=2.0, balance_index=2, size_average=True, ignore_label=255):\n super(FocalLoss, self).__init__()\n self.num_class = num_class\n self.alpha = alpha\n self.gamma = gamma\n self.size_average = size_average\n self.eps = 1e-6\n self.ignore_label = ignore_label\n\n if isinstance(self.alpha, (list, tuple)):\n assert len(self.alpha) == self.num_class\n self.alpha = torch.Tensor(list(self.alpha))\n elif isinstance(self.alpha, (float,int)):\n assert 0-1\n alpha = torch.ones((self.num_class))\n alpha *= 1-self.alpha\n alpha[balance_index] = self.alpha\n self.alpha = alpha\n elif isinstance(self.alpha,torch.Tensor):\n self.alpha = self.alpha\n else:\n raise TypeError('Not support alpha type, expect `int|float|list|tuple|torch.Tensor`')\n\n def forward(self, logit, target):\n logit = F.softmax(logit, dim=1)\n n, c, h, w = logit.size()\n target_mask = (target >= 0) * (target != self.ignore_label)\n target = target[target_mask]\n logit = logit.transpose(1, 2).transpose(2, 3).contiguous()\n logit = logit[target_mask.view(n, h, w, 1).repeat(1, 1, 1, c)].view(-1, c)\n target = target.view(-1, 1)\n\n # ----------memory saving way--------\n pt = logit.gather(1, target).view(-1) + self.eps # avoid apply\n logpt = pt.log()\n\n if self.alpha.device != logpt.device:\n alpha = self.alpha.to(logpt.device)\n alpha_class = alpha.gather(0,target.view(-1))\n logpt = alpha_class*logpt\n loss = -1 * torch.pow(torch.sub(1.0, pt), self.gamma) * logpt\n\n if self.size_average:\n loss = loss.mean()\n else:\n loss = loss.sum()\n return loss\n","repo_name":"taveraantonio/PixDA","sub_path":"utils/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":7258,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"77"} +{"seq_id":"23921241303","text":"import inspect\nimport json\nimport logging\nimport os\nfrom typing import Dict, List\n\nfrom helpers.Target import Target\n\ntry:\n from config import appname\nexcept ImportError:\n appname = \"bgsBuddy\"\n\n# test\n# Npc name, faction name\nglobal_target_factions: Dict[str, Target] = {}\ntry:\n plugin_name\nexcept NameError:\n plugin_name = os.path.basename(os.path.dirname(__file__))\n\n#\n# Dictionary/JSON file I/O\n#\ndef getDataFilePath(fName: str) -> str:\n cwd = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n cwd = os.path.join(cwd, fName)\n cwd = os.path.abspath(cwd)\n return cwd\n\n\ncwd = getDataFilePath('addresses.jsonl')\nwith open(cwd) as f:\n data: Dict[str, str] = json.load(f)\n\ndlen = len(data)\n# logger.info(f\"{dlen} items loaded in dict\")\n\nglobal_system_address_to_name: Dict[str, str] = {}\nglobal_system_name_to_address: Dict[str, str] = {}\n\nfor k in data.keys():\n key = str(k)\n val = str(data[key])\n global_system_name_to_address[key] = val\n global_system_address_to_name[val] = key\n\n\n#\n# Global logger\n#\n\ndef init_logger():\n global logger\n logger_name = f'{appname}.{plugin_name}'\n logger = logging.getLogger(logger_name)\n # If the Logger has handlers then it was already set up by the core code, else\n # it needs setting up here.\n if not logger.hasHandlers():\n level = logging.INFO # So logger.info(...) is equivalent to print()\n\n logger.setLevel(level)\n logger_channel = logging.StreamHandler()\n logger_formatter = logging.Formatter(\n f'%(asctime)s - %(name)s - %(levelname)s - %(module)s:%(lineno)d:%(funcName)s: %(message)s')\n logger_formatter.default_time_format = '%Y-%m-%d %H:%M:%S'\n logger_formatter.default_msec_format = '%s.%03d'\n logger_channel.setFormatter(logger_formatter)\n logger.addHandler(logger_channel)\n\n\ndef saveLocalDictionary(dictionary: Dict, fName: str):\n global logger\n cwd = getDataFilePath(fName)\n with open(cwd, 'w') as fp:\n json.dump(dictionary, fp)\n logger.info(f\"Saved dict to >{cwd}<\")\n\n#\n# Sometimes star systems are identified by their name, other times by their address.\n# This (imperfectly) correlates the two. There are a few star systems with identical names.\n# There are probably star systems that are identified by two different names (eg Delphi).\n#\ndef add_system_and_address(sys: str, add: str):\n global global_system_address_to_name\n global global_system_name_to_address\n\n if sys not in global_system_name_to_address:\n global_system_address_to_name[add] = sys\n global_system_name_to_address[sys] = add\n sz = len(global_system_address_to_name)\n logger.info(f\"Adding sys={sys}, add={add}, nitems={sz} and saving addresses.jsonl\")\n saveLocalDictionary(global_system_name_to_address, \"addresses.jsonl\")\n # print(json.dumps(global_system_address_to_name))\n\n\ndef get_system_by_address(add: str) -> str:\n global global_system_address_to_name\n ret: str = global_system_address_to_name.get(add)\n sz = len(global_system_address_to_name)\n\n logger.info(f\"Finding sys={ret}, add={add}, nitems={sz}\")\n return ret\n\n\ndef get_address_by_system(sys: str):\n global global_system_name_to_address\n\n return global_system_name_to_address.get(sys)\n\ndef initials(foo: str):\n xs = (foo)\n name_list = xs.split()\n\n initials = \"\"\n\n for name in name_list: # go through each name\n if any(not str.isalpha(c) for c in name):\n initials += name\n else:\n initials += name[0].upper() # append the initial\n\n return initials\n\ndef print_system_initials():\n global_system_name_to_address\n for key in global_system_name_to_address.keys():\n short = initials(key)\n print(f\"{key} - {short}\")\n#\n# Keeps track of information about targeted ships\n#\nship_types: Dict[str, str] = {\n \"adder\" : \"Adder\",\n \"anaconda\" : \"Anaconda\",\n \"asp\" : \"Asp\",\n \"asp_scout\" : \"Asp Scout\",\n \"belugaliner\" : \"Beluga Liner\",\n \"cobramkiii\" : \"Cobra Mk III\",\n \"cobramkiv\" : \"Cobra Mk IV\",\n \"cutter\" : \"Imperial Cutter\",\n \"diamondback\" : \"Diamondback Scout\",\n \"diamondbackxl\" : \"Diamondback Explorer\",\n \"dolphin\" : \"Dolphin\",\n \"eagle\" : \"Eagle\",\n \"empire_courier\" : \"Imperial Courier\",\n \"empire_eagle\" : \"Imperial Eagle\",\n \"empire_fighter\" : \"Imperial Fighter\",\n \"empire_trader\" : \"Imperial Trader\",\n \"federation_corvette\" : \"Federal Corvette\",\n \"federation_dropship\" : \"Federal Dropship\",\n \"federation_dropship_mkii\": \"Federal Dropship Mk II\",\n \"federation_fighter\" : \"Federal Fighter\",\n \"federation_gunship\" : \"Federal Gunship\",\n \"ferdelance\" : \"Fer-de-Lance\",\n \"gdn_hybrid_fighter_v1\" : \"Guardian Hybrid Fighter V1\",\n \"gdn_hybrid_fighter_v3\" : \"Guardian Hybrid Fighter V2\",\n \"hauler\" : \"Hauler\",\n \"independant_trader\" : \"Independent Trader\",\n \"independent_fighter\" : \"Independent Fighter\",\n \"krait_light\" : \"Krait Light\",\n \"krait_mkii\" : \"Krait Mk II\",\n \"mamba\" : \"Mamba\",\n \"orca\" : \"Orca\",\n \"python\" : \"Python\",\n \"sidewinder\" : \"Sidewinder\",\n \"type6\" : \"Type-6 Transporter\",\n \"type7\" : \"Type-7 Transporter\",\n \"type9\" : \"Type-9 Heavy\",\n \"type9_military\" : \"Type-9 Military\",\n \"typex\" : \"Type 10 Defender\",\n \"typex_2\" : \"Type 10 Defender (mod 2)\",\n \"typex_3\" : \"Type 10 Defender (mod 3)\",\n \"viper\" : \"Viper\",\n \"viper_mkiv\" : \"Viper Mk IV\",\n \"vulture\" : \"Vulture\"}\n\n\ndef add_target_faction(name: str, targ: Target):\n global global_target_factions\n logger.info(\"Adding target to global dict\")\n global_target_factions[name] = targ\n\n\ndef get_target_faction(name: str):\n global global_target_factions\n\n if name in global_target_factions:\n targ: Target = global_target_factions[name]\n return targ.getFaction()\n\n return None # \"Unknown Faction\"\n\n\ndef get_target_string(name: str):\n global global_target_factions\n ret = \"Unknown Target\"\n\n if name in global_target_factions:\n targ: Target = global_target_factions[name]\n ship_name = get_ship_name(targ.ship)\n ret = f\"( {ship_name}, {targ.rank})\"\n\n return ret\n\n\ndef clear_target_dictionary():\n global global_target_factions\n global_target_factions.clear()\n\n\ndef get_ship_name(name: str):\n global ship_types\n\n if name in ship_types:\n return ship_types[name]\n\n return name\n","repo_name":"HausReport/BgsBuddy","sub_path":"GlobalDictionaries.py","file_name":"GlobalDictionaries.py","file_ext":"py","file_size_in_byte":6942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"21599868185","text":"from bisect import bisect_left\n\nT = int(input())\nfor _ in range(T):\n h,c,t = [int(i) for i in input().split()]\n ct = h\n pt = [[ct,1]]\n p = 1\n for _ in range(50):\n print(ct)\n p += 1\n ct = (c + ct)/2\n pt.append([ct,p])\n print(ct)\n p += 1\n ct = (h + ct)/2\n pt.append([ct,p])\n pt.sort()\n print(pt)\n n = bisect_left(pt, [t,0])\n print(n)\n print(pt[n][1])","repo_name":"Programmerryoki/Competitive-Programming","sub_path":"CodeForces/Educational Codeforces Round 88/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"40722427088","text":"import torch.nn as nn\nfrom attention import Attention\nfrom torch import Tensor as T\nfrom torch.nn import Parameter as P\nfrom torch.autograd import Variable as V\nimport torch.nn.functional as F\nimport math\nimport torch as th\nimport torch.nn as nn\n\n\n\nclass MultiHeadAttention(nn.Module):\n \"\"\"\n Take in model size and number of heads.\n \"\"\"\n\n def __init__(self,\n d_q : int,\n d_k : int,\n d_model : int = 768,\n dropout : float = 0.1,\n h : int = 1, \n transform_Q : bool = False,\n transform_K : bool = False,\n transform_V : bool = False,\n ):\n super().__init__()\n assert d_model % h == 0\n\n self.d_qkv = [d_q, d_k, d_k]\n self.d_model_h = d_model // h\n self.h = h\n \n self.transform_Q = transform_Q\n self.transform_K = transform_K\n self.transform_V = transform_V\n \n if self.transform_Q:\n self.linear_layers_Q = nn.Linear(self.d_qkv[0], d_model)\n if self.transform_K:\n self.linear_layers_K = nn.Linear(self.d_qkv[1], d_model)\n if self.transform_V:\n self.linear_layers_V = nn.Linear(self.d_qkv[2], d_model)\n\n self.transform_QKV = self.transform_Q or self.transform_K or self.transform_V\n\n self.output_linear = nn.Linear(d_model, d_model)\n self.attention = Attention()\n\n self.layernorm = nn.LayerNorm(d_model, eps=1e-05, elementwise_affine=True)\n self.dropout = nn.Dropout(p=dropout)\n\n def forward(self, query, key, ctx_mask=None, key_mask=None):\n value = key\n batch_size = query.size(0)\n\n # 1) Do all the linear projections in batch from d_model => h x d_k\n if self.transform_QKV:\n if self.transform_Q:\n query = self.linear_layers_Q(query)\n if self.transform_K:\n key = self.linear_layers_K(key)\n if self.transform_V:\n value = self.linear_layers_V(value)\n \n query, key, value = [x.view(batch_size, -1, self.h, self.d_model_h).transpose(1, 2) for x in (query, key, value)]\n\n # 2) Apply attention on all the projected vectors in batch.\n x, attn = self.attention(query, key, value, mask=ctx_mask, dropout=self.dropout, key_mask=key_mask)\n\n # 3) \"Concat\" using a view and apply a final linear.\n x = x.transpose(1, 2).contiguous().view(batch_size, -1, self.h * self.d_model_h)\n\n x = self.output_linear(x)\n\n x = self.dropout(x)\n \n # norm_x = x\n norm_x = self.layernorm(x)\n\n attn = attn.mean(dim=1).max(dim=-1)[0]\n\n # attn = attn.max(dim=1)[0].max(dim=-1)[0]\n\n # attn *= ctx_mask\n # attn /= (attn.sum(dim=-1)[:, None] + 1e-5)\n\n return x, norm_x, attn[:, None, :], attn.max(dim=1)[0]\n\n\nclass MultiHeadAttention_raw(nn.Module):\n \"\"\"\n Take in model size and number of heads.\n \"\"\"\n\n def __init__(self, d_q, d_k, d_model=768, dropout=0.1, h=1):\n super().__init__()\n assert d_model % h == 0\n\n self.d_model_h = d_model // h\n self.h = h\n self.d_qkv = [d_q, d_k, d_k]\n self.linear_layers = nn.ModuleList([nn.Linear(self.d_qkv[i], d_model) for i in range(3)])\n self.output_linear = nn.Linear(d_model, d_model)\n self.attention = Attention()\n\n self.layernorm = nn.LayerNorm(d_model, eps=1e-05, elementwise_affine=True)\n self.dropout = nn.Dropout(p=dropout)\n\n def forward(self, query, key, ctx_mask=None, key_mask=None):\n value = key\n batch_size = query.size(0)\n\n # 1) Do all the linear projections in batch from d_model => h x d_k\n query, key, value = [l(x).view(batch_size, -1, self.h, self.d_model_h).transpose(1, 2)\n for l, x in zip(self.linear_layers, (query, key, value))]\n # key = key.view(batch_size, -1, self.h, self.d_model_h).transpose(1, 2)\n # value = key\n # query = self.linear_layers[0](query).view(batch_size, -1, self.h, self.d_model_h).transpose(1, 2)\n\n # 2) Apply attention on all the projected vectors in batch.\n x, attn = self.attention(query, key, value, mask=ctx_mask, dropout=self.dropout, key_mask=key_mask)\n\n # 3) \"Concat\" using a view and apply a final linear.\n x = x.transpose(1, 2).contiguous().view(batch_size, -1, self.h * self.d_model_h)\n\n x = self.output_linear(x)\n\n x = self.dropout(x)\n \n norm_x = x\n\n\n # attn = attn.mean(dim=1).max(dim=-1)[0]\n attn_maxpool = attn.max(dim=1)[0].max(dim=-1)[0]\n\n # attn *= ctx_mask\n # attn /= (attn.sum(dim=-1)[:,None]+1e-5)\n\n return x, norm_x, attn_maxpool[:,None,:]","repo_name":"wonderseen/OVC-MMT","sub_path":"multi_head.py","file_name":"multi_head.py","file_ext":"py","file_size_in_byte":4740,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"77"} +{"seq_id":"70039348730","text":"from fastapi import FastAPI\n\n\ndef get_application() -> FastAPI:\n \"\"\"App Factory\"\"\"\n application = FastAPI(\n title=\"Health Check\",\n version=\"0.0.1\",\n )\n\n @application.get(\"/health/\")\n async def get_health():\n return {\"status\": \"OK\"}\n\n return application\n\n\napp = get_application()\n","repo_name":"andy-takker/ma_1_docker","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"2414301182","text":"import argparse\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nfrom torchvision import models\n\nfrom utils import *\nfrom datasets import *\nfrom models import *\nfrom visualize import Visualizer\nfrom deeplab import Res50_Deeplab\n\n\nglobal feat_target\ndef get_feat_target(self, input, output):\n feat_target.append(output)\n # feat_norm = torch.norm(output, p=2, dim=1, keepdim=True)\n # feat_target.append(torch.div(output, feat_norm))\n\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--exp_name\", type=str, default='cls1', help=\"experiment name\")\n parser.add_argument(\"--n_epochs\", type=int, default=300, help=\"number of epochs\")\n parser.add_argument(\"--batch_size\", type=int, default=8, help=\"size of each image batch\")\n parser.add_argument(\"--n_cpu\", type=int, default=8, help=\"number of cpu threads for batch generation\")\n parser.add_argument(\"--gpu\", type=int, default=0, help=\"gpu id\")\n parser.add_argument(\"--img_size\", type=int, default=256, help=\"size of each image dimension\")\n parser.add_argument(\"--feat_size\", type=int, default=100, help=\"size of each feat dimension\")\n parser.add_argument(\"--k\", type=int, default=2, help=\"number of parts per class\")\n parser.add_argument(\"--n_classes\", type=int, default=1, help=\"number of classes\")\n parser.add_argument(\"--w_cls\", type=float, default=0, help=\"classification loss weight\")\n parser.add_argument(\"--w_sem\", type=float, default=1e4, help=\"classification loss weight\")\n parser.add_argument(\"--w_ort\", type=float, default=0, help=\"classification loss weight\")\n parser.add_argument(\"--w_geo\", type=float, default=1e2, help=\"classification loss weight\")\n parser.add_argument(\"--w_eqv\", type=float, default=1e3, help=\"classification loss weight\")\n parser.add_argument(\"--data_dir\", type=str, default='/tmp4/hank/VOCdevkit/VOC2012/', help=\"path to data files\")\n parser.add_argument(\"--weights\", type=str, help=\"if specified starts from checkpoint model\")\n parser.add_argument(\"--checkpoint_interval\", type=int, default=50, help=\"interval between saving model weights\")\n parser.add_argument(\"--evaluation_interval\", type=int, default=5, help=\"interval evaluations on validation set\")\n opt = parser.parse_args()\n print(opt)\n\n k = opt.k\n nc = opt.n_classes\n h, w = opt.feat_size, opt.feat_size\n\n viz = Visualizer(opt.exp_name)\n device = torch.device(\"cuda:\"+str(opt.gpu) if torch.cuda.is_available() else \"cpu\")\n\n\n # ================= Prepare training data ==================\n if nc == 1:\n class_names = ['horse']\n elif nc == 2:\n class_names = ['cow', 'horse']\n elif nc == 5:\n class_names = ['cat', 'cow', 'dog', 'horse', 'sheep']\n\n datasets = {x: VOCDataset(opt.data_dir, x, class_names, opt.img_size, h) for x in ['train', 'val']}\n dataloaders = {x: torch.utils.data.DataLoader(datasets[x], batch_size=opt.batch_size, shuffle=True,\n num_workers=opt.n_cpu) for x in ['train', 'val']}\n\n class_weights = []\n for i in range(nc):\n pos = 1. * datasets['train'].size[i] / len(datasets['train'])\n class_weights.append((1-pos) / pos)\n class_weights = torch.Tensor(class_weights).to(device)\n\n\n # ===================== Base model =====================\n model = Res50_Deeplab(nc * k + 1).to(device)\n params = model.state_dict()\n\n resnet = models.resnet50(pretrained=True).to(device)\n state_dict = resnet.state_dict().copy()\n for name, param in params.items():\n if name in state_dict and param.size() == state_dict[name].size():\n params[name].copy_(state_dict[name])\n model.load_state_dict(params)\n\n\n # ==================== Part basis ======================\n part_basis = PartBasis(1024, nc * k).to(device)\n\n\n # =================== Reference feature =================\n vgg19 = models.vgg19(pretrained=True).to(device)\n vgg19.eval()\n\n global feat_target\n vgg19.features[31].register_forward_hook(get_feat_target)\n vgg19.features[35].register_forward_hook(get_feat_target)\n\n\n # ================= training settings ================\n optimizer = optim.SGD(model.parameters(), lr=1e-4, momentum=0.9, weight_decay=5e-4)\n optimizer_b = optim.SGD(part_basis.parameters(), lr=1e-1, momentum=0.9, weight_decay=5e-4)\n\n exp_lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.5)\n exp_lr_scheduler_b = lr_scheduler.StepLR(optimizer_b, step_size=100, gamma=0.5)\n\n\n # ==================== Start training ======================\n coord = np.tile(1. * np.arange(w) / (w-1), (h, 1))\n u = torch.from_numpy(coord).to(device).float()\n v = torch.from_numpy(coord.transpose()).to(device).float()\n\n for epoch in range(opt.n_epochs):\n print('Epoch {}/{}'.format(epoch, opt.n_epochs-1))\n\n if epoch % opt.evaluation_interval == 0:\n phases = ['train', 'val']\n else:\n phases = ['train']\n\n for phase in phases:\n if phase == 'train':\n model.train()\n part_basis.train()\n else:\n model.eval()\n part_basis.eval()\n\n running_loss_cls = 0.0\n running_loss_geo = 0.0\n running_loss_sem = 0.0\n running_loss_ort = 0.0\n running_loss_eqv = 0.0\n running_corrects = 0\n\n # Iterate over data\n for inputs, saliency, labels in dataloaders[phase]:\n inputs = inputs.to(device)\n labels = labels.to(device)\n saliency = saliency.to(device).float()\n\n nb = inputs.size(0)\n label_mask = torch.zeros((nb, nc), dtype=torch.bool).to(device)\n label_mask = label_mask.scatter_(1, labels.view(-1, 1), 1).repeat_interleave(k, dim=1)\n\n # Zero the parameter gradients\n optimizer.zero_grad()\n optimizer_b.zero_grad()\n\n # Forward\n with torch.set_grad_enabled(phase == 'train'):\n\n outputs = model(inputs)\n outputs = nn.functional.interpolate(outputs, size=(h, w),\n mode='bilinear', align_corners=True)\n\n pams = nn.Softmax(dim=1)(outputs)[:, :-1, :, :]\n pams_masked = pams.masked_select(label_mask.view(-1, nc*k, 1, 1)).view(-1, k, h, w)\n\n\n # Classification loss\n probs = nn.AdaptiveMaxPool2d(output_size=(1, 1))(pams).squeeze()\n _, preds = torch.max(torch.sum(probs.view(-1, nc, k), 2), 1)\n sample_weights = class_weights.index_select(0, labels).view(-1, 1)\n loss_cls = nn.BCELoss(weight=sample_weights)(probs, label_mask.float())\n\n #pams = pams.view(-1, n_classes, k, h, w)\n #select_mask = torch.zeros((inputs.size(0), n_classes), dtype=torch.uint8).to(device)\n #select_mask = select_mask.scatter_(1, labels.view(-1, 1), 1).view(-1, n_classes, 1, 1, 1)\n #pams_selected = torch.masked_select(pams, select_mask).view(-1, k, h, w)\n\n #cams = torch.sum(outputs[:, :-1, :, :].view(-1, n_classes, k, h, w), 2)\n #probs = nn.AdaptiveAvgPool2d(output_size=(1, 1))(cams).view(-1, n_classes)\n #_, preds = torch.max(probs, 1)\n #loss_cls = nn.CrossEntropyLoss(weight=class_weights)(probs, labels)\n\n\n # Semantic loss\n basis = part_basis()\n basis_masked = basis.view(1024, nc, k).index_select(1, labels).transpose(0, 1)\n\n feat_target = []\n _ = vgg19(inputs)\n feat_t = nn.functional.interpolate(torch.cat(feat_target, dim=1), size=(h, w),\n mode='bilinear', align_corners=True)\n\n feat_r = torch.bmm(basis_masked, pams_masked.view(-1, k, h*w)).view(-1, 1024, h, w)\n #feat_r = torch.zeros(feat_t.size()).to(device)\n #for i in range(nb):\n # feat_r[i, :, :, :] = torch.mm(basis_masked[:, i, :],\n # pams_masked[i, :, :, :].view(k, -1)).view(-1, h, w)\n loss_sem = nn.MSELoss()(feat_r, feat_t * saliency)\n\n\n # Orthonormal loss\n wn = torch.norm(basis_masked, p=2, dim=1, keepdim=True)\n ww = basis_masked.div(wn.expand_as(basis_masked) + 1e-9).view(-1, k)\n wwt = torch.matmul(ww.transpose(0, 1), ww)\n loss_ort = nn.MSELoss()(wwt, torch.eye(k).to(device))\n\n\n # Geometric concentration loss\n pams_sum = pams_masked.sum(2, keepdim=True).sum(3, keepdim=True)\n pams_geo = pams_masked.div(pams_sum + 1e-9)\n center_u = (pams_geo * u).sum(2, keepdim=True).sum(3, keepdim=True)\n center_v = (pams_geo * v).sum(2, keepdim=True).sum(3, keepdim=True)\n dist = torch.sqrt((u - center_u)**2 + (v - center_v)**2)\n loss_geo = torch.sum(pams_geo * dist)\n\n\n # Equivariance loss\n inputs = inputs.detach()#.cpu()\n outputs = outputs.detach()#.cpu()\n #inputs_tf = torch.zeros(inputs.size())\n #feat_tf = torch.zeros(outputs.size())\n\n flip = np.random.randint(2)\n angle = np.random.randn()*10\n translate = (np.random.random(2)*0.2).tolist()\n scale = np.random.random()*0.5+1\n shear = np.random.randn()*5\n params_tf = [device, flip, angle, translate, scale]\n\n inputs_tf = spatial_transforms(inputs, *params_tf)\n pams_tf = spatial_transforms(pams, *params_tf)\n\n #for i in range(nb):\n # inputs_tf[i, :, :, :] = transforms_img(inputs[i, :, :, :], *params_tf)\n # for j in range(outputs.size(1)):\n # feat_tf[i, j, :, :] = transforms_pam(outputs[i, j, :, :], *params_tf)\n #pams_tf = nn.Softmax(dim=1)(feat_tf.to(device))\n\n outputs_tf = model(inputs_tf.to(device))\n outputs_tf = nn.functional.interpolate(outputs_tf, size=(h, w),\n mode='bilinear', align_corners=True)\n outputs_tf = nn.LogSoftmax(dim=1)(outputs_tf)[:, :-1, :, :]\n loss_eqv = nn.KLDivLoss()(outputs_tf, pams_tf)\n\n\n loss = opt.w_cls * loss_cls + \\\n opt.w_geo * loss_geo + \\\n opt.w_sem * loss_sem + \\\n opt.w_ort * loss_ort + \\\n opt.w_eqv * loss_eqv\n\n\n # Visualization\n with torch.no_grad():\n if epoch % 5 == 0:\n pams_viz = pams.view(-1, nc * k, h, w)\n pams_tf_viz = pams_tf.view(-1, nc * k, h, w)\n pams_viz = pams_viz / pams_viz.max(2, keepdim=True)[0].max(3, keepdim=True)[0]\n pams_tf_viz = pams_tf_viz / pams_tf_viz.max(2, keepdim=True)[0].max(3, keepdim=True)[0]\n viz.vis_inputs(epoch, inputs, prefix='')\n viz.vis_inputs(epoch, inputs_tf, prefix='_tf')\n viz.vis_inputs(epoch, saliency, prefix='saliency')\n viz.vis_DFF_heatmaps(epoch, pams_viz, threshold=0.1, prefix='pams')\n viz.vis_DFF_heatmaps(epoch, pams_tf_viz, threshold=0.1, prefix='pams_tf')\n\n if phase == 'train':\n viz.vis_losses(epoch, [loss, loss_cls, loss_geo, loss_sem, loss_ort, loss_eqv],\n ['loss_train', 'loss_cls_train', 'loss_geo_train', 'loss_sem_train',\n 'loss_ort_train', 'loss_eqv_train'])\n else:\n viz.vis_losses(epoch, [loss, loss_cls, loss_geo, loss_sem, loss_ort, loss_eqv],\n ['loss_val', 'loss_cls_val', 'loss_geo_val', 'loss_sem_val',\n 'loss_ort_val', 'loss_eqv_val'])\n\n # Backward + optimize only in training phase\n if phase == 'train':\n loss.backward()\n nn.utils.clip_grad_norm_(model.parameters(), 5)\n nn.utils.clip_grad_norm_(part_basis.parameters(), 5)\n optimizer.step()\n optimizer_b.step()\n exp_lr_scheduler.step()\n exp_lr_scheduler_b.step()\n\n # Statistics\n running_loss_cls += loss_cls.item() * nb\n running_loss_geo += loss_geo.item() * nb\n running_loss_sem += loss_sem.item() * nb\n running_loss_ort += loss_ort.item() * nb\n running_loss_eqv += loss_eqv.item() * nb\n running_corrects += torch.sum(preds == labels.data)\n\n epoch_acc = running_corrects.float() / len(datasets[phase])\n epoch_loss_cls = opt.w_cls * running_loss_cls / len(datasets[phase])\n epoch_loss_geo = opt.w_geo * running_loss_geo / len(datasets[phase])\n epoch_loss_sem = opt.w_sem * running_loss_sem / len(datasets[phase])\n epoch_loss_ort = opt.w_ort * running_loss_ort / len(datasets[phase])\n epoch_loss_eqv = opt.w_eqv * running_loss_eqv / len(datasets[phase])\n epoch_loss = epoch_loss_cls + epoch_loss_geo + epoch_loss_sem + epoch_loss_ort + epoch_loss_eqv\n\n print('{} Loss: {:.3f}, Acc: {:.3f}'.format(phase, epoch_loss, epoch_acc))\n print('cls loss:{:.3f}, geo loss:{:.3f}, sem loss:{:.3f}, ort loss:{:.3f}, eqv loss:{:.3f}'.format(\n epoch_loss_cls, epoch_loss_geo, epoch_loss_sem, epoch_loss_ort, epoch_loss_eqv))\n\n if (epoch+1) % opt.checkpoint_interval == 0:\n model_saved = 'checkpoints/model_{}_epoch_{}.pt'.format(opt.exp_name, str(epoch))\n basis_saved = 'checkpoints/basis_{}_epoch_{}.pt'.format(opt.exp_name, str(epoch))\n torch.save(model.state_dict(), model_saved)\n torch.save(part_basis.state_dict(), basis_saved)\n\n print('Training complete.')\n","repo_name":"chhankyao/part_segmentation","sub_path":"my_train.py","file_name":"my_train.py","file_ext":"py","file_size_in_byte":14896,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"21498716117","text":"from p3_app import db\nfrom sqlalchemy import ForeignKey\nfrom sqlalchemy.orm import relationship\n\nclass key_model(db.Model):\n __tablename__ = 'key'\n\n id = db.Column(db.Integer(),primary_key=True)\n corp_code = db.Column(db.Integer())\n corp_name = db.Column(db.String())\n\n corps=relationship('corp_model', back_populates='keys')\n\n def __repr__(self):\n return dict(corp_code = self.corp_code, corp_name = self.corp_name)","repo_name":"snaiws/Project_3","sub_path":"p3_app/Models/key_model.py","file_name":"key_model.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"31804996509","text":"from django.db import models\nfrom django.urls import reverse\nfrom datetime import date\nfrom django.contrib.auth.models import *\n\n\nclass Order(models.Model):\n\n product_name = models.CharField(max_length=300)\n url = models.URLField(max_length=800)\n email = models.EmailField()\n query_name = models.CharField(max_length=30)\n date = models.DateField(default=date.today)\n active = models.BooleanField(default=True)\n category = models.CharField(max_length=35)\n\n def __str__(self):\n return self.product_name\n\n\nclass Product(models.Model):\n\n class Section(models.TextChoices):\n GROCERY = 'Grocery'\n HOUSEHOLD_ESSENTIALS = 'Household Essentials'\n WOMEN = 'Women'\n MEN = 'Men'\n YOUNG_ADULT = 'Young Adult'\n KIDS = 'Kids'\n SHOES = 'Shoes'\n BABY = 'Baby'\n HOME = 'Home'\n FURNITURE = 'Furniture'\n KITCHEN_AND_DINING = 'Kitchen & Dining'\n TOYS = 'Toys'\n ELECTRONICS = 'Electronics'\n VIDEO_GAMES = 'Video Games'\n MOVIES = 'Movies'\n MUSIC = 'Music'\n BOOKS = 'Books'\n SPORTS_AND_OUTDOORS = \"Sports & Outdoors\"\n BEAUTY = 'Beauty'\n PERSONAL_CARE = 'Personal Care'\n HEALTH = 'Health'\n PETS = 'Pets'\n LUGGAGE = 'Luggage'\n SCHOOL_AND_OFFICE_SUPPLIES = 'School & Office Supplies'\n PARTY_SUPPLIES = 'Party Supplies'\n OTHER = 'Other'\n\n category = models.CharField(choices=Section.choices, max_length=100)\n\n user = models.EmailField()\n\n def __str__(self):\n return self.category\n\n\nclass Review(models.Model):\n\n class Rating(models.IntegerChoices):\n ONE = 1\n TWO = 2\n THREE = 3\n FOUR = 4\n FIVE = 5\n\n value = models.IntegerField(choices=Rating.choices)\n user = models.CharField(max_length=20)\n order_id = models.ForeignKey(Order,\n on_delete=models.CASCADE,\n related_name='rreview')\n\n def __str__(self):\n return self.name\n","repo_name":"jcari-dev/Item-Availlability-Checker-with-Email-Notification","sub_path":"django/main_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"18666568396","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\"\"\"\n有一堆石头,每块石头的重量都是正整数。\n\n每一回合,从中选出两块 最重的 石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下:\n\n如果 x == y,那么两块石头都会被完全粉碎;\n如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。\n最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0。\n\"\"\"\n\n\nclass Solution:\n def lastStoneWeight(self, stones) -> int:\n while len(stones) >= 2:\n y = max(stones)\n stones.remove(y)\n x = max(stones)\n stones.remove(x)\n if x != y:\n stones.append(y - x)\n if len(stones) == 0:\n return 0\n return stones[0]\n\n\nstones = [2, 7, 4, 1, 8, 1]\nsol = Solution()\nres = sol.lastStoneWeight(stones)\nprint(res)\n","repo_name":"LikeSco/learn-python","sub_path":"py-exam/1046.lastStoneWeight.py","file_name":"1046.lastStoneWeight.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"24965789823","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# get commends from Amazon\nimport time\nimport json\nimport csv\nimport re\nfrom selectorlib import Extractor\nfrom dateutil import parser as dateparser\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException, WebDriverException\n\n\n# Create an Extractor by reading from the YAML file\ne = Extractor.from_yaml_file('selectors.yml')\noptions = webdriver.ChromeOptions()\noptions.add_argument(\"start-maximized\")\noptions.add_argument(\"disable-infobars\")\noptions.add_argument(\"--disable-extensions\")\noptions.add_experimental_option(\"excludeSwitches\", [\"enable-automation\"])\ndriver = driver = webdriver.Chrome(chrome_options=options,\n executable_path=ChromeDriverManager().install())\n\n# extract html to dict\ndef getDictComm():\n html = driver.page_source.replace('\\n', '')\n return e.extract(html)\n\n# goto next page\ndef NextPage():\n try:\n # wait page load\n time.sleep(3)\n driver.execute_script(\"return arguments[0].scrollIntoView(true);\", WebDriverWait(\n driver, 10).until(EC.element_to_be_clickable((By.XPATH, \"//li[@class='a-last']/a\"))))\n driver.find_element_by_xpath(\n \"//li[@class='a-last']/a\").click()\n print(\"Navigating to Next Page\")\n return True\n except (TimeoutException, WebDriverException) as e:\n print(\"Last page reached\")\n return False\n\n# write dict to scv file\ndef writeToCSV(dictComm, writer):\n for r in dictComm['reviews']:\n r[\"product\"] = dictComm[\"product_title\"]\n r['verified'] = 'Yes' if r['verified'] else 'No'\n r['rating'] = r['rating'].split(\n ' out of')[0] if r['rating'] else 'N/A'\n r['images'] = \" \".join(\n r['images']) if r['images'] else 'N/A'\n r['date'] = dateparser.parse(\n r['date'].split('on ')[-1]).strftime('%d %b %Y')\n writer.writerow(r)\n\n# product_data = []\ndef getAmazonCom():\n with open(\"urls.txt\", 'r') as urllist:\n for url in urllist.readlines():\n driver.get(url)\n html = driver.page_source.replace('\\n', '')\n dictComm = e.extract(html)\n if dictComm:\n productTittle = re.findall(\n r'[^\\*\"/:?\\\\|<>]', dictComm[\"product_title\"].replace(' ', '_'), re.S)\n csvFileName = \"\".join(productTittle) + '.csv'\n with open('comm/'+csvFileName, 'w', encoding='UTF-8', errors='ignore') as outfile:\n writer = csv.DictWriter(outfile, fieldnames=[\"title\", \"content\", \"date\", \"variant\",\n \"images\", \"verified\", \"author\", \"rating\", \"product\"], quoting=csv.QUOTE_ALL)\n writer.writeheader()\n writeToCSV(dictComm, writer)\n while True:\n if NextPage():\n writeToCSV(getDictComm(), writer)\n else:\n break\n driver.close()\n\n\nif __name__ == '__main__':\n getAmazonCom()\n","repo_name":"jhc-shou/data-mining","sub_path":"test/getAmazonReview.py","file_name":"getAmazonReview.py","file_ext":"py","file_size_in_byte":3369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"22969301459","text":"from functools import partial\nimport os\n\nfrom absl.testing import parameterized\nfrom big_vision import utils\nimport chex\nimport flax\nimport jax\nfrom jax.experimental.array_serialization import serialization as array_serial\nimport jax.numpy as jnp\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.io import gfile\n\n\nNDEV = 4\n\n\ndef setUpModule():\n chex.set_n_cpu_devices(NDEV)\n\n\nclass PadShardUnpadTest(chex.TestCase, tf.test.TestCase):\n BATCH_SIZES = [NDEV, NDEV + 1, NDEV - 1, 5 * NDEV, 5 * NDEV + 1, 5 * NDEV - 1]\n DTYPES = [np.float32, np.uint8, jax.numpy.bfloat16, np.int32]\n\n def tearDown(self):\n chex.clear_trace_counter()\n super().tearDown()\n\n @parameterized.product(dtype=DTYPES, bs=BATCH_SIZES)\n def test_basics(self, dtype, bs):\n # Just tests that basic calling works without exploring caveats.\n @partial(utils.pad_shard_unpad, static_argnums=())\n def add(a, b):\n return a + b\n\n x = np.arange(bs, dtype=dtype)\n y = add(x, 10*x)\n chex.assert_type(y.dtype, x.dtype)\n np.testing.assert_allclose(np.float64(y), np.float64(x + 10*x))\n\n @parameterized.parameters(DTYPES)\n def test_min_device_batch_avoids_recompile(self, dtype):\n @partial(utils.pad_shard_unpad, static_argnums=())\n @jax.jit\n @chex.assert_max_traces(n=1)\n def add(a, b):\n return a + b\n\n chex.clear_trace_counter()\n\n for bs in self.BATCH_SIZES:\n x = np.arange(bs, dtype=dtype)\n y = add(x, 10*x, min_device_batch=9) # pylint: disable=unexpected-keyword-arg\n chex.assert_type(y.dtype, x.dtype)\n np.testing.assert_allclose(np.float64(y), np.float64(x + 10*x))\n\n @parameterized.product(dtype=DTYPES, bs=BATCH_SIZES)\n def test_static_argnum(self, dtype, bs):\n @partial(utils.pad_shard_unpad, static_argnums=(1,))\n def add(a, b):\n return a + b\n\n x = np.arange(bs, dtype=dtype)\n y = add(x, 10)\n chex.assert_type(y.dtype, x.dtype)\n np.testing.assert_allclose(np.float64(y), np.float64(x + 10))\n\n @parameterized.product(dtype=DTYPES, bs=BATCH_SIZES)\n def test_static_argnames(self, dtype, bs):\n # In this test, leave static_argnums at the default value too, in order to\n # test the default/most canonical path where `params` are the first arg.\n @partial(utils.pad_shard_unpad, static_argnames=('b',))\n def add(params, a, *, b):\n return params * a + b\n\n x = np.arange(bs, dtype=dtype)\n y = add(5, x, b=10)\n chex.assert_type(y.dtype, x.dtype)\n np.testing.assert_allclose(np.float64(y), np.float64(5 * x + 10))\n\n\nclass TreeTest(tf.test.TestCase):\n\n def setUp(self):\n super().setUp()\n\n self.d1 = {'w1': 1, 'w2': 2, 'w34': (3, 4)}\n self.d1_flat = [1, 2]\n self.d1_flat_jax = jax.tree_flatten(self.d1)[0]\n self.d1_named_flat = [('w1', 1), ('w2', 2), ('w34/0', 3), ('w34/1', 4)]\n self.d1_named_flat_jax = [('w1', 1), ('w2', 2), ('w34/0', 3), ('w34/1', 4)]\n\n self.d2 = {'conv1': {'kernel': 0, 'bias': 1},\n 'conv2': {'kernel': 2, 'bias': 3}}\n self.d2_flat = [1, 0, 3, 2]\n self.d2_flat_jax = jax.tree_flatten(self.d2)[0]\n self.d2_named_flat = [('conv1/bias', 1), ('conv1/kernel', 0),\n ('conv2/bias', 3), ('conv2/kernel', 2)]\n self.d2_named_flat_jax = [('conv1/bias', 1), ('conv1/kernel', 0),\n ('conv2/bias', 3), ('conv2/kernel', 2)]\n self.d2_named_flat_inner = [\n ('conv1/bias', 1), ('conv1/kernel', 0), ('conv1', self.d2['conv1']),\n ('conv2/bias', 3), ('conv2/kernel', 2), ('conv2', self.d2['conv2']),\n ('', self.d2),\n ]\n\n # This is a very important testcase that checks whether we correctly\n # recover jax' traversal order, even though our custom traversal may not\n # be consistent with jax' traversal order. In particular, jax traverses\n # FlaxStruct in the order of attribute definition, while our custom\n # traversal is alphabetical.\n @flax.struct.dataclass\n class FlaxStruct():\n v3: float\n v2: int\n v1: str\n self.d3 = {'a': 0, 'flax': FlaxStruct(2.0, 1, 's')}\n self.d3_flat = [0, 1, 2.0, 's']\n self.d3_flat_jax = jax.tree_flatten(self.d3)[0]\n self.d3_named_flat = [\n ('a', 0), ('flax/v1', 's'), ('flax/v2', 1), ('flax/v3', 2.0)]\n self.d3_named_flat_jax = [\n ('a', 0), ('flax/v3', 2.0), ('flax/v2', 1), ('flax/v1', 's')]\n\n def test_traverse_with_names(self):\n names_and_vals = list(utils._traverse_with_names(self.d1))\n self.assertEqual(names_and_vals, self.d1_named_flat)\n\n names_and_vals = list(utils._traverse_with_names(self.d2))\n self.assertEqual(names_and_vals, self.d2_named_flat)\n\n names_and_vals = list(utils._traverse_with_names(\n self.d2, with_inner_nodes=True))\n self.assertEqual(names_and_vals, self.d2_named_flat_inner)\n\n names_and_vals = list(utils._traverse_with_names(self.d3))\n self.assertEqual(names_and_vals, self.d3_named_flat)\n\n def test_tree_flatten_with_names(self):\n names_and_vals = utils.tree_flatten_with_names(self.d1)[0]\n self.assertEqual(names_and_vals, self.d1_named_flat_jax)\n self.assertEqual([x for _, x in names_and_vals], self.d1_flat_jax)\n\n names_and_vals = utils.tree_flatten_with_names(self.d2)[0]\n self.assertEqual(names_and_vals, self.d2_named_flat_jax)\n self.assertEqual([x for _, x in names_and_vals], self.d2_flat_jax)\n\n names_and_vals = utils.tree_flatten_with_names(self.d3)[0]\n self.assertEqual(names_and_vals, self.d3_named_flat_jax)\n self.assertEqual([x for _, x in names_and_vals], self.d3_flat_jax)\n\n def test_tree_map_with_names(self):\n d1 = utils.tree_map_with_names(\n lambda name, x: -x if 'w2' in name else x, self.d1)\n self.assertEqual(d1, {'w1': 1, 'w2': -2, 'w34': (3, 4)})\n\n d1 = utils.tree_map_with_names(\n lambda name, x1, x2: x1 + x2 if 'w2' in name else x1, self.d1, self.d1)\n self.assertEqual(d1, {'w1': 1, 'w2': 4, 'w34': (3, 4)})\n\n def test_recover_tree(self):\n keys = ['a/b', 'a/c/x', 'a/c/y', 'd']\n values = [0, 1, 2, 3]\n self.assertEqual(utils.recover_tree(keys, values),\n {'a': {'b': 0, 'c': {'x': 1, 'y': 2}}, 'd': 3})\n\n def test_make_mask_trees(self):\n F, T = False, True # pylint: disable=invalid-name\n tree = {'a': {'b': 0, 'x': 1}, 'b': {'x': 2, 'y': 3}}\n msk1 = {'a': {'b': F, 'x': T}, 'b': {'x': T, 'y': F}}\n msk2 = {'a': {'b': F, 'x': F}, 'b': {'x': F, 'y': T}}\n # Note that 'b' matches '^b' only and not '.*/b'.\n # Also note that \"b/x\" is matched by rule 1 only (because it comes first).\n self.assertEqual(\n utils.make_mask_trees(tree, ('.*/x', 'b/.*')), [msk1, msk2])\n\n def test_tree_get(self):\n tree = {'a': {'b': 0, 'x': 1}, 'b': {'x': 2, 'y': 3}}\n self.assertEqual(utils.tree_get(tree, 'a/b'), 0)\n self.assertEqual(utils.tree_get(tree, 'a/x'), 1)\n self.assertEqual(utils.tree_get(tree, 'b/x'), 2)\n self.assertEqual(utils.tree_get(tree, 'b/y'), 3)\n self.assertEqual(utils.tree_get(tree, 'a'), tree['a'])\n self.assertEqual(utils.tree_get(tree, 'b'), tree['b'])\n\n def test_tree_replace(self):\n tree = {'a': {'b': 2, 'c': 3}, 'c': 4}\n replacements = {\n 'a/b': 'a/b/x', # replaces 'a/b' with 'a/b/x'\n '.*c': 'C', # replaces 'c' with 'C' ('a/c' is removed)\n 'C': 'D', # replaces 'C' (which was 'c') with 'D'\n '.*/c': None, # removes 'a/c'\n }\n tree2 = utils.tree_replace(tree, replacements)\n self.assertEqual(tree2, {'D': 4, 'a': {'b': {'x': 2}}})\n\n def test_tree_compare(self):\n tree1_only, tree2_only, dtype_shape_mismatch = utils.tree_compare(\n {'a': {'b': jnp.array(2), 'c': jnp.array(3)}},\n {'a': {'B': jnp.array(2), 'c': jnp.array(3.)}},\n )\n self.assertEqual(tree1_only, {'a/b'})\n self.assertEqual(tree2_only, {'a/B'})\n self.assertEqual(\n dtype_shape_mismatch,\n {'a/c': [(jnp.dtype('int32'), ()), (jnp.dtype('float32'), ())]})\n\n\nclass StepConversionTest(parameterized.TestCase, tf.test.TestCase):\n\n @parameterized.named_parameters(\n ('nice_steps', 1000, None, None, dict(foo_steps=3), 3),\n ('nice_epochs', 1000, 100, None, dict(foo_epochs=3), 30),\n ('nice_examples', None, 100, None, dict(foo_examples=300), 3),\n ('nice_percent', None, None, 10, dict(foo_percent=0.30), 3),\n ('offbyone_steps', 1001, None, None, dict(foo_steps=3), 3),\n ('offbyone_epochs', 1001, 100, None, dict(foo_epochs=3), 30),\n ('offbyone_examples', None, 101, None, dict(foo_examples=300), 3),\n ('offbyone_percent', None, None, 11, dict(foo_percent=0.30), 3),\n )\n def test_steps(self, data_size, batch_size, total, cfg, expected):\n # Correct default usage:\n step = utils.steps('foo', cfg, data_size=data_size, batch_size=batch_size,\n total_steps=total)\n self.assertEqual(step, expected)\n\n # Inexitent entry:\n with self.assertRaises(ValueError):\n step = utils.steps('bar', cfg, data_size=data_size, batch_size=batch_size,\n total_steps=total)\n step = utils.steps('bar', cfg, data_size=data_size, batch_size=batch_size,\n total_steps=total, default=1234)\n self.assertEqual(step, 1234)\n\n\nclass CreateLearningRateScheduleTest(parameterized.TestCase, tf.test.TestCase):\n\n @parameterized.named_parameters(\n ('linear', 'linear', {}, 13, .5),\n ('polynomial', 'polynomial', {'end': .1, 'power': 2}, 13, .325),\n ('cosine', 'cosine', {}, 13, .5),\n ('rsqrt', 'rsqrt', {'timescale': 1}, 13, 0.3333333),\n ('stair_5', 'stair', {'steps': [10], 'mults': [.5]}, 5, 1.),\n ('stair_10', 'stair', {'steps': [10], 'mults': [.5]}, 10, .5),\n ('warmup_before', 'rsqrt', {'timescale': 1}, 3, .6),\n ('cooldown_after', 'rsqrt', {'timescale': 1}, 20, .05),\n )\n def test_schedule(self, decay_type, extra_kwargs, step, expected_lr):\n lr_fn = utils.create_learning_rate_schedule(\n total_steps=21,\n batch_size=512,\n base=.5,\n decay_type=decay_type,\n scale_with_batchsize=True,\n warmup_steps=5,\n cooldown_steps=5,\n **extra_kwargs)\n lr = lr_fn(step)\n self.assertAlmostEqual(lr, expected_lr)\n\n\nclass CheckpointTest(tf.test.TestCase):\n\n def setup(self):\n gacm = array_serial.GlobalAsyncCheckpointManager()\n\n save_path = os.path.join(self.create_tempdir('workdir'), 'checkpoint.bv')\n x = utils.put_cpu(np.array([1, 2, 3, 4]))\n y = utils.put_cpu(np.array([5, 6, 7, 8]))\n ckpt = {'x': x, 'y': {'z': y}}\n\n sharding = jax.sharding.SingleDeviceSharding(jax.devices('cpu')[0])\n shardings = jax.tree_map(lambda _: sharding, ckpt)\n\n return gacm, save_path, ckpt, shardings\n\n def test_save_and_load(self):\n gacm, save_path, ckpt, shardings = self.setup()\n step = 100\n utils.save_checkpoint_ts(gacm, ckpt, save_path, step, keep=True)\n gacm.wait_until_finished()\n ckpt_loaded = utils.load_checkpoint_ts(save_path,\n tree=ckpt, shardings=shardings)\n chex.assert_trees_all_equal(ckpt_loaded, ckpt)\n\n save_path_step = f'{save_path}-{step:09d}'\n ckpt_loaded_step = utils.tsload(save_path_step, shardings=shardings)\n chex.assert_trees_all_equal(ckpt_loaded_step, ckpt)\n\n def test_save_and_partial_load(self):\n gacm, save_path, ckpt, shardings = self.setup()\n utils.save_checkpoint_ts(gacm, ckpt, save_path, step=100)\n gacm.wait_until_finished()\n _ = shardings.pop('x'), ckpt.pop('x')\n ckpt_loaded = utils.load_checkpoint_ts(save_path,\n tree=ckpt, shardings=shardings)\n chex.assert_trees_all_equal(ckpt_loaded, ckpt)\n\n def test_save_and_cpu_load(self):\n gacm, save_path, ckpt, _ = self.setup()\n utils.save_checkpoint_ts(gacm, ckpt, save_path, step=100)\n gacm.wait_until_finished()\n ckpt_loaded = utils.load_checkpoint_ts(save_path)\n chex.assert_trees_all_equal(ckpt_loaded, ckpt)\n\n def test_save_and_partial_cpu_load(self):\n gacm, save_path, ckpt, _ = self.setup()\n utils.save_checkpoint_ts(gacm, ckpt, save_path, step=100)\n gacm.wait_until_finished()\n ckpt.pop('y')\n ckpt_loaded = utils.load_checkpoint_ts(save_path, regex='x.*')\n chex.assert_trees_all_equal(ckpt_loaded, ckpt)\n\n def test_keep_deletes(self):\n def x(tree, factor): # x as in \"times\" for multiplying.\n return jax.tree_map(lambda a: a * factor, tree)\n\n gacm, save_path, ckpt, _ = self.setup()\n utils.save_checkpoint_ts(gacm, ckpt, save_path, step=100, keep=False)\n utils.save_checkpoint_ts(gacm, x(ckpt, 2), save_path, step=200, keep=True)\n utils.save_checkpoint_ts(gacm, x(ckpt, 3), save_path, step=300, keep=False)\n gacm.wait_until_finished()\n ckpt_loaded_200 = utils.tsload(f'{save_path}-{200:09d}')\n chex.assert_trees_all_equal(ckpt_loaded_200, x(ckpt, 2))\n ckpt_loaded_300 = utils.tsload(f'{save_path}-{300:09d}-tmp')\n chex.assert_trees_all_equal(ckpt_loaded_300, x(ckpt, 3))\n ckpt_loaded_last = utils.load_checkpoint_ts(save_path)\n chex.assert_trees_all_equal(ckpt_loaded_last, x(ckpt, 3))\n with self.assertRaises(Exception): # Can different types depending on fs.\n _ = utils.tsload(f'{save_path}-{100:09d}')\n # Test that ckpt@100 was deleted\n self.assertFalse(gfile.exists(f'{save_path}-{100:09d}-tmp'))\n\n\nif __name__ == '__main__':\n tf.test.main()\n","repo_name":"google-research/big_vision","sub_path":"big_vision/utils_test.py","file_name":"utils_test.py","file_ext":"py","file_size_in_byte":13282,"program_lang":"python","lang":"en","doc_type":"code","stars":1152,"dataset":"github-code","pt":"77"} +{"seq_id":"70106630328","text":"import pytest\nimport subprocess\nimport logging\n\nimport nss.nss as nss\nimport nss.ssl as ssl\n\n@pytest.fixture(scope='session')\ndef server_name():\n return 'nsswstunnel.tdihp.github.com'\n\n\n@pytest.fixture(scope='session')\ndef server_cert(tmp_path_factory, server_name):\n \"\"\"returns cert and key paths\"\"\"\n path = tmp_path_factory.mktemp('openssl')\n key_path = str(path / 'server.key')\n cert_path = str(path / 'server.crt')\n openssl_args = [\n 'openssl', 'req', '-batch',\n '-newkey', 'rsa:2048', '-nodes', '-keyout', key_path,\n '-x509', '-days', '1', '-out', cert_path,\n '-subj', '/CN=' + server_name, \n ]\n subprocess.run(openssl_args, check=True)\n return cert_path, key_path\n\n\n@pytest.fixture(scope='session')\ndef certdb(tmp_path_factory, server_cert, server_name):\n \"\"\"generates cert db and return its path\"\"\"\n path = tmp_path_factory.mktemp('nsscertdb')\n certdb = 'sql:' + str(path)\n init_certdb_cmd = ['certutil', '-N', '--empty-password', '-d', certdb]\n subprocess.run(init_certdb_cmd, check=True)\n add_server_cert_cmd = [\n 'certutil', '-A', '-t', 'C,,', '-d', certdb,\n '-n', server_name, '-i', server_cert[0]]\n subprocess.run(add_server_cert_cmd, check=True)\n return certdb\n\n\n@pytest.fixture(scope='function', autouse=True)\ndef nssinit(certdb):\n nss.nss_init(certdb)\n ssl.set_domestic_policy()\n # yield\n # ssl.clear_session_cache()\n # nss.nss_shutdown()\n\n\n@pytest.fixture(scope='function', autouse=True)\ndef loginit(caplog):\n caplog.set_level(logging.DEBUG, logger=\"nsswstunnel\")\n\n","repo_name":"tdihp/nsswstunnel","sub_path":"nsswstunnel/test/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"14340203675","text":"import pickle\nimport os\nfrom os import listdir\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nmypath=\"/home/orkeny/PycharmProjects/3Dobject_class/test\"\ninstances = [files for files in listdir(mypath+\"/\")]\ni = 0\nfor inst in instances:\n print(i)\n f = open(mypath+\"/\"+inst, \"rb\")\n f.seek(os.SEEK_SET)\n data = np.fromfile(f, dtype=np.int32)\n f.close()\n print(data.max())\n data = data.reshape((40,40,40))\n print(data.shape)\n fig = plt.figure()\n\n ax = fig.add_subplot(111, projection='3d')\n ax.voxels(data, edgecolors='gray')\n ax.set_xlabel('X Label')\n ax.set_ylabel('Y Label')\n ax.set_zlabel('Z Label')\n plt.title(' voxels')\n plt.show()\n label = input(\"label: \")\n\n with open('dataset/' + label + '/' + inst + 'f1.pkl', \"wb\") as f:\n pickle.dump(data, f)\n i = i + 1","repo_name":"zovathio/SmartCar-3Dobjectrecognition","sub_path":"tools/datagenerator/sztaki2pickle.py","file_name":"sztaki2pickle.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":"14616200364","text":"import tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport sys\nimport os\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\npath = sys.path[0]\n\n\"\"\" tf.app.flags.DEFINE_integer('is_train', -1, '指定是否训练模型,还是拿数据去预测')\nFLAGS = tf.app.flags.FLAGS \"\"\"\n\ndef full_connection():\n \"\"\"\n 用全连接来对手写数字进行识别\n \"\"\"\n #1、准备数据\n with tf.variable_scope('mnist_data'):\n mnist = input_data.read_data_sets(path + '\\mnist_data', one_hot = True)\n x = tf.placeholder(dtype = tf.float32, shape = [None, 784])\n y_true = tf.placeholder(dtype = tf.float32, shape = [None, 10])\n\n \n y_predict = create_model(x)\n\n #3.构建损失函数\n with tf.variable_scope('softmax_crossentrop'):\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y_true, logits = y_predict))\n \n #4.优化损失函数\n with tf.variable_scope('optimizer'):\n train_op = tf.train.AdamOptimizer(learning_rate = 0.01).minimize(loss)\n\n #5、准确率计算\n with tf.variable_scope('accuracy'):\n #1)比较输出的结果最大值所在位置和真实值的最大值所在位置\n equal_list = tf.equal(tf.arg_max(y_true, 1), tf.arg_max(y_predict, 1))\n #2)求平均\n accuracy = tf.reduce_mean(tf.cast(equal_list, tf.float32))\n\n #初始化变量\n init = tf.global_variables_initializer()\n\n with tf.Session() as sess:\n sess.run(init)\n image, label = mnist.train.next_batch(100)\n\n print('训练前,损失为%f:' % sess.run(loss, feed_dict = {x: image, y_true: label}))\n\n #开始训练\n for i in range(3000):\n _, loss_value, accuracy_value = sess.run([train_op, loss, accuracy], feed_dict = {x: image, y_true: label})\n print('第%d训练,损失为%f,准确率为%f' % (i + 1, loss_value, accuracy_value))\n\n return None\n\ndef create_model(x):\n \"\"\"\n 构建卷积神经��络\n \"\"\"\n #1)第一个卷积大层\n #将x[None, 784]形状进行修改\n with tf.variable_scope('conv1'):\n input_x = tf.reshape(x, shape = [-1, 28, 28, 1])\n #卷积层\n #定义filter和偏置\n conv1_weights = create_weights(shape = [5, 5, 1, 32])\n conv1_bias = create_weights(shape = [32])\n conv1_x = tf.nn.conv2d(input = input_x, filter = conv1_weights, strides = [1, 1, 1, 1], padding = 'SAME') + conv1_bias\n\n #激活层\n relu1_x = tf.nn.relu(conv1_x)\n\n #池化层\n pool1_x = tf.nn.max_pool(value = relu1_x, ksize = [1, 2, 2, 1], strides = [1, 2, 2, 1], padding = 'SAME')\n\n #2)第二个卷积大层\n with tf.variable_scope('conv2'):\n #卷积层\n #定义filter和偏置\n conv2_weights = create_weights(shape = [5, 5, 32, 64])\n conv2_bias = create_weights(shape = [64])\n conv2_x = tf.nn.conv2d(input = pool1_x, filter = conv2_weights, strides = [1, 1, 1, 1], padding = 'SAME') + conv2_bias\n\n #激活层\n relu2_x = tf.nn.relu(conv2_x)\n\n #池化层\n pool2_x = tf.nn.max_pool(value = relu2_x, ksize = [1, 2, 2, 1], strides = [1, 2, 2, 1], padding = 'SAME')\n\n #3)全连接层\n with tf.variable_scope('full_connection'):\n x_fc = tf.reshape(pool2_x, shape = [-1, 7 * 7 * 64])\n weights_fc = create_weights(shape = [7 * 7 * 64,10])\n bais_fc = create_weights(shape = [10])\n y_predict = tf.matmul(x_fc, weights_fc) + bais_fc\n\n return y_predict\n\ndef create_weights(shape):\n return tf.Variable(initial_value = tf.random_normal(shape = shape, stddev = 0.01))\n\nif __name__ == '__main__':\n full_connection()","repo_name":"lishuliang/Emotion-Recognition","sub_path":"demo/day_03/day03_deeplearning_cnn_mnist.py","file_name":"day03_deeplearning_cnn_mnist.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"13754639160","text":"def pow2(b): # helper function which returns 2**b\r\n if (b == 0): # time complexity: O(log(b))\r\n return 1 # space complexity: O(1)\r\n else: # recurrence relation: pow2(b) = pow2(b/2)**2 , b is even\r\n if (b%2 == 0): # pow2(b) = 2*pow2(b-1) , b is odd\r\n return pow2(int(b/2))**2 # base case: pow2(0) = 1\r\n else:\r\n return 2*pow2(b-1)\r\n\r\ndef log2(n): # helper function which returns log2(n)\r\n if (n == 1): # time complexity: O(log(n))\r\n return 0 # space complexity: O(1)\r\n else: # base case: log2(1) = 0\r\n ans = 0\r\n while (n > 1): # loop invariant: n*(2**ans) is N\r\n n = int(n/2) # initialization: ans = 0, n = N, so n*(2**0) = N\r\n ans += 1 # maintainence: if n*(2**ans) = N then (n/2)*(2**(ans-1)) = N\r\n return ans # termination: n = 1, 1*(2**ans) = N , therefore ans = log2(N)\r\n\r\n# class starts\r\n\r\nclass priority_queue: \r\n\r\n '''\r\n This class is a special implementation of priority queue (min-heaps) wrt time of collisions, \r\n it has been modified according to needs of our problem statement.\r\n\r\n Attributes: \r\n \r\n self._positions : list of float, self._positions[i] is the position of ith particle at the time of last updation \r\n self._velocities : list of float, self._velocities[i] is the velocity of ith particle at the time of last updation\r\n self._collisions : list of tuple(float, float, int), self._collisions[i] contains a tuple of time, position, index respectively.\r\n self._length : int, length of self._collisions\r\n self._indexes : list of int, self._indexes[i] is the index of tuple(with index = i) in self._collisions\r\n self.last_updation_time : list of int, self.last_updation_time[i] contains the time at which the attributes(position, velocity) of ith particle is changed\r\n \r\n\r\n Methods:\r\n\r\n self.swap(i, j) : swaps the ith and jth element of self._collisions and also swaps the ith and jth element of self._indexes\r\n self.heap_down(i) : implements the standard heap_down method of min_heaps and prioritize small index in tuple as tie breaker(i.e., small index should be above large index)\r\n self.heap_up(i) : implements the standard heap_up method of min_heaps and prioritize small index in tuple as tie breaker(i.e., small index should be above large index)\r\n self.build(list_of_collision_time, list_of_collision_pos) : builds a min heap in O(n) time.\r\n self.push(time,position,index) : pushes tuple => (time, position, index) in self._collisions\r\n self.pop() : pops the smallest tuple (wrt time) from self._collisions\r\n self.size() : size of the self._collisions\r\n self.index_at_top() : index of smallest element of self._collisions\r\n self.set_velocity(index, velocity) : assigns self._velocities[index] <-- velocity\r\n self.set_position(index, position) : assigns self._positions[index] <-- position\r\n self.top() : returns smallest element of self._collisions\r\n self.get_velocity(index) : returns self._velocities[index]\r\n self.get_position(index) : returns self._positions[index]\r\n self.get_time_of_collisions(i) : returns the time of collision between the particles with indexes i and i+1 by calculation\r\n self.get_pos_of_collision(i) : returns the position of collision between the particles with indexes i and i+1 by calculation\r\n self.set_last_updation_time(i,time) : assigns self._last_updation_time[i] <-- time\r\n self.get_last_updation_time(i) : returns self._last_updation_time[i]\r\n self.modify_collisions(time, position, i) : assigns the element of self._collisions(which has index i) to (time, position, i) and then applies heap_up and heap_down\r\n '''\r\n \r\n def __init__(self,x,v,n): # initializes class \r\n self._positions = x\r\n self._velocities = v\r\n self._collisions = []\r\n self._length = 0\r\n self._indexes = [-1]*(n-1)\r\n self._last_updation_time = [0]*(n)\r\n \r\n def swap(self, i, j): # time complexity O(1), space complexity O(1)\r\n temp_index_1 = self._collisions[i][2] \r\n temp_index_2 = self._collisions[j][2]\r\n temp = self._indexes[temp_index_1]\r\n self._indexes[temp_index_1] = self._indexes[temp_index_2]\r\n self._indexes[temp_index_2] = temp\r\n\r\n temp1 = self._collisions[i]\r\n self._collisions[i] = self._collisions[j]\r\n self._collisions[j] = temp1\r\n\r\n def heap_down(self,i): # time complexity O(log(n)), space complexity O(log(n))\r\n if (self._length == 0 or self._length == 1): \r\n return\r\n else:\r\n last_level = log2(self._length)\r\n while (i < pow2(last_level) - 1):\r\n \r\n if (2*i + 2 <= self._length - 1):\r\n if (self._collisions[2*i+1][0] < self._collisions[2*i+2][0]):\r\n if (self._collisions[i][0] < self._collisions[2*i+1][0]):\r\n return\r\n elif (self._collisions[i][0] == self._collisions[2*i+1][0]):\r\n if (self._collisions[i][1] > self._collisions[2*i+1][1]):\r\n self.swap(i,2*i+1)\r\n return\r\n else:\r\n self.swap(i,2*i+1)\r\n i = 2*i + 1\r\n elif (self._collisions[2*i+1][0] > self._collisions[2*i+2][0]):\r\n if (self._collisions[i][0] < self._collisions[2*i+2][0]):\r\n return\r\n elif (self._collisions[i][0] == self._collisions[2*i+2][0]):\r\n if (self._collisions[i][1] > self._collisions[2*i+2][1]):\r\n self.swap(i,2*i+2)\r\n return\r\n else:\r\n self.swap(i,2*i+2)\r\n i = 2*i + 2\r\n else:\r\n if (self._collisions[i][0] < self._collisions[2*i+1][0]):\r\n return\r\n elif (self._collisions[i][0] == self._collisions[2*i+1][0]):\r\n if (self._collisions[2*i+1][1] < self._collisions[2*i+2][1]):\r\n if (self._collisions[i][1] > self._collisions[2*i+1][1]):\r\n self.swap(i,2*i+1)\r\n return\r\n else:\r\n if (self._collisions[i][1] > self._collisions[2*i+2][1]):\r\n self.swap(i,2*i+2)\r\n return\r\n else:\r\n if (self._collisions[2*i+1][1] < self._collisions[2*i+2][1]):\r\n self.swap(i,2*i+1)\r\n i = 2*i+1\r\n else:\r\n self.swap(i,2*i+2)\r\n i = 2*i + 2\r\n\r\n elif (2*i + 1 == self._length - 1):\r\n if (self._collisions[i][0] > self._collisions[2*i+1][0]):\r\n self.swap(i,2*i+1)\r\n i = 2*i + 1\r\n elif (self._collisions[i][0] == self._collisions[2*i+1][0]):\r\n if (self._collisions[i][1] > self._collisions[2*i+1][1]):\r\n self.swap(i, 2*i+1)\r\n return\r\n else:\r\n return\r\n else:\r\n return\r\n return\r\n\r\n def heap_up(self,i): # time complexity O(log(n)), space complexity O(log(n))\r\n if (self._length == 0 or self._length == 1): \r\n return\r\n else:\r\n while (i > 0):\r\n if (self._collisions[int((i-1)/2)][0] > self._collisions[i][0]):\r\n self.swap(i,int((i-1)/2))\r\n i = int((i-1)/2)\r\n elif (self._collisions[int((i-1)/2)][0] == self._collisions[i][0]):\r\n if (self._collisions[int((i-1)/2)][1] > self._collisions[i][1]):\r\n self.swap(i,int((i-1)/2))\r\n return\r\n else:\r\n return\r\n return\r\n\r\n def build(self, lst_of_coll_time, lst_of_coll_pos): # time complexity O(n), space complexity O(n)\r\n count = 0 \r\n for i in range(len(lst_of_coll_time)):\r\n if (lst_of_coll_time[i] > -1):\r\n self._indexes[i] = count\r\n self._collisions.append((lst_of_coll_time[i], lst_of_coll_pos[i], i))\r\n count += 1\r\n \r\n self._length = count\r\n if (count == 1 or count == 0):\r\n return\r\n else:\r\n last_level = log2(count)\r\n curr_level = last_level - 1\r\n while (curr_level >= 0):\r\n for i in range(pow2(curr_level) - 1, 2*pow2(curr_level) - 1):\r\n self.heap_down(i)\r\n curr_level -= 1\r\n return\r\n\r\n def push(self,time,pos,ind): # time complexity: O(log(n)), space complexity: O(log(n))\r\n self._collisions.append((time,pos,ind))\r\n self._length += 1\r\n self._indexes[ind] = self._length - 1\r\n self.heap_up(self._length - 1)\r\n\r\n def pop(self): # time complexity: O(log(n)), space complexity: O(log(n))\r\n if (self._length > 1):\r\n self._indexes[self._collisions[0][2]] = -1\r\n self._indexes[self._collisions[self._length - 1][2]] = 0\r\n temp = self._collisions[0]\r\n self._collisions[0] = self._collisions[self._length - 1]\r\n self._collisions[self._length - 1] = temp\r\n self._collisions.pop()\r\n self._length -= 1\r\n self.heap_down(0)\r\n elif (self._length == 1):\r\n self._indexes[self._collisions[0][2]] = -1\r\n self._collisions.pop()\r\n self._length -= 1\r\n else:\r\n return\r\n\r\n def size(self): # time complexity: O(1), space complexity: O(1)\r\n return self._length\r\n\r\n def index_at_top(self): # time complexity: O(1), space complexity: O(1)\r\n if (self._length > 0):\r\n return self._collisions[0][2]\r\n\r\n def set_velocity(self,i,vel): # time complexity: O(1), space complexity: O(1)\r\n self._velocities[i] = vel\r\n\r\n def set_position(self,i,pos): # time complexity: O(1), space complexity: O(1)\r\n self._positions[i] = pos\r\n\r\n def top(self): # time complexity: O(1), space complexity: O(1)\r\n if (self._length > 0):\r\n return self._collisions[0]\r\n\r\n def get_velocity(self,i): # time complexity: O(1), space complexity: O(1)\r\n return self._velocities[i]\r\n\r\n def get_position(self,i): # time complexity: O(1), space complexity: O(1)\r\n return self._positions[i]\r\n\r\n def get_time_of_collision(self,i): # time complexity: O(1), space complexity: O(1)\r\n if (self._velocities[i] > self._velocities[i+1] and self._positions[i+1] > self._positions[i]):\r\n return (self._positions[i+1] - self._positions[i])/(self._velocities[i] - self._velocities[i+1])\r\n else:\r\n return -1\r\n\r\n def get_pos_of_collision(self,i): # time complexity: O(1), space complexity: O(1)\r\n if (self.get_time_of_collision(i) > 0):\r\n return (self._positions[i+1]*self._velocities[i] - self._positions[i]*self._velocities[i+1])/(self._velocities[i] - self._velocities[i+1])\r\n else:\r\n return 0\r\n\r\n def set_last_updation_time(self,i,time): # time complexity: O(1), space complexity: O(1)\r\n self._last_updation_time[i] = time\r\n\r\n def get_time_of_last_updation(self,i): # time complexity: O(1), space complexity: O(1)\r\n return self._last_updation_time[i]\r\n \r\n def modify_collisions(self,time,pos,index): # time complexity: O(log(n)), space complexity: O(log(n))\r\n lst_index = self._indexes[index]\r\n # print(self._indexes)\r\n temp = (time, pos, index)\r\n self._collisions[lst_index] = temp\r\n \r\n self.heap_down(lst_index)\r\n self.heap_up(self._indexes[index])\r\n\r\n\r\ndef listCollisions(M, x, v, m, T): # return list of tuples(time, index, position) in dictionary order\r\n n = len(M) # n : int, M.length\r\n if (n == 0 or n == 1): # base cases\r\n return []\r\n else:\r\n lst_of_collisions = [] # lst_of_collisions : list of tuples(time, index, position) of collisions in dictionary order\r\n ob = priority_queue(x, v, n) # ob : priority_queue of collisions\r\n\r\n initial_lst_of_times = [-1]*(n-1) # initial_lst_of_times : list of float, contains initial time of collisions\r\n initial_lst_of_collision_pos = [0]*(n-1) # initial_lst_of_collisions_pos : list of float, contains position of next collision\r\n\r\n for i in range(n-1): # assigns the respective values to initial_lst_of_times, initial_lst_of_collisions_pos according to the following formulaes\r\n # t = (x[i+1] - x[i])/(v[i] - v[i+1]) and pos = (x[i+1]*v[i] - x[i]*v[i+1])/(v[i] - v[i+1])\r\n if (v[i] > v[i+1]): \r\n initial_lst_of_times[i] = (x[i+1] - x[i])/(v[i] - v[i+1])\r\n initial_lst_of_collision_pos[i] = (x[i+1]*v[i] - x[i]*v[i+1])/(v[i] - v[i+1])\r\n \r\n ob.build(initial_lst_of_times, initial_lst_of_collision_pos) # builds the initial priority_queue\r\n absolute_time = 0 # absolute_time : float, starts with t = 0 denotes the time elapsed\r\n \r\n while (ob.size() > 0 and m > 0 and absolute_time <= T): # while number of collisions completed are less than m or time elapsed is less than T\r\n\r\n curr_collision = ob.top() # tuple of (time, position, index) of the current collision\r\n curr_index = curr_collision[2] # int, index of the left particle(particle with lesser value of x) involved in the current collision\r\n\r\n absolute_time = curr_collision[0] # as per definition of time stored in curr_collision\r\n\r\n if (absolute_time > T): # as per conditions provided in the problem statement\r\n break\r\n \r\n m -= 1 # as per conditions provided in the problem statement\r\n \r\n ob.set_position(curr_index, curr_collision[1]) # updates the position of left particle involved in current collision\r\n ob.set_position(curr_index+1, curr_collision[1]) # updates the position of right particle involved in current collision\r\n\r\n ob.set_last_updation_time(curr_index, absolute_time) # updates the time of left particle involved in current collision\r\n ob.set_last_updation_time(curr_index+1, absolute_time) # updates the time of right particle involved in current collision\r\n v1 = ob.get_velocity(curr_index) # v1 : float, velocity of left particle before collision\r\n v2 = ob.get_velocity(curr_index+1) # v2 : float, velocity of right particle before collision\r\n tempv = v1 # tempv : float, temporary variable \r\n v1 = (2*M[curr_index+1]*v2 + (M[curr_index] - M[curr_index+1])*v1)/(M[curr_index] + M[curr_index+1]) # v1 : float, velocity of left particle after collision\r\n v2 = (2*M[curr_index]*tempv + (M[curr_index+1] - M[curr_index])*v2)/(M[curr_index] + M[curr_index+1]) # v2 : float, velocity of right particle after collision\r\n ob.set_velocity(curr_index,v1) # updates the velocity of left particle\r\n ob.set_velocity(curr_index+1, v2) # updates the velocity of right particle\r\n lst_of_collisions.append((absolute_time,curr_index, curr_collision[1])) # adds the current collision in the lst_of_collisions\r\n ob.pop() # removes the node containing the current_collision from ob._collisions\r\n\r\n \r\n # this block updates the attributes related to curr_index - 1 particle \r\n if (curr_index - 1 >= 0): \r\n if (ob._indexes[curr_index - 1] == -1):\r\n if (ob.get_velocity(curr_index-1) > ob.get_velocity(curr_index)):\r\n \r\n ob.set_position(curr_index-1, ob.get_position(curr_index-1) + ob.get_velocity(curr_index-1)*(absolute_time - ob.get_time_of_last_updation(curr_index-1)))\r\n new_time = ob.get_time_of_collision(curr_index-1)\r\n new_pos = ob.get_pos_of_collision(curr_index - 1)\r\n ob.push(absolute_time + new_time, new_pos, curr_index - 1)\r\n ob.set_last_updation_time(curr_index-1, absolute_time)\r\n else:\r\n if (ob.get_velocity(curr_index-1) > ob.get_velocity(curr_index)):\r\n ob.set_position(curr_index-1, ob.get_position(curr_index-1) + ob.get_velocity(curr_index-1)*(absolute_time - ob.get_time_of_last_updation(curr_index-1)))\r\n new_time = ob.get_time_of_collision(curr_index - 1)\r\n new_pos = ob.get_pos_of_collision(curr_index-1)\r\n ob.modify_collisions(absolute_time + new_time, new_pos, curr_index-1)\r\n ob.set_last_updation_time(curr_index-1, absolute_time)\r\n \r\n # this block updates the attributes related to curr_index + 2 particle \r\n if (curr_index + 2 <= n - 1):\r\n if (ob._indexes[curr_index + 1] == -1):\r\n if (ob.get_velocity(curr_index+1) > ob.get_velocity(curr_index+2)):\r\n ob.set_position(curr_index+2, ob.get_position(curr_index + 2) + ob.get_velocity(curr_index+2)*(absolute_time - ob.get_time_of_last_updation(curr_index + 2)))\r\n new_time = ob.get_time_of_collision(curr_index + 1)\r\n new_pos = ob.get_pos_of_collision(curr_index + 1)\r\n ob.push(absolute_time + new_time, new_pos, curr_index + 1)\r\n ob.set_last_updation_time(curr_index+2, absolute_time)\r\n else:\r\n if (ob.get_velocity(curr_index+1) > ob.get_velocity(curr_index+2)):\r\n ob.set_position(curr_index+2, ob.get_position(curr_index + 2) + ob.get_velocity(curr_index+2)*(absolute_time - ob.get_time_of_last_updation(curr_index + 2)))\r\n new_time = ob.get_time_of_collision(curr_index + 1)\r\n new_pos = ob.get_pos_of_collision(curr_index + 1)\r\n ob.modify_collisions(absolute_time + new_time, new_pos, curr_index + 1)\r\n ob.set_last_updation_time(curr_index+2, absolute_time)\r\n\r\n \r\n return lst_of_collisions # returns final list of collisions","repo_name":"Dhruv-Kushwaha2010/COL106-Assignments","sub_path":"Code Solution/a2.py","file_name":"a2.py","file_ext":"py","file_size_in_byte":20615,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"8272585870","text":"import socket\nimport os\n\nMSGFORMAT = \"utf-8\"\nserverPort = 12000\nserverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nIP = socket.gethostbyname(socket.gethostname())\nserverSocket.bind((IP, serverPort))\n\npath = './Database'\nisdir = os.path.isdir(path)\nif isdir is False:\n os.mkdir('./Database')\n\nserverSocket.listen()\nprint('The server is ready to receive')\nwhile True:\n connectionSocket, addr = serverSocket.accept()\n msg = \"Client Connected; IP: \"+addr[0]+\"\\n\"\n fileList = os.listdir(\"./Database\")\n prompt = \"Type X to access a file, type Y to upload a file.\"\n connectionSocket.send(msg.encode(MSGFORMAT))\n connectionSocket.send(prompt.encode(MSGFORMAT))\n ans = connectionSocket.recv(1024).decode()\n print(ans)\n if ans == \"X\":\n fileDisp = \"\"\n for filename in fileList:\n fileDisp += filename\n connectionSocket.send(fileDisp.encode(MSGFORMAT))\n #connectionSocket.close()\n #ADsdsada.sdfgh - password delimit by \" \", check up until \".\" in file name to ensure full file name included.\n\n","repo_name":"GregoryMaselle/Assignment1_60_CSC3002F","sub_path":"Server.py","file_name":"Server.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":"13626985208","text":"#무지의 먹방 라이브\nimport heapq\n\nfood_times = list(map(int,input().split()))\nk = int(input())\nresult=-1\nq=[]\nfor i in range(len(food_times)):\n heapq.heappush(q, (food_times[i],i+1))\n\nprevious = 0\nsum_val=0\nlength=len(q)\nwhile(q):\n sum_val=(q[0][0]-previous)*length \n if k>=sum_val:\n k-=sum_val\n previous, _ = heapq.heappop(q)\n length-=1\n else:\n idx=k%length\n q.sort(key=lambda x: x[1])\n result=q[idx][1]\n break\nprint(result)","repo_name":"kimsungwug/codingtest","sub_path":"example/1_greedy/A06.py","file_name":"A06.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"72397446650","text":"import os\nfrom arches.management.commands import utils\nfrom arches.app.models import models\nfrom arches.app.models.system_settings import settings\nfrom django.core.management.base import BaseCommand, CommandError\n\n\nclass Command(BaseCommand):\n \"\"\"\n Commands for managing Arches functions\n\n \"\"\"\n\n def add_arguments(self, parser):\n parser.add_argument(\"operation\", nargs=\"?\", help=\"operation 'livereload' starts livereload for this project on port 35729\")\n parser.add_argument(\n \"-lrh\",\n \"--livereloadhost\",\n action=\"store\",\n dest=\"livereloadhost\",\n default=None,\n help=\"Host on which to run livereload (defaults to 127.0.0.1)\",\n )\n\n def handle(self, *args, **options):\n host = options[\"livereloadhost\"]\n if options[\"operation\"] == \"livereload\":\n self.start_livereload(host)\n\n def start_livereload(self, host):\n from livereload import Server\n\n server = Server()\n for path in settings.STATICFILES_DIRS:\n server.watch(path)\n for path in settings.TEMPLATES[0][\"DIRS\"]:\n server.watch(path)\n\n if host is None:\n server.serve(port=settings.LIVERELOAD_PORT)\n else:\n server.serve(port=settings.LIVERELOAD_PORT, host=host)\n","repo_name":"archesproject/arches","sub_path":"arches/management/commands/developer.py","file_name":"developer.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","stars":191,"dataset":"github-code","pt":"77"} +{"seq_id":"33909558355","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport numpy as np\nfrom scipy import stats as st\nimport math\nfrom utilities import *\nfrom SQKR import SQKR, PrivHS\nimport random\n\n# Privatizes a vector x according to given mechanism\n# x: input vector \n# eps: privacy parameter, if eps=-1 no privacy\n# k: projection parameter for low-communication algorithms\n# mech: in [PrivUnitG,ProjUnit,FastProjUnit,SQKR, PrivHS, RePrivHS,CompPrivUnitG]\n# p,gamma,sigma: parameters for privG \n# fast: if True, use FWHT implementation of Hadamard transform which works\n# faster for the MNIST experiment\n# W: transform to be used for corr-transform algorithms such as FastProjUnit-corr \n# and ProjUnit-corr. \n# For FastProjUnit-corr, one should use \n# W = np.random.choice(a=[-1, 1], size=(n), p=[0.5, 0.5]) \n# For ProjUnit-corr, one should use \n# S = np.sort(random.sample(range(0, n), min(k,n))) #list of indices (different for different users)\n# W = W_full[S,:]\n#\ndef privatize_vector(x,eps,k,mech,p=None,gamma=None,sigma=None,fast=False,W=None):\n n = len(x)\n if mech in ['PrivUnitG', 'ProjUnit', 'FastProjUnit']: \n if p is None or gamma is None or sigma is None:\n # parameters for PrivG algorthms\n p = priv_unit_G_get_p(eps)\n gamma, sigma = get_gamma_sigma(p, eps)\n if mech == 'PrivUnit':\n return PrivUnit(x,eps)\n elif mech == 'PrivUnitG':\n return PrivUnitG(x,eps,p,gamma,sigma)\n elif mech == 'CompPrivUnitG':\n return CompPrivUnitG(x, eps, p, gamma, sigma)\n return priv_G_compressed(x, eps, p, gamma, sigma)\n elif mech == 'FastProjUnit':\n return FastProjUnit(x,eps,k,p,gamma,sigma,fast)\n elif mech == 'FastProjUnit-corr':\n if W is None:\n assert(\"Base transform not provided\")\n return FastProjUnit(x,eps,k,p,gamma,sigma,fast,W)\n elif mech == 'ProjUnit':\n return ProjUnit(x,eps,k,p,gamma,sigma)\n elif mech == 'ProjUnit-corr':\n if W is None:\n assert(\"corr transform not provided\")\n return ProjUnit(x,eps,k,p,gamma,sigma,W)\n elif mech == 'RePrivHS':\n return PrivHS(x.reshape(1,len(x)),eps,k).squeeze() \n elif mech == 'PrivHS':\n k = 1\n return PrivHS(x.reshape(1,len(x)),eps,k).squeeze() \n elif mech == 'SQKR':\n return SQKR(x.reshape(1,len(x)),eps,k,True).squeeze()\n \n\n\n\n# Applies the ProjUnit algorithm based on Gaussian projections \n# for input vector x\n# x: input vecotr \n# eps: privacy parameter, if eps=-1 no privacy\n# p,gamma,sigma: parameters for privG \n# R_p: predefined projection matrix. If None, sample fresh rotation matrix\ndef ProjUnit(x,eps,k,p=None,gamma=None,sigma=None,R_p=None):\n if p is None or gamma is None or sigma is None:\n p = priv_unit_G_get_p(eps)\n gamma, sigma = get_gamma_sigma(p, eps)\n n = len(x)\n \n R = None\n if R_p is None:\n vectors = np.random.rand(k, n)\n q, _ = np.linalg.qr(vectors.T)\n R = math.sqrt(1.0*n/k) * q.T\n else:\n R = R_p\n clipped_Rx = normalize (R @ x)\n noisy_Rx = None\n if eps == -1:\n noisy_Rx = clipped_Rx\n else:\n noisy_Rx = PrivUnitG(clipped_Rx, eps, p, gamma, sigma)\n\n z = np.transpose(R) @ noisy_Rx\n return z\n\n\n\n# Applies the FastProjUnit algorithm based on the SRHT transform\n# for an input vector x\n# x: input vector with unit norn\n# eps: privacy parameter, if eps=-1 no privacy\n# k: projection to k-dimensional sub-space\n# p,gamma,sigma: parameters for privG \n# D: predefined D for the HD transform. If none, sample new D\ndef FastProjUnit(x,eps,k,p=None,gamma=None,sigma=None,fast=False,D=None):\n n = len(x)\n if p is None or gamma is None or sigma is None:\n p = priv_unit_G_get_p(eps)\n gamma, sigma = get_gamma_sigma(p, eps)\n \n D1 = None\n if D is None:\n D1 = np.random.choice(a=[-1, 1], size=(n), p=[0.5, 0.5])\n else:\n D1 = D\n #S = np.sort(random.choices(range(n), k=k)) # with repitition\n S = random.sample(range(n), k) # without repitition\n clipped_z = normalize(applyHDs(x, S, [D1],fast))\n noisy_z = None\n if eps == -1:\n noisy_z = clipped_z\n else:\n noisy_z = PrivUnitG(clipped_z, eps, p, gamma, sigma)\n z = applyInverseHDs(noisy_z, S, [D1],fast)\n return z\n\n\n\n# Applies the PrivUnitG randomizer over input vector x\n# x: input vector with unit norm\n# eps: privacy parameter, if eps=-1 no privacy\n# p,gamma,sigma: parameters for privG \n# n_trials: number of trials for sampling for the tail of gaussian\ndef PrivUnitG(x, eps, p=None, gamma=None, sigma=None, n_tries=None):\n if not p:\n p = priv_unit_G_get_p(eps)\n if p is None or gamma is None or sigma is None:\n gamma, sigma = get_gamma_sigma(p, eps)\n dim = x.size\n g = np.random.normal(0, 1, size = dim)\n pos_cor = np.random.binomial(1, p)\n\n if pos_cor:\n chosen_dps = np.array([sample_from_G_tail_stable(gamma)])\n else:\n if n_tries is None:\n n_tries = 25 # here probability of success is 1/2\n dps = np.random.normal(0, 1, size=n_tries)\n chosen_dps = dps[dps gamma:\n # In this case, we select with probability sp_high\n if np.random.binomial(1, sp_high) == 1:\n break\n else:\n # In this case, we select with probability 1-sp_low\n if np.random.binomial(1, sp_low) == 1:\n break\n \n # In simulation, we send sigma*g. In a compressed version, we send the seed\n # and the server regenerates (this same) g from the seed and uses sigma * g\n return sigma * g\n\n","repo_name":"apple/ml-projunit","sub_path":"PrivUnitAlgs.py","file_name":"PrivUnitAlgs.py","file_ext":"py","file_size_in_byte":7124,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"77"} +{"seq_id":"1087421134","text":"import numpy as np\nnp.set_printoptions(precision = 10, linewidth = 150, suppress = True)\n\nfrom trading_functions import get_stochastic_batch, create_backtrack_array, create_difference_array, create_forward_maxdiff\nfrom classification_training import train_classes\nfrom sklearn.preprocessing import scale, MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelBinarizer, label_binarize\n\nimport tensorflow as tf\n\nflags = tf.app.flags\nFLAGS = flags.FLAGS\n\n\n## ORIGINAL DATA\nfilepath = '/home/patrick/dev/hannah/data'\n\nfilename = 'EURUSD_Candlestick_1_m_ASK_01.01.2013-31.12.2013_2.txt'\nfull_filepath = filepath + '/' + filename\n\n##\nfilename_mode = 'EURUSD_Candlestick_2013_mode'\nfull_filename_mode = filepath + '/' + filename_mode\n\n##\nfilename_labels = 'EURUSD_Candlestick_2013_labels'\nfull_filename_labels = filepath + '/' + filename_labels\n\n##\nfilename_binary_labels = 'EURUSD_Candlestick_2013_binary_labels'\nfull_filename_binary_labels = filepath + '/' + filename_binary_labels\n\n\n## PARAMETERS\nreadout_mode = \"Other\" ## possible readout modes are --Original-- and --Other--\nsave_mode = \"Old\" ## possible save modes are --New-- and --Old--\nsave_type = \"npy\" ## possible save type are --npy-- and --txt--\nbacktrack = 30\nforwardtracking = 30\nrng = 47\nrng_str = str(rng)\n\n\nflags.DEFINE_string('summaries_dir', filepath + '/logs', 'Directory for storing logs')\nflags.DEFINE_string('variables_dir', filepath + '/variables', 'Directory for storing variable data')\n# classification\nflags.DEFINE_integer('max_steps', 20000, 'Number of steps to run trainer.')\nflags.DEFINE_float('learning_rate', 0.001, 'Initial learning rate.')\nflags.DEFINE_float('dropout', 0.5, 'Keep probability for training dropout.')\nflags.DEFINE_integer('features',8, 'Amount of features per convolutional step')\n\nflags.DEFINE_string('train', 'train', '-train the set, -evaluate a specific entry or -both')\nflags.DEFINE_boolean('anew', False, 'Continue training variables or create a new one. Will create new, if no previous data is availabe')\n\n\n\n\nif readout_mode == \"Original\" or save_mode == \"New\":\n print('Reading out data from', full_filepath, '..')\n trading_data = np.genfromtxt(full_filepath, dtype = float, skip_header = 1, delimiter='\\t', autostrip= True, usecols = (2))\n\n\n# array_width = backtrack\n\n## MODE\nif save_mode == 'New':\n trading_mode = create_difference_array(trading_data)\n bt_mode_array = create_backtrack_array(trading_mode, backtrack).astype(np.int16)\n if save_type == 'txt':\n print('Saving txt mode data in', full_filename_mode, '..')\n np.savetxt(full_filename_mode, bt_mode_array, delimiter = '/t')\n elif save_type == 'npy':\n print('Saving npy mode data in', full_filename_mode, '..')\n np.save(full_filename_mode, bt_mode_array)\n else:\n raise ValueError('Save_type must be either -txt- or -npy-')\nelif save_mode == 'Old':\n if save_type == 'txt':\n print('Reading out txt mode data from', full_filename_mode, '..')\n bt_mode_array = np.genfromtxt(full_filename_mode)\n elif save_type == 'npy':\n print('Reading npy out mode data from', full_filename_mode, '..')\n bt_mode_array = np.load(full_filename_mode + '.npy')\n else:\n raise ValueError('Save_type must be either -txt- or -npy-')\nelse:\n raise ValueError\n\n\n## LABELS\n\n## REGULAR\n## SAVING\nif save_mode == 'New':\n labels = create_forward_maxdiff(trading_data, forwardtracking).astype(np.int16)\n if save_type == 'txt':\n print('Saving txt labels data in', full_filename_labels, '..')\n np.savetxt(full_filename_labels, labels, delimiter = '/t')\n elif save_type =='npy':\n print('Saving npy labels data in', full_filename_labels, '..')\n np.save(full_filename_labels, labels)\n else:\n raise ValueError('Your save_type must be either -txt- or -npy-')\n## LOADING\nelif save_mode == 'Old':\n if save_type == 'txt':\n print('Reading out txt label data from', full_filename_labels, '..')\n labels = np.genfromtxt(full_filename_labels)\n elif save_type == 'npy':\n print('Reading out npy label data from', full_filename_labels, '..')\n labels = np.load(full_filename_labels + '.npy')\n else:\n raise ValueError('Save_type must be either -txt- or -npy-')\nelse:\n raise ValueError()\n\n## ONEHOT\n## SAVING\nif save_mode == 'New':\n lb = LabelBinarizer()\n lb.fit(labels)\n label_classes = lb.classes_\n print(label_classes)\n\n binary_labels = label_binarize(labels, classes=label_classes).astype(np.int8)\n if save_type == 'txt':\n print('Saving txt labels data in', full_filename_binary_labels, '..')\n np.savetxt(full_filename_binary_labels, binary_labels, delimiter = '/t')\n elif save_type =='npy':\n print('Saving npy labels data in', full_filename_binary_labels, '..')\n np.save(full_filename_binary_labels, binary_labels)\n else:\n raise ValueError('Your save_type must be either -txt- or -npy-')\n## LOADING\nelif save_mode == 'Old':\n if save_type == 'txt':\n print('Reading out txt label data from', full_filename_binary_labels, '..')\n binary_labels = np.genfromtxt(full_filename_binary_labels)\n elif save_type == 'npy':\n print('Reading out npy label data from', full_filename_binary_labels, '..')\n binary_labels = np.load(full_filename_binary_labels + '.npy')\n else:\n raise ValueError('Save_type must be either -txt- or -npy-')\nelse:\n raise ValueError()\n\n\n\n#\n# print(bt_mode_array)\n# # print(labels)\nunique_labels = len(np.unique(labels))\n# print(len(np.unique(labels)))\n# print(len(np.unique(bt_mode_array)))\n#\narray_length = len(labels)\nindices = np.arange(0,array_length)\n\n# scaled_mode = MinMaxScaler().fit_transform(bt_mode_array)\n# scaled_labels = MinMaxScaler().fit_transform(labels)\n\n# print(scaled_mode)\n# print(scaled_labels)\n#\n# lb = LabelBinarizer()\n# lb.fit(labels)\n# label_classes =lb.classes_\n# # print(label_classes)\n# binary_labels = label_binarize(labels, classes = label_classes)\n# scaled_binary_labels = lb.fit_transform(scaled_labels)\n# print(len(binary_labels))\n# print(np.shape(binary_labels))\nprint(np.nonzero(binary_labels[1350:1370,:])[1])\n# print(binary_labels[1350:1370,:])\n# print(np.nonzero(binary_labels))\n# print(len(np.unique(np.nonzero(binary_labels))))\n# print(len(np.unique(np.sum(binary_labels))))\n# print(scaled_binary_labels)\n# print(len(np.unique(scaled_binary_labels)))\n\ntrain_timestamps, test_timestamps, train_set, test_set, train_labels, test_labels = train_test_split(indices, bt_mode_array,\n binary_labels, train_size=0.5,\n random_state=rng)\n\n\nprint('Train set:', len(train_set[:,0]), 'entries')\nprint('Train_set:', len(np.unique(np.nonzero(train_labels)[1])), 'different labels')\nprint('Test set:', len(test_set[:,0]), 'entries')\nprint('Test_set:', len(np.unique(np.nonzero(test_labels)[1])), 'different labels')\nprint(train_timestamps)\nprint(train_set)\nprint(train_set[0,:])\n\n\n\n\n\n\ntrain_classes(train_timestamps, train_set, train_labels, test_timestamps, test_set, test_labels, train_labels, test_labels, unique_labels,\n features = FLAGS.features, learning_rate = FLAGS.learning_rate, max_steps = FLAGS.max_steps, rng_str = rng_str, dropout = FLAGS.dropout,\n summaries_dir = FLAGS.summaries_dir, variables_dir = FLAGS.variables_dir, mode = FLAGS.train)\n","repo_name":"peterlicht/forex","sub_path":"execute.py","file_name":"execute.py","file_ext":"py","file_size_in_byte":7610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"6483431904","text":"# -*- coding: utf-8 -*-\n# from django.shortcuts import get_object_or_404\nfrom helpers.views import ModelView, ExpertRequiredApiView\n\nfrom dialogwatt.models import CatchmentArea\nfrom dialogwatt.forms import CatchmentAreaForm\nfrom dialogwatt.serializers import CatchmentAreaSerializer\nfrom territories.models import Commune\nfrom django.core.exceptions import ValidationError\n\n\nclass CatchmentAreaView(ModelView, ExpertRequiredApiView):\n \"\"\"\n CatchmentAreaView requires authenticated user\n\n get :model:`dialogwatt.CatchmentArea`\n\n \"\"\"\n\n model = CatchmentArea\n form = CatchmentAreaForm\n serializer = CatchmentAreaSerializer\n perm_module = \"dialogwatt/catchment_area\"\n\n def post_save(self, request, catchment_area, catchment_area_data, created):\n \"\"\"\n Save territories as M2M field\n \"\"\"\n if \"territories\" in catchment_area_data and catchment_area_data[\"territories\"]:\n # territories_id = [x[\"pk\"] for x in catchment_area_data[\"territories\"]]\n territories_id = catchment_area_data[\"territories\"]\n for id in territories_id:\n try:\n commune = Commune.objects.get(pk=id)\n except Exception:\n raise ValidationError(f\"La commune {id} n'existe pas.\")\n\n if not self.request.user.has_perm(\"commune.can_use\", commune):\n raise ValueError(\n f\"Vous n'avez pas la permission d'utiliser la commune {commune.name} / {commune.pk}\"\n )\n\n catchment_area.territories.clear()\n catchment_area.territories.add(*territories_id)\n else:\n raise ValidationError(\n \"La zone de chalandise doit être associée à au moins une commune.\"\n )\n","repo_name":"alexandrenorman/mixeur","sub_path":"dialogwatt/views/catchment_area_view.py","file_name":"catchment_area_view.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":"41265191193","text":"\"\"\"A small logging framework that supports timing and indented log messages.\n\nImportant functions:\n - task: a context manager to wrap self-contained tasks\n - event: print a log message (indented based on active tasks)\n\"\"\"\n\nfrom collections import defaultdict\nfrom contextlib import contextmanager\nimport datetime\n\nfrom cozy.opts import Option\n\nverbose = Option(\"verbose\", bool, False)\n\n_times = defaultdict(float)\n_task_stack = []\n_begin = datetime.datetime.now()\n\ndef log(string):\n if verbose.value:\n print(string)\n\ndef task_begin(name, **kwargs):\n start = datetime.datetime.now()\n _task_stack.append((name, start))\n if not verbose.value:\n return\n indent = \" \" * (len(_task_stack) - 1)\n log(\"{indent}{name}{maybe_kwargs}...\".format(\n indent = indent,\n name = name,\n maybe_kwargs = (\" [\" + \", \".join(\"{}={}\".format(k, v) for k, v in kwargs.items()) + \"]\") if kwargs else \"\"))\n\ndef task_end(success=True):\n end = datetime.datetime.now()\n key = tuple(name for name, start in _task_stack)\n name, start = _task_stack.pop()\n duration = (end-start).total_seconds()\n _times[key] += duration\n if not verbose.value:\n return\n indent = \" \" * len(_task_stack)\n message = \"Finished\" if success else \"FAILED\"\n log(\"{indent}{msg} {name} [duration={duration:.3}s]\".format(indent=indent, msg=message, name=name, duration=duration))\n\n@contextmanager\ndef task(name, **kwargs):\n try:\n yield task_begin(name, **kwargs)\n except:\n task_end(success=False)\n raise\n task_end()\n\ndef event(name):\n if not verbose.value:\n return\n indent = \" \" * len(_task_stack)\n log(\"{indent}{name}\".format(indent=indent, name=name))\n\ndef dump_profile():\n duration = (datetime.datetime.now() - _begin).total_seconds()\n with open(\"/tmp/cozy.profile\", \"w\") as f:\n f.write(\"Total duration: {:.3} seconds\\n\".format(duration))\n f.write(\"Currently in: {}\\n\\n\".format(\", \".join(name for (name, start) in _task_stack)))\n for k in sorted(_times.keys(), key=_times.get, reverse=True):\n f.write(\"{:16.3}\".format(_times[k]))\n f.write(\" \")\n f.write(\", \".join(k))\n f.write(\"\\n\")\n","repo_name":"CozySynthesizer/cozy","sub_path":"cozy/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":2229,"program_lang":"python","lang":"en","doc_type":"code","stars":210,"dataset":"github-code","pt":"77"} +{"seq_id":"33556762117","text":"#!/usr/bin/python\nimport sys\n\ncodes = set()\n\ndefault = dict()\nfor line in open(\"codes-Default.txt\"):\n line = line.strip()\n code, text = line.split('\\t',1)\n default[code] = text\n codes.add(code)\n\ngeneric = dict()\nfor line in open(\"codes-Generic.txt\"):\n line = line.strip()\n code, text = line.split('\\t',1)\n generic[code] = text\n codes.add(code)\n\nprogress = dict()\nfor line in open(\"progress.txt\"):\n line = line.strip()\n code, text = line.split('\\t',1)\n progress[code] = text\n\nresult = dict()\nfor code in codes:\n if default.get(code, None) == None:\n result[code] = generic[code]\n continue\n if generic.get(code, None) == None:\n result[code] = default[code]\n continue\n\n if len(generic[code]) <= len(default[code]):\n start = generic[code]\n full = default[code]\n else:\n start = default[code]\n full = generic[code]\n\n if full.startswith(start):\n result[code] = full\n else:\n result[code] = progress[code]\n #else:\n # print \"Conflict (%s):\" % (code)\n # print \"\\tDefault: %s\" % (default[code])\n # print \"\\tGeneric: %s\" % (generic[code])\n # #print \"use what?\"\n # #result[code] = sys.stdin.readline().strip()\n # #progress.write(\"%s\\t%s\\n\" % (code, result[code]))\n\noutput = open(\"output.txt\", \"w\")\nfor code in codes:\n output.write(\"%s\\t%s\\n\" % (code, result[code]))\noutput.close()\n","repo_name":"Technopig100/adk-scantool","sub_path":"codes/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"19019313476","text":"import sys\n\nimport numpy as np\n\nimport genome.trackstat\n\nfrom .continuoustrack import ContinuousTrack\nfrom .basellrtrack import BaseLLRTrack\n\nclass NormReadDepthTrack(BaseLLRTrack):\n def __init__(self, region, options):\n gdb = options['gdb']\n\n track_name1 = options['track1']\n track_name2 = options['track2']\n\n pseudo_count = float(options['pseudocount'])\n \n track1 = gdb.open_track(track_name1)\n track2 = gdb.open_track(track_name2)\n \n values1 = track1.get_nparray(region.chrom, start=region.start,\n end=region.end)\n \n values2 = track2.get_nparray(region.chrom, start=region.start,\n end=region.end)\n\n if \"scale_factor1\" in options:\n scale_factor1 = float(options['scale_factor1'])\n try:\n stat = gdb.get_track_stat(track1)\n scale1 = scale_factor1 / float(stat.sum)\n values1 = values1 * scale1\n sys.stderr.write(\" total reads %d, using \"\n \"scale %.3f\\n\" % (stat.sum, scale1))\n except ValueError as err:\n sys.stderr.write(\" WARNING: cannot scale values for \"\n \"track %s because track stats have \"\n \"not been calculated. run \"\n \"set_track_stats.py first.\\n\" %\n track.name)\n track1.close() \n\n if \"scale_factor2\" in options:\n scale_factor2 = float(options['scale_factor2'])\n try:\n stat = gdb.get_track_stat(track2)\n scale2 = scale_factor2 / float(stat.sum)\n values2 = values2 * scale2\n sys.stderr.write(\" total reads %d, using \"\n \"scale %.3f\\n\" % (stat.sum, scale2))\n except ValueError as err:\n sys.stderr.write(\" WARNING: cannot scale values for \"\n \"track %s because track stats have \"\n \"not been calculated. run \"\n \"set_track_stats.py first.\\n\" %\n track.name)\n \n track2.close()\n\n ratio = np.log2((values1 + pseudo_count) / (values2 + pseudo_count))\n \n sys.stderr.write(\" %d > 0; %d < 0; %d == 0\\n\" %\n (np.sum(ratio > 0.0), np.sum(ratio < 0.0),\n np.sum(ratio == 0.0)))\n \n \n \n super_init = super(NormReadDepthTrack, self).__init__\n super_init(ratio, region, options)\n \n\n","repo_name":"gmcvicker/draw_genes","sub_path":"draw/normreaddepthtrack.py","file_name":"normreaddepthtrack.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"77"} +{"seq_id":"10168196589","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Dec 24 10:20:25 2021\r\n\r\n@author: acer\r\n\"\"\"\r\n# In[]:\r\nimport keras,os\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Conv2D, MaxPool2D , Flatten\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nimport numpy as np\r\nimport pandas as pd\r\n# In[]:\r\n \r\ntrdata = ImageDataGenerator()\r\ntraindata = trdata.flow_from_directory(directory=\"C:/Users/acer/Desktop/dpml/foraminiera_detect/data\",target_size=(150,150), batch_size = 16)\r\ntsdata = ImageDataGenerator()\r\ntestdata = tsdata.flow_from_directory(directory=\"C:/Users/acer/Desktop/dpml/foraminiera_detect/test\", target_size=(150,150), batch_size = 16)\r\nprint(tsdata)\r\n\r\n\r\n# In[]:\r\nmodel = Sequential()\r\nmodel.add(Conv2D(input_shape=(150,150,3),filters=64,kernel_size=(3,3),padding=\"same\", activation=\"relu\"))\r\nmodel.add(Conv2D(filters=64,kernel_size=(3,3),padding=\"same\", activation=\"relu\"))\r\nmodel.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))\r\nmodel.add(Conv2D(filters=128, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\r\nmodel.add(Conv2D(filters=128, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\r\nmodel.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))\r\nmodel.add(Conv2D(filters=256, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\r\nmodel.add(Conv2D(filters=256, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\r\nmodel.add(Conv2D(filters=256, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\r\nmodel.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))\r\nmodel.add(Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\r\nmodel.add(Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\r\nmodel.add(Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\r\nmodel.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))\r\nmodel.add(Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\r\nmodel.add(Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\r\nmodel.add(Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\r\nmodel.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))\r\n\r\n# In[]:\r\nmodel.add(Flatten())\r\nmodel.add(Dense(units=4096,activation=\"relu\"))\r\nmodel.add(Dense(units=4096,activation=\"relu\"))\r\nmodel.add(Dense(units=2, activation=\"softmax\"))\r\n\r\n\r\n# In[]:\r\n\r\nfrom keras.optimizers import Adam\r\nopt = Adam(lr=0.01)\r\nmodel.compile(optimizer=opt, loss=keras.losses.categorical_crossentropy, metrics=['accuracy'])\r\n\r\nmodel.summary()\r\n\r\n# In[]:\r\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\r\ncheckpoint = ModelCheckpoint(\"vgg16_1.h5\", monitor='val_acc', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=1)\r\nearly = EarlyStopping(monitor='val_acc', min_delta=0, patience=20, verbose=1, mode='auto')\r\nhist = model.fit_generator(steps_per_epoch=100,generator=traindata, validation_data= testdata, validation_steps=10,epochs=10,callbacks=[checkpoint,early])\r\n\r\n# In[]:\r\nmodel.save(\"model1_catsVSdogs_10epoch.h5\")\r\n# In[]:\r\nimport matplotlib.pyplot as plt\r\nplt.plot(hist.history[\"acc\"])\r\nplt.plot(hist.history['val_acc'])\r\nplt.plot(hist.history['loss'])\r\nplt.plot(hist.history['val_loss'])\r\nplt.title(\"model accuracy\")\r\nplt.ylabel(\"Accuracy\")\r\nplt.xlabel(\"Epoch\")\r\nplt.legend([\"Accuracy\",\"Validation Accuracy\",\"loss\",\"Validation Loss\"])\r\nplt.show()\r\n\r\n# In[]:\r\nimport keras,os\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Conv2D, MaxPool2D , Flatten\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom keras.preprocessing import image\r\nimg = image.load_img(\"./output/31.jpg\",target_size=(150,150))\r\nimg = np.asarray(img)\r\nplt.imshow(img)\r\nimg = np.expand_dims(img, axis=0)\r\nfrom keras.models import load_model\r\nsaved_model = load_model(\"model1_catsVSdogs_10epoch.h5\")\r\noutput = saved_model.predict(img)\r\nprint(output)\r\nif output[0][0] > output[0][1]:\r\n print(\"Baculogypsina\")\r\nelse:\r\n print('Calcarina') \r\n","repo_name":"tuosteven/foraminifera_detect","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4018,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"16095079089","text":"import csv\nimport json\nfrom statistics import mean\nimport geopandas\nfrom numpy import sort\nfrom shapely.geometry import Point\n\n\nwith open('cities.geojson') as f:\n cities = json.load(f)\n\nufo = []\n\nwith open('ufo_data.csv') as f:\n csvfile = csv.DictReader(f, delimiter = ',')\n\n for row in csvfile:\n #loads csv dictionary into an array\n ufo.append(row)\n\npoints = []\nnames = []\n#makes the outline for points as well as keys for city names\nfor feature in cities[\"features\"]:\n if feature[\"geometry\"][\"type\"] == \"Point\":\n points.append(feature[\"geometry\"][\"coordinates\"])\n names.append(feature['properties']['city'])\n\ncities = []\nfor point in points:\n cities.append(Point(point))\n\n#makes geo series of all cities\ngeo = geopandas.GeoSeries(cities)\n\noutput = []\n\nfor i in range(len(geo)):\n dist = []\n\n arr = geo.distance(geo[i])\n\n #converts result to an array\n arr = arr.values \n\n for i in range(len(arr)):\n if arr[i] != 0:\n #makes tuple to store all distances\n dist.append((names[i], arr[i]))\n\n #sorts the nearest cities\n dist.sort(key= lambda x: x[1])\n\n city = {\n 'city': names[i],\n 'longitude': geo[i].x,\n 'latitude': geo[i].y,\n 'distance': dist\n }\n\n output.append(city)\n\n#writes the distances of all cities to json file\nwith open('distances.json', 'w') as f:\n f.write(json.dumps(output))\n\n#creates points of all ufos\npoints = []\nfor dics in ufo:\n points.append(Point(float(dics['lon']), float(dics['lat'])))\n\n#geoseries of all ufos\ngeoufo = geopandas.GeoSeries(points)\n\noutput = []\nfor i in range(len(geo)):\n dist = []\n\n arr = geoufo.distance(geo[i])\n\n arr = arr.values\n\n #sorts the array based on closest ufo sightings\n arr = sort(arr)\n\n #gets only the top 100 nearest ufos\n top = arr[0:100]\n\n #finds the average of the 100 closest ufos\n avg = round(mean(top), 18)\n\n city = {\n 'city': names[i],\n 'longitude': geo[i].x,\n 'latitude': geo[i].y,\n 'avgufo': avg\n }\n\n output.append(city)\n\n#writes average distance of closest ufos to file\nwith open('average_ufo.json', 'w') as f:\n f.write(json.dumps(output)) ","repo_name":"DakTheProgrammer/4553-Spatial-DS","sub_path":"Assignments/P02/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"23729495339","text":"import numpy as np\nimport os, struct\nfrom array import array as pyarray\n\ndef load_mnist(x_loc, y_loc, digits=np.arange(10)):\n \"\"\" doc \"\"\"\n flbl = open(y_loc, 'rb')\n magic_nr, size = struct.unpack(\">II\", flbl.read(8))\n lbl = pyarray(\"b\", flbl.read())\n flbl.close()\n\n fimg = open(x_loc, 'rb')\n magic_nr, size, rows, cols = struct.unpack(\">IIII\", fimg.read(16))\n img = pyarray(\"B\", fimg.read())\n fimg.close()\n\n ind = [ k for k in range(size) if lbl[k] in digits ]\n N = len(ind)\n\n images = np.zeros((N, rows, cols), dtype=np.float64)\n labels = np.zeros((N, 1), dtype=np.int8)\n for i in range(len(ind)):\n images[i] = np.array(img[ ind[i] * rows * cols : (ind[i] + 1) * rows * cols ]).reshape((rows, cols)) / 255.0\n labels[i] = lbl[ind[i]]\n\n return images, labels\n","repo_name":"upul/GNN","sub_path":"lib/datareader.py","file_name":"datareader.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"77"} +{"seq_id":"73019091768","text":"\"\"\"Text-based pattern class.\n\nThis class is used to create a pattern from a list of text strings.\n\"\"\"\nfrom octo_slample.constants import (\n BEATS_PER_BAR,\n DEFAULT_CHANNEL_COUNT,\n DEFAULT_STEP_COUNT,\n SIXTEENTHS_PER_BAR,\n)\nfrom octo_slample.pattern.pattern import Pattern\n\nVALID_PATTERN_CHARS = [\" \", \"x\", \"X\", \".\"]\n\n\nclass TextPattern(Pattern):\n \"\"\"Text-based pattern class.\n\n This class is used to create a pattern from a list of text strings.\n \"\"\"\n\n def __init__(\n self,\n channel_count: int = DEFAULT_CHANNEL_COUNT,\n step_count: int = DEFAULT_STEP_COUNT,\n ):\n \"\"\"Initialize the pattern.\n\n Args:\n text (str): The pattern text.\n channel_count (int): The number of channels. Defaults to 8.\n step_count (int): The number of steps. Defaults to 16.\n\n Returns:\n None\n \"\"\"\n super().__init__(channel_count, step_count)\n\n def _validate_pattern_lines(self, lines: list[str]) -> None:\n \"\"\"Validate the pattern lines.\n\n Args:\n lines (list[str]): The lines to validate.\n\n Raises:\n AssertionError: If the lines are invalid.\n \"\"\"\n assert isinstance(lines, list), \"Invalid pattern. Expected a list.\"\n\n # Make sure there are up to 8 lines.\n assert len(lines) <= len(\n self\n ), f\"Invalid number of lines. Expected {len(self)} lines but got {len(lines)}.\"\n\n # Make sure each line is n characters long.\n for index, line in enumerate(lines):\n assert len(line) <= len(self), (\n f\"Invalid line length. Expected up to {len(self)} characters per line \"\n + f\"but got {len(line)} characters on line {index + 1}.\"\n )\n\n for char in line:\n assert char in VALID_PATTERN_CHARS, (\n \"Invalid character in pattern. Expected one of \"\n + f\"[{''.join(VALID_PATTERN_CHARS)}] but got {char}.\"\n )\n\n @property\n def pattern(self) -> list[list[bool]]:\n \"\"\"Get the pattern.\n\n Returns:\n list[list[bool]]: The pattern.\n \"\"\"\n return super().pattern\n\n @pattern.setter\n def pattern(self, pattern: list[str]) -> None:\n \"\"\"Set the pattern.\n\n Args:\n pattern (list[str]): The pattern.\n\n Returns:\n None\n \"\"\"\n self._convert_lines_to_pattern(pattern)\n\n def _convert_lines_to_pattern(self, lines: list[str]) -> None:\n \"\"\"Convert the lines to a pattern.\n\n If any of the lines are less than 16 characters long, they will be\n padded with spaces on the left to make their length 16.\n\n Args:\n lines (list[str]): The lines to convert.\n\n Raises:\n AssertionError: If the lines are invalid.\n \"\"\"\n self._validate_pattern_lines(lines)\n\n for idx_i, line in enumerate(lines):\n for idx_j, char in enumerate(line.ljust(len(self), \".\")):\n self._pattern[idx_i][idx_j] = char.lower() == \"x\"\n\n def __str__(self) -> str:\n \"\"\"Get the pattern as a string.\n\n Returns:\n The pattern as a string.\n \"\"\"\n pattern_string = f\" {self._build_pattern_header()}\\n\"\n for idx, channel in enumerate(self._pattern):\n pattern_string += (\n f\"{idx} \"\n + \"\".join([\"x\" if step else \".\" for step in channel])\n + f\" ({str(self.channel_volumes[idx]).rjust(5)} dB)\"\n + \"\\n\"\n )\n\n return pattern_string\n\n def _build_pattern_header(self) -> str:\n \"\"\"Get the pattern header.\n\n The pattern header has the following format:\n\n 1 1.1 1.2 1.3 2 2.1 2.2 2.3\n\n Returns:\n The pattern header.\n \"\"\"\n pattern_header = \"\"\n pattern_length = len(self.pattern[0])\n\n for bar in range(0, pattern_length // SIXTEENTHS_PER_BAR):\n for step in range(0, BEATS_PER_BAR):\n pattern_header += (\n f\"{bar + 1}{'.' + str(step + 1) if step > 0 else ' '} \"\n )\n\n return pattern_header\n","repo_name":"peteb4ker/octo-slample","sub_path":"octo_slample/pattern/text_pattern.py","file_name":"text_pattern.py","file_ext":"py","file_size_in_byte":4215,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"31621662133","text":"from pathlib import Path\nfrom typing import Tuple\nimport os.path\nimport inspect\n\nimport numpy as np\nimport warnings\nimport importlib\nimport scipy.interpolate\n\nimport mjoindices.empirical_orthogonal_functions as eof\nimport mjoindices.olr_handling as olr\nimport mjoindices.principal_components as pc\nimport mjoindices.omi.wheeler_kiladis_mjo_filter as wkfilter\nimport mjoindices.omi.quick_temporal_filter as qfilter\nimport mjoindices.tools as tools\n\neofs_spec = importlib.util.find_spec(\"eofs\")\neofs_package_available = eofs_spec is not None\nif eofs_package_available:\n import eofs.standard as eofs_package\n\n\n# #################EOF calculation\n\ndef calc_eofs_from_olr(olrdata: olr.OLRData, implementation: str = \"internal\", sign_doy1reference: bool = True,\n interpolate_eofs: bool = False, interpolation_start_doy: int = 293,\n interpolation_end_doy: int = 316, strict_leap_year_treatment: bool = False) -> eof.EOFDataForAllDOYs:\n \"\"\"\n One major function of this module. It performs the complete OMI EOF computation.\n\n This function executes consistently the preprocessing (filtering), the actual EOF analysis, and the postprocessing.\n\n :param olrdata: The OLR dataset, from which OMI should be calculated. Note that OLR values are assumed to be given\n in positive values. The spatial grid of the OLR datasets defines also the spatial grid of the complete OMI\n calculation.\n :param implementation: See :meth:`calc_eofs_from_preprocessed_olr`.\n :param sign_doy1reference: See :meth:`correct_spontaneous_sign_changes_in_eof_series`.\n :param interpolate_eofs: If true, the EOF sub-series between the given DOYs will be interpolated.\n :param interpolation_start_doy: See description of :meth:`interpolate_eofs_between_doys`.\n :param interpolation_end_doy: See description of :meth:`interpolate_eofs_between_doys`.\n :param strict_leap_year_treatment: See description in :meth:`mjoindices.tools.find_doy_ranges_in_dates`.\n :return:\n \"\"\"\n preprocessed_olr = preprocess_olr(olrdata)\n raw_eofs = calc_eofs_from_preprocessed_olr(preprocessed_olr, implementation=implementation, strict_leap_year_treatment=strict_leap_year_treatment)\n result = post_process_eofs(raw_eofs, sign_doy1reference=sign_doy1reference, interpolate_eofs=interpolate_eofs,\n interpolation_start_doy=interpolation_start_doy,\n interpolation_end_doy=interpolation_end_doy)\n return result\n\n\ndef preprocess_olr(olrdata: olr.OLRData) -> olr.OLRData:\n \"\"\"\n Performs the preprocessing of an OLR dataset to make it suitable for the EOF analysis.\n\n This is actually a major step of the OMI algorithm and includes the Wheeler-Kiladis-Filtering.\n\n Note that it is recommended to use the function :meth:`calc_eofs_from_olr` to cover the complete algorithm.\n\n :param olrdata: The OLR dataset, which should be preprocessed. Note that OLR values are assumed to be given in\n positive values.\n\n :return: The filtered OLR dataset.\n \"\"\"\n if np.mean(olrdata.olr) < 0:\n warnings.warn(\"OLR data apparently given in negative numbers. Here it is assumed that OLR is positive.\")\n olrdata_filtered = wkfilter.filter_olr_for_mjo_eof_calculation(olrdata)\n return olrdata_filtered\n\n\ndef calc_eofs_from_preprocessed_olr(olrdata: olr.OLRData, implementation: str = \"internal\",\n strict_leap_year_treatment: bool = False) -> eof.EOFDataForAllDOYs:\n \"\"\"\n Calculates a series of EOF pairs: one pair for each DOY.\n\n This is based on already preprocessed OLR. Note that it is recommended to use the function\n :meth:`calc_eofs_from_olr` to cover the complete algorithm.\n\n :param olrdata: the preprocessed OLR data, from which the EOFs are calculated.\n :param implementation: Two options are available: First, \"internal\": uses the internal implementation of the EOF\n approach. Second, \"eofs_package\": Uses the implementation of the external package :py:mod:`eofs`.\n :param strict_leap_year_treatment: see description in :meth:`mjoindices.tools.find_doy_ranges_in_dates`.\n\n :return: A pair of EOFs for each DOY. This series of EOFs has probably still to be postprocessed.\n \"\"\"\n if implementation == \"eofs_package\" and not eofs_package_available:\n raise ValueError(\"Selected calculation with external eofs package, but package not available. Use \"\n \"internal implementation or install eofs package\")\n doys = tools.doy_list()\n eofs = []\n for doy in doys:\n print(\"Calculating EOFs for DOY %i\" % doy)\n if (implementation == \"eofs_package\"):\n singleeof = calc_eofs_for_doy_using_eofs_package(olrdata, doy,\n strict_leap_year_treatment=strict_leap_year_treatment)\n else:\n singleeof = calc_eofs_for_doy(olrdata, doy, strict_leap_year_treatment=strict_leap_year_treatment)\n eofs.append(singleeof)\n return eof.EOFDataForAllDOYs(eofs)\n\n\ndef post_process_eofs(eofdata: eof.EOFDataForAllDOYs, sign_doy1reference: bool = True,\n interpolate_eofs: bool = False, interpolation_start_doy: int = 293,\n interpolation_end_doy: int = 316) -> eof.EOFDataForAllDOYs:\n \"\"\"\n Post processes a series of EOF pairs for all DOYs.\n\n Postprocessing includes an alignment of EOF signs and an interpolation of the EOF functions in a given DOY\n window. Both steps are part of the original OMI algorithm described by Kiladis (2014).\n\n See documentation of the methods :meth:`correct_spontaneous_sign_changes_in_eof_series` and\n :meth:`interpolate_eofs_between_doys` for further information.\n\n Note that it is recommended to use the function :meth:`calc_eofs_from_olr` to cover the complete algorithm.\n\n :param eofdata: The EOF series, which should be post processed.\n :param sign_doy1reference: See description of :meth:`correct_spontaneous_sign_changes_in_eof_series`.\n :param interpolate_eofs: If true, the EOF sub-series between the given DOYs will be interpolated.\n :param interpolation_start_doy: See description of :meth:`interpolate_eofs_between_doys`.\n :param interpolation_end_doy: See description of :meth:`interpolate_eofs_between_doys`.\n\n :return: the postprocessed series of EOFs\n \"\"\"\n pp_eofs = correct_spontaneous_sign_changes_in_eof_series(eofdata, doy1reference=sign_doy1reference)\n if interpolate_eofs:\n pp_eofs = interpolate_eofs_between_doys(pp_eofs, start_doy=interpolation_start_doy,\n end_doy=interpolation_end_doy)\n return pp_eofs\n\n\ndef calc_eofs_for_doy(olrdata: olr.OLRData, doy: int, strict_leap_year_treatment: bool = False) -> eof.EOFData:\n \"\"\"\n Calculates a pair of EOFs for a particular DOY.\n\n An explicit internal implementation of the EOF approach is used.\n\n Note that it is recommended to use the function :meth:`calc_eofs_from_olr` to cover the complete algorithm.\n\n :param olrdata: The filtered OLR data to calculate the EOFs from.\n :param doy: The DOY for which the EOFs are calculated.\n :param strict_leap_year_treatment: see description in :meth:`mjoindices.tools.find_doy_ranges_in_dates`.\n\n :return: An object containing the pair of EOFs together with diagnostic values.\n\n .. seealso:: :meth:`calc_eofs_for_doy_using_eofs_package`\n\n \"\"\"\n nlat = olrdata.lat.size\n nlong = olrdata.long.size\n olr_maps_for_doy = olrdata.extract_olr_matrix_for_doy_range(doy, window_length=60,\n strict_leap_year_treatment=strict_leap_year_treatment)\n N = olr_maps_for_doy.shape[0]\n M = nlat * nlong\n F = np.reshape(olr_maps_for_doy, [N, M]).T # vector: only one dimension. Length given by original longitude and latitude bins\n R = np.matmul(F, F.T) / N # in some references, it is divided by (N-1), however, we follow Kutzbach (1967), in which it is only divided by N. In any case, the result should not differ much.\n if not np.allclose(R, R.T):\n warnings.warn(\"Covariance matrix is not symmetric within defined tolerance\")\n L, E = np.linalg.eig(R)\n\n if not np.allclose(np.imag(L), 0.):\n warnings.warn(\"Imaginary part of at least one Eigenvalue greater than expected. Neglecting it anyway\")\n L = np.real(L)\n order = (np.flip(L.argsort(), axis=None))\n L = L[order]\n total_var = np.sum(L)\n explainedVariances = L / total_var # See Kutzbach (1967), Eq 12\n\n E = E[:, order]\n if not np.allclose(np.imag(E[:, 0:2]), 0.):\n warnings.warn(\"Imaginary part of one of the first two Eigenvectors greater than expected. Neglecting it anyway\")\n E = np.real(E)\n eof1_vec = np.squeeze(E[:, 0])\n eof2_vec = np.squeeze(E[:, 1])\n\n return eof.EOFData(olrdata.lat, olrdata.long, eof1_vec, eof2_vec,\n eigenvalues=L, explained_variances=explainedVariances, no_observations=N)\n\n\ndef calc_eofs_for_doy_using_eofs_package(olrdata: olr.OLRData, doy: int,\n strict_leap_year_treatment: bool = False) -> eof.EOFData:\n \"\"\"\n Calculates a pair of EOFs for a particular DOY.\n\n The external package :py:mod:`eofs` is used for the core calculation\n\n Note that it is recommended to use the function :meth:`calc_eofs_from_olr` to cover the complete algorithm.\n\n :param olrdata: The filtered OLR data to calculate the EOFs from.\n :param doy: The DOY for which the EOFs are calculated.\n :param strict_leap_year_treatment: see description in :meth:`mjoindices.tools.find_doy_ranges_in_dates`.\n\n :return: An object containing the pair of EOFs together with diagnostic values.\n\n .. seealso:: :meth:`calc_eofs_for_doy`\n\n \"\"\"\n if eofs_package_available:\n nlat = olrdata.lat.size\n nlong = olrdata.long.size\n olr_maps_for_doy = olrdata.extract_olr_matrix_for_doy_range(doy, window_length=60,\n strict_leap_year_treatment=strict_leap_year_treatment)\n\n ntime = olr_maps_for_doy.shape[0]\n N = ntime\n M = nlat * nlong\n F = np.reshape(olr_maps_for_doy,\n [N, M]).T # vector: only one dimension. Length given by original longitude and latitude bins\n solver = eofs_package.Eof(F.T)\n # Todo: Should we care about complex values here?\n eofs = solver.eofs(neofs=2)\n explainedVariances = solver.varianceFraction()\n L = solver.eigenvalues()\n\n if L.size < M:\n # This usually happens if the covariance matrix did not have full rank (e.g. N eof.EOFDataForAllDOYs:\n \"\"\"\n Switches the signs of all pairs of EOFs (for all DOYs) if necessary, so that the signs are consistent for all DOYs.\n\n Note that the sign of the EOFs is not uniquely defined by the PCA. Hence, the sign may jump from one DOY to another,\n which can be improved using this function. As long as this step is performed before computing the PCs, it will not\n change the overall result.\n\n Generally, the sign of the EOFs for a specific DOY is changed if it differs from the sign of the EOF for the previous\n DOY. The EOFs for DOY 1 are by default aligned with the original calculation by Kiladis (2014), resulting in a\n an EOF series, which is totally comparable to the original Kiladis (2014) calculation. This can be switched off.\n\n :param eofs: The EOF series for which the signs should be aligned.\n :param doy1reference: If true, the EOFs of DOY 1 are aligned w.r.t to the original Kiladis (2014) calculation.\n\n :return: The EOFs with aligned signs.\n \"\"\"\n switched_eofs = []\n if doy1reference is True:\n reference_path = Path(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) / \"sign_reference\"\n reference_eofs = eof.load_original_eofs_for_doy(reference_path, 1)\n if not reference_eofs.lat.size == eofs.lat.size \\\n or not reference_eofs.long.size == eofs.long.size \\\n or not np.all(reference_eofs.lat == eofs.lat) \\\n or not np.all(reference_eofs.long == eofs.long):\n warnings.warn(\"References for the sign of the EOFs for DOY1 have to be interpolated to spatial grid of the\"\n \" target EOFs. Treat results with caution.\")\n f1 = scipy.interpolate.interp2d(reference_eofs.long, reference_eofs.lat, reference_eofs.eof1map,\n kind='linear')\n eof1map_interpol = f1(eofs.long, eofs.lat)\n f2 = scipy.interpolate.interp2d(reference_eofs.long, reference_eofs.lat, reference_eofs.eof2map,\n kind='linear')\n eof2map_interpol = f2(eofs.long, eofs.lat)\n reference_eofs = eof.EOFData(eofs.lat, eofs.long, eof1map_interpol, eof2map_interpol)\n corrected_doy1 = _correct_spontaneous_sign_change_of_individual_eof(reference_eofs, eofs.eofdata_for_doy(1))\n else:\n corrected_doy1 = eofs.eofdata_for_doy(1)\n switched_eofs.append(corrected_doy1)\n previous_eof = corrected_doy1\n for doy in tools.doy_list()[1:]:\n corrected_eof = _correct_spontaneous_sign_change_of_individual_eof(previous_eof, eofs.eofdata_for_doy(doy))\n switched_eofs.append(corrected_eof)\n previous_eof = corrected_eof\n return eof.EOFDataForAllDOYs(switched_eofs)\n\n\ndef _correct_spontaneous_sign_change_of_individual_eof(reference: eof.EOFData, target=eof.EOFData) -> eof.EOFData:\n \"\"\"\n Switches the sign of a particular pair of EOFs (for a particular DOY) if necessary, so that is aligned with the\n reference.\n\n Note that the signs of the EOFs is not uniquely defined by the PCA. Hence, the sign may jump from one DOY to another,\n which can be improved using this function. As long as this step is performed before computing the PCs, it will not\n change the overall result.\n\n :param reference: The reference-EOFs. This is usually the EOF pair of the previous DOY.\n :param target: The EOFs of which the signs should be switched\n\n :return: The target EOFs with aligned signs.\n \"\"\"\n if (np.mean(np.abs(target.eof1vector + reference.eof1vector))\n < np.mean(np.abs(\n target.eof1vector - reference.eof1vector))): # if abs(sum) is lower than abs(diff), than the signs are different...\n eof1_switched = -1 * target.eof1vector\n else:\n eof1_switched = target.eof1vector\n if (np.mean(np.abs(target.eof2vector + reference.eof2vector))\n < np.mean(np.abs(\n target.eof2vector - reference.eof2vector))): # if abs(sum) is lower than abs(diff), than the signs are different...\n eof2_switched = -1 * target.eof2vector\n else:\n eof2_switched = target.eof2vector\n return eof.EOFData(target.lat,\n target.long,\n eof1_switched,\n eof2_switched,\n eigenvalues=target.eigenvalues,\n explained_variances=target.explained_variances,\n no_observations=target.no_observations)\n\n\ndef interpolate_eofs_between_doys(eofs: eof.EOFDataForAllDOYs, start_doy: int = 293,\n end_doy: int = 316) -> eof.EOFDataForAllDOYs:\n \"\"\"\n Replaces the EOF1 and EOF2 functions between 2 DOYs by a linear interpolation between these 2 DOYs.\n\n This should only rarely be used and has only been implemented to closely reproduce the original OMI values. There,\n the EOFs have also been replaced by an interpolation according to Kiladis (2014). However, the period stated in\n Kiladis (2014) from 1 November to 8 November is too short. The authors have confirmed that the right\n interpolation period is from DOY 294 to DOY 315, which is used here as default value.\n\n ATTENTION: The corresponding statistical values (e.g., the explained variances) are not changed by this routine.\n So these values further on represent the original results of the PCA also for the interpolated EOFs.\n\n :param eofs: The complete EOF series, in which the interpolation takes place.\n :param start_doy: The DOY, which is used as the first point of the interpolation (i.e. start_doy + 1 is the first\n element, which will be replaced by the interpolation.\n :param end_doy: The DOY, which is used as the last point of the interpolation (i.e. end_doy - 1 is the last\n element, which will be replaced by the interpolation.\n\n :return: The complete EOF series with the interpolated values.\n \"\"\"\n doys = tools.doy_list()\n start_idx = start_doy - 1\n end_idx = end_doy - 1\n eof_len = eofs.lat.size * eofs.long.size\n eofs1 = np.empty((doys.size, eof_len))\n eofs2 = np.empty((doys.size, eof_len))\n # Todo: Maybe this could be solved more efficiently\n # by using internal numpy functions for multidimenasional operations\n for (idx, doy) in enumerate(doys):\n eofs1[idx, :] = eofs.eof1vector_for_doy(doy)\n eofs2[idx, :] = eofs.eof2vector_for_doy(doy)\n\n for i in range(0, eof_len):\n eofs1[start_idx + 1:end_idx - 1, i] = np.interp(doys[start_idx + 1:end_idx - 1],\n [doys[start_idx], doys[end_idx]],\n [eofs1[start_idx, i], eofs1[end_idx, i]])\n eofs2[start_idx + 1:end_idx - 1, i] = np.interp(doys[start_idx + 1:end_idx - 1],\n [doys[start_idx], doys[end_idx]],\n [eofs2[start_idx, i], eofs2[end_idx, i]])\n interpolated_eofs = []\n for (idx, doy) in enumerate(doys):\n orig_eof = eofs.eofdata_for_doy(doy)\n interpolated_eofs.append(eof.EOFData(orig_eof.lat, orig_eof.long, np.squeeze(eofs1[idx, :]),\n np.squeeze(eofs2[idx, :]),\n explained_variances=orig_eof.explained_variances,\n eigenvalues=orig_eof.eigenvalues, no_observations=orig_eof.no_observations)\n )\n return eof.EOFDataForAllDOYs(interpolated_eofs)\n\n\n# #################PC Calculation\n\ndef calculate_pcs_from_olr(olrdata: olr.OLRData,\n eofdata: eof.EOFDataForAllDOYs,\n period_start: np.datetime64,\n period_end: np.datetime64,\n use_quick_temporal_filter=False) -> pc.PCData:\n \"\"\"\n This major function computes PCs according to the OMI algorithm based on given OLR data and previously calculated\n EOFs.\n\n :param olrdata: The OLR dataset. The spatial grid must fit to that of the EOFs\n :param eofdata: The previously calculated DOY-dependent EOFs.\n :param period_start: the beginning of the period, for which the PCs should be calculated.\n :param period_end: the ending of the period, for which the PCs should be calculated.\n :param use_quick_temporal_filter: There are two implementations of the temporal filtering: First, the original\n Wheeler-Kiladis-Filter, which is closer to the original implementation while being slower (because it is based\n on a 2-dim FFT) or a 1-dim FFT Filter. Setting this parameter to True uses the quicker 1-dim implementation. The\n results are quite similar.\n\n :return: The PC time series.\n \"\"\"\n resticted_olr_data = olr.restrict_time_coverage(olrdata, period_start, period_end)\n resampled_olr_data = olr.interpolate_spatial_grid(resticted_olr_data, eofdata.lat, eofdata.long)\n if use_quick_temporal_filter:\n filtered_olr_data = qfilter.filter_olr_for_mjo_pc_calculation_1d_spectral_smoothing(resampled_olr_data)\n else:\n filtered_olr_data = wkfilter.filter_olr_for_mjo_pc_calculation(resampled_olr_data)\n raw_pcs = regress_3dim_data_onto_eofs(filtered_olr_data, eofdata)\n normalization_factor = 1 / np.std(raw_pcs.pc1)\n pc1 = np.multiply(raw_pcs.pc1, normalization_factor)\n pc2 = np.multiply(raw_pcs.pc2, normalization_factor)\n return pc.PCData(raw_pcs.time, pc1, pc2)\n\n\ndef calculate_pcs_from_olr_original_conditions(olrdata: olr.OLRData,\n original_eof_dirname: Path,\n use_quick_temporal_filter=False) -> pc.PCData:\n \"\"\"\n Calculates the OMI PCs for the original period using the original dataset (which has, however, to be provided\n by the user himself).\n\n :param olrdata: The original OLR data, which can be downloaded from\n ftp://ftp.cdc.noaa.gov/Datasets/interp_OLR/olr.day.mean.nc\n :param original_eof_dirname: Path to the original EOFs, which can be downloaded\n from ftp://ftp.cdc.noaa.gov/Datasets.other/MJO/eof1/ and ftp://ftp.cdc.noaa.gov/Datasets.other/MJO/eof2/ .\n The contents of both remote directories should again be placed into sub directories *eof1* and *eof2*\n :param use_quick_temporal_filter: see :func:`calculate_pcs_from_olr`\n\n :return: The PCs, which should be similar to the original ones.\n \"\"\"\n period_start = np.datetime64(\"1979-01-01\")\n period_end = np.datetime64(\"2018-08-28\")\n eofs = eof.load_all_original_eofs_from_directory(original_eof_dirname)\n return calculate_pcs_from_olr(olrdata,\n eofs,\n period_start,\n period_end,\n use_quick_temporal_filter)\n\n\ndef regress_3dim_data_onto_eofs(data: object, eofdata: eof.EOFDataForAllDOYs) -> pc.PCData:\n \"\"\"\n Finds time-dependent coefficients w.r.t the DOY-dependent EOF basis for time-dependent spatially resolved data.\n\n I.e. it finds the PCs for temporally resolved OLR data. But the function can also be used for other datasets,\n as long as those datasets have the same structure like the the class :class:`mjoindices.olr_handling.OLRData`.\n\n :param data: The data, for which the coefficients are sought. Should be an object of class\n :class:`mjoindices.olr_handling.OLRData` or of similar structure.\n :param eofdata: The DOY-dependent pairs of EOFs, like computed by, e.g., :func:`calc_eofs_from_olr`\n\n :return: The time-dependent PCs as :class:`mjoindices.principal_components.PCData`\n \"\"\"\n if not np.all(data.lat == eofdata.lat):\n raise ValueError(\"Latitude grid of EOFs and OLR is not equal.\")\n if not np.all(data.long == eofdata.long):\n raise ValueError(\"Longitude grid of EOFs and OLR is not equal.\")\n pc1 = np.empty(data.time.size)\n pc2 = np.empty(data.time.size)\n\n for idx, val in enumerate(data.time):\n day = val\n olr_singleday = data.get_olr_for_date(day)\n doy = tools.calc_day_of_year(day)\n (pc1_single, pc2_single) = regress_vector_onto_eofs(\n eofdata.eofdata_for_doy(doy).reshape_to_vector(olr_singleday),\n eofdata.eof1vector_for_doy(doy),\n eofdata.eof2vector_for_doy(doy))\n pc1[idx] = pc1_single\n pc2[idx] = pc2_single\n return pc.PCData(data.time, pc1, pc2)\n\n\ndef regress_vector_onto_eofs(vector: np.ndarray, eof1: np.ndarray, eof2: np.ndarray) -> Tuple[float, float]:\n \"\"\"\n Helper method that finds the coefficients of the given vector with respect to the given basis of 2 EOFs.\n\n The computed coefficients are the PCs in the terminology of the EOF analysis.\n\n :param vector: The vector for which the coefficients in the EOF basis should be found.\n :param eof1: EOF basis vector 1.\n :param eof2: EOF basis vector 2.\n\n :return: The two PCs.\n \"\"\"\n eof_mat = np.array([eof1, eof2]).T\n\n # Alternative implementation 1:\n x = np.linalg.lstsq(eof_mat, vector, rcond=-1)\n pc1, pc2 = x[0]\n return pc1, pc2\n\n # Alternative implementation 2:\n # pseudo_inverse = np.linalg.pinv(eof_mat)\n # pcs = np.matmul(pseudo_inverse, vector)\n # return pcs[0], pcs[1]\n","repo_name":"holmdk/mjoindices","sub_path":"src/mjoindices/omi/omi_calculator.py","file_name":"omi_calculator.py","file_ext":"py","file_size_in_byte":24890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"77"} +{"seq_id":"21327411426","text":"def area_quadrado(lado: float) -> float:\n area = lado ** 2\n return area\n\nprint(f'Área do quadrado = {area_quadrado(5)}')\n\n\n\"\"\"\nSintaxe função lambda\n\n = lambda : \n\"\"\"\n\n\narea_quad = lambda lado: lado**2\n\nprint(f'Área do quadrado utilizando lambda = {area_quad(6)}')\n","repo_name":"PlinioCE/infinitypython","sub_path":"aula_funcao_lambda.py","file_name":"aula_funcao_lambda.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"71813132730","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\nimport json\n\nNg = 3\nlengths = 2*np.array(range(1,100,2)) #need this factor of two to compensate for an earlier mistake\ntrials = 10000\n\n\n\n \nwith open(\"C:\\\\Users\\\\laura\\\\OneDrive\\\\Desktop\\\\Lab3\\\\NQVMTrialsNoisyQVMTrials10000Lengths200Ng3.json\", 'r') as fp:\n data = json.load(fp)\n \n\n \naveraged_fidelities = (1/Ng)*np.sum(np.array(data) , axis=0) \n \ndef func(m, A, B, f):\n return A + B*f**m\n\npopt, pcov = curve_fit(func, lengths,averaged_fidelities,p0=[0.6,0.5,0.97])\n\nA=popt[0]\nB=popt[1]\nf=popt[2]\n\n\ny = [func(x, A, B, f) for x in lengths]\nplt.plot()\nplt.plot(lengths,averaged_fidelities,'-b')\nplt.plot(lengths, y, '-r')\nplt.ylabel('Fidelity',fontsize='xx-large')\nplt.xlabel('Circuit Length',fontsize='xx-large')\nplt.title('Randomized Benchmarking: Noisy QVM',fontsize='xx-large')\nplt.xticks(fontsize=14)\nplt.yticks(fontsize=14)\ntext = '$f=0.994$'\nprops = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\nplt.text(150, 0.87, text, fontsize=19,bbox=props)\nplt.grid()\nplt.show()\n\nd = 2\nFavg = ((d-1)*(1-f))/d\n","repo_name":"Fagin-H/Rigetti_hackathon","sub_path":"BenchmarkingResults/curvefit.py","file_name":"curvefit.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"70860128249","text":"from tensorflow.examples.tutorials.mnist import input_data\r\nmnist = input_data.read_data_sets('C:/Users/maliqi/Desktop/tensorflow/MNIST_data')\r\n\r\nimport tensorflow as tf\r\nimport numpy as np\r\nfrom functools import partial\r\n\r\n# construction phase\r\nn_inputs = 28 * 28\r\nn_hidden1 = 300\r\nn_hidden2 = 150\r\nn_hidden3 = n_hidden1\r\nn_outputs = n_inputs\r\nlearning_rate = 0.01\r\n\r\nnoise_level = 1.0\r\nX = tf.placeholder(tf.float32, shape = [None, n_inputs])\r\nX_noisy = X + noise_level * tf.random_normal(tf.shape(X))\r\nhidden1 = tf.layers.dense(X_noisy, n_hidden1, activation=tf.nn.relu,\r\n name=\"hidden1\")\r\nhidden2 = tf.layers.dense(hidden1, n_hidden2, activation=tf.nn.relu, \r\n name=\"hidden2\") \r\nhidden3 = tf.layers.dense(hidden2, n_hidden3, activation=tf.nn.relu, \r\n name=\"hidden3\") \r\noutputs = tf.layers.dense(hidden3, n_outputs, name=\"outputs\") \r\n\r\nreconstruction_loss = tf.reduce_mean(tf.square(outputs - X)) \r\n\r\noptimizer = tf.train.AdamOptimizer(learning_rate)\r\ntraining_op = optimizer.minimize(reconstruction_loss)\r\n\r\ninit = tf.global_variables_initializer()\r\n\r\nn_epochs = 10\r\nbatch_size = 150\r\n\r\nwith tf.Session() as sess:\r\n init.run()\r\n for epoch in range(n_epochs):\r\n n_batches = mnist.train.num_examples // batch_size\r\n for iteration in range(n_batches):\r\n X_batch, y_batch = mnist.train.next_batch(batch_size)\r\n sess.run(training_op, feed_dict={X: X_batch})\r\n loss_train = reconstruction_loss.eval(feed_dict={X: X_batch})\r\n print(\"\\r{}\".format(epoch), \"Train MSE:\", loss_train)","repo_name":"liqima/Machine_Learning_books","sub_path":"deep learning and tensorflow/15autoencoder/stack_denoising_autoencoder.py","file_name":"stack_denoising_autoencoder.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"43194515640","text":"# handling exceptions\n\n# imports ===============\nimport sys\n\n# functions =============\n\n# main() ================\ndef main():\n\t# use a try/except net to capture errors\n\t# rem the default except does not know what error might be captured\n\t# rem the default except must appear last in the set of exceptions\n\ttry:\n\t\t# x = 1\n\t\t# x = int('foo')\n\t\tx = 5/0\n\texcept ValueError:\n\t\tprint('The script has captured a ValueError.')\n\t#except ZeroDivisionError:\n\t#\tprint('The script has captured a ZeroDivisionError.')\n\texcept: # default\n\t\t# use sys to report on error details\n\t\t# use [1] index notation to pull the second indexed item from the list\n\t\t# of info that is returned by sys\n\t\tprint(f'The script has caused an unknown error: {sys.exc_info()[1]}')\n\telse:\n\t\tprint('The script appears to be error free.')\n\t\tprint(x)\n\t\t\nif __name__ == '__main__': main()\t\n","repo_name":"stcybrdgs/myPython-refresher","sub_path":"pythonEssential/handleException.py","file_name":"handleException.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"13551111073","text":"expression = input()\r\n\r\n\r\ndef push(lst, item):\r\n lst.append(item)\r\n\r\n\r\ndef pop(lst):\r\n return lst.pop()\r\n\r\n\r\ndef top(lst):\r\n return lst[-1]\r\n\r\n\r\ndef is_empty(lst):\r\n return len(lst) == 0\r\n\r\n\r\ndef checkPrecedence(operator):\r\n operatorPrecedence = {\"(\": 0, \"+\": 1, \"-\": 1, \"*\": 2, \"/\": 2}\r\n return operatorPrecedence[operator]\r\n\r\n\r\ndef Infix_to_Postfix(expression):\r\n expression = expression.split(\" \")\r\n stack = []\r\n result = \"\"\r\n for i in expression:\r\n if i.isalpha():\r\n result += i + \" \"\r\n elif i == \"(\":\r\n push(stack, i)\r\n elif i == \")\":\r\n while not (is_empty(stack)) and top(stack) != \"(\":\r\n result += pop(stack) + \" \"\r\n pop(stack)\r\n else:\r\n while not (is_empty(stack)\r\n ) and checkPrecedence(i) <= checkPrecedence(top(stack)):\r\n result += pop(stack) + \" \"\r\n push(stack, i)\r\n while not is_empty(stack):\r\n result += pop(stack) + \" \"\r\n\r\n return result\r\n\r\n\r\nprint(Infix_to_Postfix(\"A+((B+C)*(D+E))\"))","repo_name":"Qazalbash/GradVault","sub_path":"data-structure-and-algorithms/labs/Infix to Postfix.py","file_name":"Infix to Postfix.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"77"} +{"seq_id":"14737444113","text":"# coding: utf-8\n\nimport requests\nimport unittest\nimport re\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nimport json\nimport numpy as np\nimport time\nimport concurrent.futures\nimport urllib.request\n\n# API Google Map\nurl_api = 'https://maps.googleapis.com/maps/api/distancematrix/json?'\nurl_villes = \"https://www.insee.fr/fr/statistiques/1906659?sommaire=1906743\"\n\nAPI_KEY = open(\"tokenMap.txt\", \"r\").read()\n\ndef get_request_from_url_and_build_soup(url):\n request = requests.get(url)\n if request.status_code == 200:\n html_doc = request.text\n soup = BeautifulSoup(html_doc, \"html.parser\")\n return soup\n else:\n print(\"The website is not responding : \" + str(request.status_code))\n\n\ndef get_request_from_url_and_build_json(url, body):\n request = requests.post(url+API_KEY, data=body)\n if request.status_code == 200:\n jsonObject = json.loads(request.text)\n return jsonObject\n else:\n print(\"erreur requête json : \", str(request.status_code), request.text)\n return\n\n\n#Matrice distance entre les 50 plus grandes villes de France\n\n\nsoup = get_request_from_url_and_build_soup(url_villes)\n\ntblvilles = soup.find(id=\"produit-tableau-T16F014T4\")\n\ndf = pd.read_html(str(tblvilles))[0]\nprint(df.head())\n\n# 50 plus grandes villes\ndf2 = df.iloc[:50]\n\n\n\nbody = r\"{ 'locations': [ 'Paris, Fr','Marseilles','Lyon'], \" \\\n r\"'options': {'allToAll': true}}\"\n\n# http://developer.mapquest.com/documentation/directions-api/route-matrix/post/\ntest = get_request_from_url_and_build_json(url_api, body)\n\nmatrix = np.array(test['distance'])\n\nprint(matrix)\n","repo_name":"MSBigData2019/stephane_mulard","sub_path":"Lesson3/exo_cc_lesson_03.py","file_name":"exo_cc_lesson_03.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":"29440489199","text":"# completa el código de la función\ndef suma_divisores(a):\n i = 0\n div = [ ]\n for divisor in range(1,a):\n if a % divisor == 0:\n div.append(divisor)\n \n i +=1\n s = sum(div)\n if s == 1:\n lala = (s,True)\n return lala\n else:\n lolo = (s,False)\n return lolo\n\nif __name__ == '__main__':\n num = int(input())\n i = 0\n d = [ ]\n for divisor in range(1,num):\n if num % divisor == 0:\n d.append(divisor)\n i +=1\n sumaD = sum(d)\n print(suma_divisores(num))","repo_name":"pabloschwarzenberg/grader","sub_path":"tema3_ej1/tema3_ej1_9bd18f843d7d30c27a2cc6b29f1bb31f.py","file_name":"tema3_ej1_9bd18f843d7d30c27a2cc6b29f1bb31f.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"71525584248","text":"#!/usr/bin/env python3\n\"\"\"Train various models on various datasets, and measure quantities related\n\nto the gradient and the Hessian.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport h5py\nimport uuid\nimport os\nimport sys\nimport random\nimport logging\nimport logging.handlers\nimport datetime\nimport tempfile\nimport time\n\n# python2+3 compatibility\ntry:\n from StringIO import StringIO\nexcept ImportError:\n from io import StringIO\n\nfrom absl import app\nfrom absl import flags\n\nimport numpy as np\nimport scipy\n\nimport tensorflow as tf\n\nfrom tensorflow.python.client import device_lib\n\nimport tensorflow.keras as keras\nimport tensorflow.keras.backend as K\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport colored_traceback\n\nimport scope.datasets\nimport scope.measurements as meas\nimport scope.models as models\nimport scope.schedules as schedules\nimport scope.tbutils as tbutils\nimport scope.tfutils as tfutils\nfrom scope.experiment_defs import *\n\ncolored_traceback.add_hook()\n\nRUN_TIMESTAMP = datetime.datetime.now().strftime('%Y-%m-%d--%H-%M-%S')\nALL_SAMPLES = -1\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string('job-dir', '', 'Ignored')\nflags.DEFINE_string('summary_dir', 'logs', 'Base summary and logs directory')\nflags.DEFINE_string(UID_TAG, uuid.uuid4().hex, 'Unique run identifier')\nflags.DEFINE_string(NAME_TAG, '', 'Experiment name')\nflags.DEFINE_integer('run_number', None,\n 'Number of the current run within the experiment. '\n 'An experiment can have multiple runs with the same '\n 'parameters, for example when collecting statistics.')\nflags.DEFINE_integer('total_runs', None,\n 'How many runs total are in the current experiment')\nflags.DEFINE_float('delay_logging', None,\n 'Delay log messages going to file but this many seconds '\n 'before flushing.')\nflags.DEFINE_boolean('log_to_file', True,\n 'Log everything to file, in addition to stdout. '\n 'If false, only log to stdout.')\nflags.DEFINE_string('load_weights', None,\n 'Load the model weights from the given path and use it as '\n 'a starting point')\nflags.DEFINE_string('dataset', 'mnist',\n 'Dataset: mnist, mnist_eo, cifar10, sine, or gaussians')\nflags.DEFINE_float('image_resize', 1, 'Resize images by given factor')\nflags.DEFINE_boolean('dropout', False, 'Use dropout')\nflags.DEFINE_boolean('batch_norm', False, 'Use batch normalization')\nflags.DEFINE_float('lr', 0.1, 'Learning rate')\nflags.DEFINE_float('lr_linear_decay_alpha', None,\n 'alpha defining linear learning rate decay. '\n 'If this is specified, learning rate will start at --lr '\n 'value and will decay linearly with every step until '\n 'step T. The final lr value is alpha*(initial-lr).')\nflags.DEFINE_float('lr_linear_decay_T', None,\n 'T defining linear learning rate decay. '\n 'If this is specified, learning rate will start at --lr '\n 'value and will decay linearly with every step until '\n 'step T. The final lr value is alpha*(initial-lr).')\nflags.DEFINE_boolean('lr_overlap_schedule', False,\n 'Set the lr dynamically using the Hessian-gradient overlap')\n\nflags.DEFINE_float('resample_prob', 1,\n 'Probability each sample being replaced at each step. '\n 'Must be specified with --iid_batches.')\n\nflags.DEFINE_boolean('resnetv2', False,\n 'Consider the Resnetv2 from keras.examples')\n\nflags.DEFINE_float('resample_prob_decay_T', None,\n 'T defining resample probability decay. '\n 'If this is specified, it will start at --resample_prob '\n 'value and will decay linearly with every step until '\n 'step T. The final value is alpha*initial.')\nflags.DEFINE_float('resample_prob_decay_alpha', None,\n 'alpha defining linear resample probability decay. '\n 'If this is specified, it will start at --resample_prob '\n 'value and will decay linearly with every step until '\n 'step T. The final value is alpha*initial. '\n 'If T is specified and alpha is not, alpha is set to '\n '1/initial so the final prob value is 1.')\n\nflags.DEFINE_boolean('resample_prob_follows_lr', False,\n 'If True, resample probability will decay with the '\n 'learning rate, starting at --resample_prob.')\n\nflags.DEFINE_boolean('adam', False, 'Use Adam optimizer')\nflags.DEFINE_float('momentum', None, 'Use momentum optimizer '\n '(supply momentum coefficient)')\n# flags.DEFINE_boolean('projected_gd', False, 'Use Projected Gradient Descent')\n# flags.DEFINE_integer('projected_num_evs', 10,\n# 'How many Hessian eigenvalues to measure for PGD')\n# flags.DEFINE_integer('projected_batch_size', 2048,\n# 'Batch size when computing Hessian spectrum for PGD '\n# '(-1 for all)')\nflags.DEFINE_boolean('dense', True,\n 'Include a big fully-connected layer in the CNN')\nflags.DEFINE_integer(\n 'overparam', 0, 'Overparameterize the dense layers by adding '\n 'N linear layers')\nflags.DEFINE_string(\n 'fc', None, 'Use a fully-connected network, with '\n 'hidden layer widths given by comma-separated WIDTHS '\n '(e.g. 100,100). Can also say \\'none\\' to have '\n 'no hidden layers.')\nflags.DEFINE_boolean('cnn', False, 'Use a convnet architecture')\nflags.DEFINE_integer('cnn_last_layer', 256,\n 'Width of the last dense layer in the CNN')\nflags.DEFINE_boolean('small_cnn', False, 'Create a small CNN')\nflags.DEFINE_boolean('use_bias', True, 'Use bias in dense layers in FC nets')\nflags.DEFINE_string(\n 'activation', 'relu',\n 'The non-linear activation, can be relu, tanh, softplus,'\n 'or anything else supported by Keras.')\nflags.DEFINE_float('l2', None, 'L2 weight regularization')\nflags.DEFINE_integer('samples', -1, 'Numbers of training samples (-1 for all)')\nflags.DEFINE_integer('val_samples', -1,\n 'Numbers of validation samples (-1 for all)')\nflags.DEFINE_integer('epochs', 1000, 'Number of training epochs')\nflags.DEFINE_integer('steps', None,\n 'Number of training steps (overrides --epochs)')\nflags.DEFINE_integer('batch_size', 64, 'Batch size (-1 for all)')\nflags.DEFINE_boolean('iid_batches', False,\n 'Sample fully IID batches at each time step '\n '(allowing replacement)')\nflags.DEFINE_boolean('summaries', True, 'Save tensorboard-style summaries')\nflags.DEFINE_integer(\n 'measure_batch_size', 2048,\n 'Batch size used when calculating measurements. Does not '\n 'affect results, only performance (-1 for all).')\nflags.DEFINE_string(\n 'loss_and_acc', '1',\n 'Measure loss and accuracy with given frequency '\n '(frequency e.g. \"1\", \"2epochs\", \"10steps\"). '\n 'This is more accurate than the builtin Keras measurement.')\nflags.DEFINE_string(\n 'gradients', None, 'Collect gradient statistics at given frequency '\n '(e.g. \"1\", \"2epochs\", \"10steps\")')\nflags.DEFINE_string(\n 'weight_updates', None,\n 'Measure weight updates and Hessian-update overlap '\n 'at given frequency (e.g. \"1\", \"2epochs\", \"10steps\")')\nflags.DEFINE_boolean('random_overlap', False,\n 'Compute overlaps of the Hessian with random vectors')\nflags.DEFINE_string(\n 'hessian', None,\n 'Compute a partial Hessian spectrum at given frequency '\n ' (e.g. \"1\", \"2epochs\", \"10steps\")')\nflags.DEFINE_string(\n 'last_layer_hessian', None,\n 'Compute a partial Hessian spectrum, for the last layer weights, '\n ' at given frequency (e.g. \"1\", \"2epochs\", \"10steps\")')\nflags.DEFINE_integer('hessian_num_evs', 10,\n 'How many Hessian eigenvalues to measure')\nflags.DEFINE_integer('hessian_batch_size', 2048,\n 'Batch size when computing Hessian spectrum (-1 for all)')\nflags.DEFINE_boolean('stochastic_hessian', False,\n 'If True, compute a stochastic approximation to the Hessian'\n ' instead of full-batch. --hessian_batch_size is the'\n ' batch size to use for the approximation.')\nflags.DEFINE_string(\n 'full_hessian', None, 'Measure the full Hessian spectrum at given frequency'\n ' (e.g. \"1\", \"2epochs\", \"10steps\")')\nflags.DEFINE_integer(\n 'full_hessian_batch_size', 2048,\n 'Batch size when computing the full Hessian. '\n 'This may affect performance but does not affect '\n 'results. (-1 for all)')\nflags.DEFINE_boolean(\n 'grad_2pt', False, 'Also collect gradient 2-point functions '\n '(much more expensive)')\nflags.DEFINE_string(\n 'interpolate_loss', None,\n 'Measure interpolated loss in various directions at the given frequency '\n ' (e.g. \"1\", \"2epochs\", \"10steps\")')\n\nflags.DEFINE_integer('gaussians_num_classes', 2,\n 'Number of classes in gaussians dataset')\nflags.DEFINE_float('gaussians_sigma', 0, 'Stddev of noise in gaussians dataset')\nflags.DEFINE_integer('gaussians_dim', 1000,\n 'Input dimension in gaussians dataset')\nflags.DEFINE_boolean('measure_gaussians_every_step', False,\n 'If True, measure gaussians every steps, '\n 'otherwise every epoch')\n\nflags.DEFINE_boolean('show_progress_bar', False,\n 'Show progress bar during training')\nflags.DEFINE_string('gpu', '0', 'Which GPU to use')\nflags.DEFINE_boolean('cpu', False, 'Use CPU instead of GPU')\nflags.DEFINE_integer('seed', None, 'Set the random seed')\nflags.DEFINE_boolean('nothing', False, 'Do nothing (for sanity testing)')\nflags.DEFINE_string('save_weights', None,\n 'Save the per-layer weights as a summary at the given '\n 'frequency (e.g. \"1\", \"2epochs\", \"10steps\")')\nflags.DEFINE_boolean('save_final_flat_weights_vector', False,\n 'Save the final trained weights vector as a '\n 'flat vector summary')\nflags.DEFINE_integer('prefetch_buffer_size', 10,\n 'How many elements to prefetch during training')\n\n\nclass ExtendedFlags:\n \"\"\"Wraps the existing FLAGS and allows us to add arbitrary flags during\n\n runtime.\n \"\"\"\n def __init__(self):\n self.additional_flags = {}\n\n def __getattr__(self, name):\n \"\"\"Gets called if the object does not contain the requested attribute.\n\n We then pass it on to FLAGS.\n \"\"\"\n return getattr(FLAGS, name)\n\n def set(self, flag, value):\n \"\"\"Set a flag value.\n\n Args:\n attribute: The flag name.\n value: The flag value.\n \"\"\"\n setattr(self, flag, value)\n self.additional_flags[flag] = value\n\n\nxFLAGS = ExtendedFlags()\n\n\ndef get_padded_run_number():\n if xFLAGS.total_runs is not None:\n max_len = len(format(xFLAGS.total_runs))\n return format(xFLAGS.run_number, '0' + str(max_len))\n else:\n return format(xFLAGS.run_number)\n\n\ndef run_name(): # pylint: disable=too-many-branches\n \"\"\"Returns the experiment name.\"\"\"\n name = xFLAGS.name\n\n if xFLAGS.run_number is not None:\n name += '-' + get_padded_run_number()\n\n name += '-' + xFLAGS.dataset\n name += '-' + xFLAGS.activation\n\n if xFLAGS.fc is None:\n if not xFLAGS.resnetv2:\n name += '-cnn'\n else:\n name +='-resnet'\n else:\n name += '-fc' + xFLAGS.fc\n if xFLAGS.small_cnn:\n name += '-smallcnn'\n if not xFLAGS.dense:\n name += '-nodense'\n if xFLAGS.cnn_last_layer != 256:\n name += '-cnnlast{}'.format(xFLAGS.cnn_last_layer)\n if xFLAGS.overparam > 0:\n name += '-overparam{}'.format(xFLAGS.overparam)\n name += '-' + xFLAGS.optimizer_name\n if xFLAGS.batch_norm:\n name += '-batchnorm'\n else:\n if not xFLAGS.resnetv2:\n name += '-nobatchnorm'\n if xFLAGS.dropout:\n name += '-dropout'\n else:\n name += '-nodropout'\n # else:\n # name += '-norandomlabels'\n if xFLAGS.l2 is not None:\n nice_l2 = ('%f' % xFLAGS.l2).rstrip('0')\n if nice_l2.endswith('.'):\n nice_l2 += '0'\n name += '-L2reg{}'.format(nice_l2)\n nice_lr = ('%f' % xFLAGS.lr).rstrip('0')\n name += '-lr{}'.format(nice_lr)\n if xFLAGS.lr_overlap_schedule:\n name += '-lrOverlapSched'\n elif xFLAGS.lr_linear_decay_alpha is not None:\n name += '-lrDecaySched{},{}'.format(\n xFLAGS.lr_linear_decay_alpha,\n xFLAGS.lr_linear_decay_T)\n if xFLAGS.momentum is not None:\n name += '-mom{}'.format(xFLAGS.momentum)\n if xFLAGS.iid_batches:\n name += '-iid'\n name += '-batch{}'.format(xFLAGS.batch_size)\n if xFLAGS.resample_prob < 1:\n name += '-resamp{}'.format(xFLAGS.resample_prob)\n if xFLAGS.resample_prob_follows_lr:\n name += '-resampFollosLR'\n name += '-{}-{}'.format(RUN_TIMESTAMP, xFLAGS.uid)\n if name.startswith('-'):\n name = name[1:]\n return name\n\n\ndef resize_images(images, factor):\n \"\"\"Resize the images by the given factor.\n\n Args:\n images: List of images.\n factor: float by which to resize.\n\n Returns:\n Array of resized images.\n \"\"\"\n return np.array([scipy.misc.imresize(im, factor) for im in images])\n\n\ndef preprocess_images(load_func):\n \"\"\"Load image data sets using the given function, and resizes the\n\n images as necessary.\n\n Args:\n load_func: Function that loads raw image data and labels and returns\n `(x_train, y_train), (x_test, y_test)`.\n\n Returns:\n Processed `(x_train, y_train), (x_test, y_test)`.\n \"\"\"\n (x_train, y_train), (x_test, y_test) = load_func()\n\n if xFLAGS.image_resize != 1:\n x_train = resize_images(x_train, xFLAGS.image_resize)\n x_test = resize_images(x_test, xFLAGS.image_resize)\n\n return (x_train, y_train), (x_test, y_test)\n\n\ndef is_regression():\n \"\"\"Returns whether this is a regression (as opposed to classification).\"\"\"\n return xFLAGS.dataset == 'sine'\n\n\ndef init_flags():\n \"\"\"Validate and initialize some command line flags.\"\"\"\n possible_sets = ('mnist', 'mnist_eo', 'cifar10', 'sine', 'gaussians')\n\n def fatal(desc):\n \"\"\"Report a fatal error and quit.\"\"\"\n tf.logging.error(desc)\n sys.exit(1)\n\n if xFLAGS.dataset not in possible_sets:\n fatal('Unsupported dataset {}. '\n 'Supported datasets: mnist(_eo), '\n 'sine, cifar10, gaussians'.format(xFLAGS.dataset))\n if xFLAGS.fc is None and not xFLAGS.cnn and not xFLAGS.resnetv2:\n fatal('Must specify either --cnn or --fc or --resnet')\n\n if is_regression():\n if xFLAGS.fc is None:\n fatal('Must specify --fc when using regression')\n if xFLAGS.samples == ALL_SAMPLES or xFLAGS.val_samples == ALL_SAMPLES:\n fatal('Must specify --samples and --val-samples when using regression')\n\n if xFLAGS.gradients is None:\n if xFLAGS.hessian is not None:\n fatal('Must specify --gradients with --hessian')\n\n if xFLAGS.last_layer_hessian is not None:\n fatal('Must specify --gradients with --hessian')\n\n if xFLAGS.full_hessian is not None:\n fatal('Must specify --gradients with --full-hessian')\n\n if xFLAGS.adam:\n xFLAGS.set('optimizer_name', 'adam')\n elif xFLAGS.momentum is not None:\n xFLAGS.set('optimizer_name', 'momentum')\n else:\n xFLAGS.set('optimizer_name', 'sgd')\n\n if xFLAGS.fc is not None:\n if xFLAGS.fc == 'none':\n xFLAGS.set('fc_widths', list())\n else:\n xFLAGS.set('fc_widths', list(map(int, str(xFLAGS.fc).split(','))))\n\n if xFLAGS.l2 is None:\n xFLAGS.set('l2_regularizer', None)\n else:\n xFLAGS.set('l2_regularizer', keras.regularizers.l2(xFLAGS.l2))\n\n if xFLAGS.iid_batches and xFLAGS.steps is None:\n fatal('Must specify --steps with --iid_batches')\n\n if xFLAGS.resample_prob < 1 and not xFLAGS.iid_batches:\n fatal('Must specify --iid_batches with --resample_prob')\n\n if xFLAGS.lr_overlap_schedule and xFLAGS.gradients is None:\n fatal('Must specify --gradients with --lr_overlap_schedule')\n\n\ndef init_randomness():\n \"\"\"Seed the random number generators.\"\"\"\n MAXINT32 = 2**31 - 1\n if xFLAGS.seed is None:\n random.seed()\n xFLAGS.set('seed', random.randint(0, MAXINT32))\n random.seed(xFLAGS.seed)\n np.random.seed(random.randint(0, MAXINT32))\n tf.set_random_seed(random.randint(0, MAXINT32))\n\n\ndef get_data():\n \"\"\"Create the dataset used for training.\n\n Returns:\n x_train, y_train, x_test, y_test\n \"\"\"\n if not scope.datasets.datasets_exist():\n raise IOError(\"Datasets have not been downloaded. \"\n \"Run scope/datasets.py --download\")\n num_classes = None\n output_dim = None\n\n def add_channel_dim(shape):\n \"\"\"Returns a tensor shape with an extra channel dimension.\"\"\"\n return list(shape) + [1]\n\n if xFLAGS.dataset == 'mnist':\n output_dim = num_classes = 10\n\n (x_train, y_train), (x_test, y_test) = preprocess_images(\n scope.datasets.load_mnist)\n\n x_train = x_train.reshape(add_channel_dim(x_train.shape))\n x_test = x_test.reshape(add_channel_dim(x_test.shape))\n elif xFLAGS.dataset == 'mnist_eo':\n output_dim = num_classes = 2\n\n (x_train, y_train), (x_test, y_test) = preprocess_images(\n scope.datasets.load_mnist)\n\n y_train = y_train % 2\n y_test = y_test % 2\n\n x_train = x_train.reshape(add_channel_dim(x_train.shape))\n x_test = x_test.reshape(add_channel_dim(x_test.shape))\n elif xFLAGS.dataset == 'sine':\n output_dim = 1\n\n x_train = np.random.rand(xFLAGS.samples).reshape((-1, 1))\n y_train = np.sin(2 * np.pi * x_train)\n\n x_test = np.random.rand(xFLAGS.val_samples).reshape((-1, 1))\n y_test = np.sin(2 * np.pi * x_test)\n elif xFLAGS.dataset == 'cifar10':\n num_classes = 10\n (x_train, y_train), (x_test, y_test) = preprocess_images(\n scope.datasets.load_cifar10)\n elif xFLAGS.dataset == 'gaussians':\n # Gaussians centered at random unit vectors with stddev sigma\n if xFLAGS.samples != ALL_SAMPLES:\n raise ValueError('Cannot specify --samples with gaussians dataset')\n\n n_train = 20000\n n_test = 10000\n output_dim = num_classes = int(xFLAGS.gaussians_num_classes)\n d = int(xFLAGS.gaussians_dim)\n centers = np.random.randn(d, num_classes)\n centers = centers / np.linalg.norm(centers, axis=0)\n\n def make_gaussian_samples(n):\n \"\"\"Get `n` samples from a multivariate Gaussian.\"\"\"\n noise = np.random.randn(n, d) * xFLAGS.gaussians_sigma\n x = noise\n y = np.zeros(n)\n\n samples_per_class = n // num_classes\n for k in range(num_classes):\n off = k * samples_per_class\n rng = range(off, off + samples_per_class)\n x[rng, :] += np.tile(centers[:, k], (samples_per_class, 1))\n y[rng] = k\n\n return x, y\n\n x_train, y_train = make_gaussian_samples(n_train)\n x_test, y_test = make_gaussian_samples(n_test)\n else:\n raise ValueError('Unsupported dataset ' + xFLAGS.dataset)\n\n if xFLAGS.samples != ALL_SAMPLES:\n n = xFLAGS.samples\n x_train = x_train[:n]\n y_train = y_train[:n]\n\n if xFLAGS.val_samples != ALL_SAMPLES:\n n = xFLAGS.val_samples\n x_test = x_test[:n]\n y_test = y_test[:n]\n\n num_samples = len(x_train)\n\n tf.logging.info('x_train shape: {}'.format(x_train.shape))\n tf.logging.info('y_train shape: {}'.format(y_train.shape))\n tf.logging.info('{} train samples'.format(x_train.shape[0]))\n tf.logging.info('{} test samples'.format(x_test.shape[0]))\n\n if xFLAGS.batch_size == ALL_SAMPLES:\n xFLAGS.set('batch_size', num_samples)\n if xFLAGS.measure_batch_size == ALL_SAMPLES:\n xFLAGS.set('measure_batch_size', num_samples)\n if xFLAGS.hessian_batch_size == ALL_SAMPLES:\n xFLAGS.set('hessian_batch_size', num_samples)\n if xFLAGS.full_hessian_batch_size == ALL_SAMPLES:\n xFLAGS.set('full_hessian_batch_size', num_samples)\n # if xFLAGS.projected_batch_size == ALL_SAMPLES:\n # xFLAGS.set('projected_batch_size', num_samples)\n\n def normalize(x, x_for_mean):\n \"\"\"Put the data between [xmin, xmax] in a data independent way.\"\"\"\n mean = np.mean(x_for_mean)\n return x / 255\n #return (x - mean) / 255\n\n x_train = x_train.astype('float32')\n x_test = x_test.astype('float32')\n\n if xFLAGS.dataset != 'gaussians':\n x_train = normalize(x_train, x_train)\n x_test = normalize(x_test, x_train)\n\n if not is_regression():\n # Convert class vectors to binary class matrices.\n y_train = keras.utils.to_categorical(y_train, num_classes)\n y_test = keras.utils.to_categorical(y_test, num_classes)\n\n if num_classes is not None:\n xFLAGS.set('num_classes', num_classes)\n\n if output_dim is not None:\n xFLAGS.set('output_dim', output_dim)\n\n return x_train, y_train, x_test, y_test\n\n\ndef create_model(input_shape):\n \"\"\"Returns the Keras model for training.\"\"\"\n\n if is_regression():\n model = models.regression_fc_model(xFLAGS, xFLAGS.output_dim)\n elif xFLAGS.fc is not None:\n model = models.classification_fc_model(\n xFLAGS, input_shape, xFLAGS.num_classes)\n elif xFLAGS.small_cnn:\n model = models.classification_small_convnet_model(\n xFLAGS, input_shape, xFLAGS.num_classes)\n elif xFLAGS.resnetv2:\n # from keras.examples.cifar10_resnet import resnet_v2\n #from scope.models import resnet_v2\n n=2\n depth = n * 9 + 2\n model=models.resnet_v2(input_shape=input_shape, depth=depth, num_classes=xFLAGS.num_classes)\n else:\n model = models.classification_convnet_model(\n xFLAGS, input_shape, xFLAGS.num_classes)\n\n # This is not the actual optimizer, it's just required by Keras\n # for compiling the model. We put a large learning rate just in case\n # this gets used by mistake.\n keras_opt = keras.optimizers.SGD(lr=1000)\n\n if is_regression():\n model.compile(\n loss='mean_squared_error', optimizer=keras_opt, metrics=['mae'])\n else:\n model.compile(\n loss='categorical_crossentropy',\n optimizer=keras_opt,\n metrics=['accuracy'])\n\n tf.logging.info('Model summary:')\n buf = StringIO()\n model.summary(print_fn=lambda s: buf.write(s + '\\n'))\n tf.logging.info(buf.getvalue())\n tf.logging.info('Total model parameters: {}'.format(\n tfutils.total_num_weights(model)))\n\n return model\n\n\ndef add_callbacks(\n callbacks, recorder, model, x_train, y_train, x_test, y_test, lr_schedule):\n \"\"\"Add measurement callbacks.\"\"\"\n\n # TODO convert to Dataset\n def get_batch_makers(batch_size):\n \"\"\"Returns train and test mini-batch makers.\"\"\"\n train_batches = tfutils.MiniBatchMaker(x_train, y_train, batch_size)\n test_batches = tfutils.MiniBatchMaker(x_test, y_test, batch_size)\n return train_batches, test_batches\n\n if xFLAGS.loss_and_acc is not None:\n train_batches, test_batches = get_batch_makers(xFLAGS.measure_batch_size)\n freq = meas.Frequency.from_string(xFLAGS.loss_and_acc)\n loss_acc_cb = meas.BasicMetricsMeasurement(\n recorder,\n model,\n freq,\n train_batches,\n test_batches,\n lr_schedule,\n show_progress=not xFLAGS.show_progress_bar)\n callbacks.append(loss_acc_cb)\n\n weight_norm_cb = meas.WeightNormMeasurement(recorder, model, freq)\n callbacks.append(weight_norm_cb)\n\n if xFLAGS.save_weights is not None:\n freq = meas.Frequency.from_string(xFLAGS.save_weights)\n weights_cb = meas.WeightsMeasurement(recorder, model, freq)\n callbacks.append(weights_cb)\n\n grad_cb = None\n if xFLAGS.gradients is not None:\n train_batches, test_batches = get_batch_makers(xFLAGS.measure_batch_size)\n freq = meas.Frequency.from_string(xFLAGS.gradients)\n grad_cb = meas.GradientMeasurement(recorder, model, freq, train_batches,\n test_batches, xFLAGS.random_overlap)\n callbacks.append(grad_cb)\n\n if xFLAGS.weight_updates is not None:\n train_batches, test_batches = get_batch_makers(xFLAGS.measure_batch_size)\n freq = meas.Frequency.from_string(xFLAGS.weight_updates)\n weight_update_cb = meas.WeightUpdateMeasurement(\n recorder, model, freq, train_batches, test_batches)\n callbacks.append(weight_update_cb)\n\n if xFLAGS.hessian is not None:\n freq = meas.Frequency.from_string(xFLAGS.hessian)\n hess_cb = meas.LanczosHessianMeasurement(\n recorder,\n model,\n freq,\n xFLAGS.hessian_num_evs,\n x_train,\n y_train,\n xFLAGS.hessian_batch_size,\n xFLAGS.stochastic_hessian,\n lr=xFLAGS.lr,\n log_dir=xFLAGS.runlogdir)\n callbacks.append(hess_cb)\n\n if xFLAGS.last_layer_hessian is not None:\n freq = meas.Frequency.from_string(xFLAGS.last_layer_hessian)\n if xFLAGS.use_bias:\n weights = model.trainable_weights[-2:]\n else:\n weights = model.trainable_weights[-1:]\n num_weights = tfutils.num_weights(weights)\n grad_subvec = lambda g: g[-num_weights:]\n ll_hess_cb = meas.LanczosHessianMeasurement(\n recorder,\n model,\n freq,\n xFLAGS.hessian_num_evs,\n x_train,\n y_train,\n xFLAGS.hessian_batch_size,\n lr=xFLAGS.lr,\n log_dir=xFLAGS.runlogdir,\n weights=weights,\n grad_subvec=grad_subvec,\n name=meas.LAST_LAYER)\n callbacks.append(ll_hess_cb)\n\n if xFLAGS.full_hessian is not None:\n train_batches, test_batches = get_batch_makers(\n xFLAGS.full_hessian_batch_size)\n freq = meas.Frequency.from_string(xFLAGS.full_hessian)\n full_hess_cb = meas.FullHessianMeasurement(\n recorder,\n model,\n freq,\n train_batches,\n xFLAGS.runlogdir,\n num_eigenvector_correlations=xFLAGS.output_dim)\n callbacks.append(full_hess_cb)\n\n if xFLAGS.interpolate_loss is not None:\n train_batches, test_batches = get_batch_makers(xFLAGS.measure_batch_size)\n freq = meas.Frequency.from_string(xFLAGS.interpolate_loss)\n loss_interp_cb = meas.LossInterpolationMeasurement(\n recorder,\n model,\n freq,\n train_batches,\n test_batches)\n callbacks.append(loss_interp_cb)\n\n if xFLAGS.dataset == 'gaussians':\n freq = meas.Frequency(1, xFLAGS.measure_gaussians_every_step)\n gauss_cb = meas.GaussiansMeasurement(\n recorder, model, freq, x_train, y_train)\n callbacks.append(gauss_cb)\n\n\ndef save_model_weights(model, save_dir=None, model_filename=None):\n \"\"\"Save the model.\"\"\"\n if save_dir is None:\n save_dir = xFLAGS.runlogdir + '/saved_models'\n tf.gfile.MakeDirs(save_dir)\n if model_filename is None:\n model_filename = '{}-model-weights.h5'.format(xFLAGS.uid)\n model_weights_path = os.path.join(save_dir, model_filename)\n\n # TODO when h5py 2.9.0 is available, we can create the h5py.File\n # using a tf.gfile.GFile object and skip the temp file.\n tmp_model_weights_path = os.path.join(tempfile.gettempdir(), model_filename)\n # model.save(tmp_model_weights_path)\n model.save_weights(tmp_model_weights_path)\n tf.gfile.Copy(tmp_model_weights_path, model_weights_path)\n tf.gfile.Remove(tmp_model_weights_path)\n tf.logging.info('Saved trained model at {} '.format(model_weights_path))\n\n\ndef load_model_weights(model_weights_path, model):\n \"\"\"Load the model weights from the given file.\n\n Args:\n model_weights_path: Path to model weights file.\n model: An initialized Keras Model.\n \"\"\"\n tf.logging.info('Loading model weights from {}'.format(model_weights_path))\n tmp_model_weights_path = os.path.join(\n tempfile.gettempdir(), 'model-weights.h5')\n tf.gfile.Copy(model_weights_path, tmp_model_weights_path)\n try:\n # return keras.models.load_model(tmp_model_weights_path)\n model.load_weights(tmp_model_weights_path)\n finally:\n tf.gfile.Remove(tmp_model_weights_path)\n\n\ndef get_optimizer(lr):\n if xFLAGS.optimizer_name == 'sgd':\n tf_opt = tf.train.GradientDescentOptimizer(learning_rate=lr)\n elif xFLAGS.optimizer_name == 'adam':\n tf_opt = tf.train.AdamOptimizer(learning_rate=lr)\n elif xFLAGS.optimizer_name == 'momentum':\n tf_opt = tf.train.MomentumOptimizer(\n learning_rate=lr, momentum=xFLAGS.momentum)\n # elif xFLAGS.optimizer_name == 'projected-gd':\n # hessian_spec = tfutils.KerasHessianSpectrum(\n # model, x_train, y_train, xFLAGS.projected_batch_size)\n # keras_opt = meas.ProjectedGradientDescent(\n # lr, model, x_train, y_train,\n # hessian_spec, xFLAGS.projected_num_evs)\n else:\n raise RuntimeError('Unknown optimizer: {}'.format(xFLAGS.optimizer_name))\n return tf_opt\n\n\ndef get_learning_rate_schedule(lr_tensor):\n if xFLAGS.lr_overlap_schedule:\n return schedules.OverlapSchedule(\n lr_tensor, xFLAGS.lr)\n elif xFLAGS.lr_linear_decay_alpha is None:\n return schedules.LinearDecaySchedule(\n lr_tensor, xFLAGS.lr, None, None)\n else:\n return schedules.LinearDecaySchedule(\n lr_tensor,\n xFLAGS.lr,\n xFLAGS.lr_linear_decay_alpha,\n xFLAGS.lr_linear_decay_T)\n\n\nclass DelayedLoggingHandler(logging.handlers.MemoryHandler):\n \"\"\"Buffers logging messages and flushes them after a certain delay.\n One use case is writing logs to rate-limited storage.\n \"\"\"\n def __init__(self, delay, capacity, flushLevel=logging.ERROR, target=None):\n \"\"\"Ctor.\n\n Args:\n delay: Seconds to buffer before flushing\n capacity: Buffering capacity\n flushLevel: Automatically flush messages at or above this level\n target: Target logging handler to send records to\n \"\"\"\n super(DelayedLoggingHandler, self).__init__(\n capacity, flushLevel=flushLevel, target=target)\n self.delay = delay\n self.last_flushed = time.time()\n\n def _delayPassed(self):\n return time.time() > self.last_flushed + self.delay\n\n def shouldFlush(self, record):\n \"\"\"Flush if parent says we should flush, or if enough time elapsed\n since last flush.\"\"\"\n if super(logging.handlers.MemoryHandler, self).shouldFlush(record):\n self.last_flushed = time.time()\n return True\n elif self._delayPassed():\n self.last_flushed = time.time()\n return True\n else:\n return False\n\n\ndef init_logging():\n xFLAGS.set(RUN_NAME_TAG, run_name())\n xFLAGS.set('runlogdir', '{}/{}'.format(xFLAGS.summary_dir, run_name()))\n tf.gfile.MakeDirs(xFLAGS.runlogdir)\n log = logging.getLogger('tensorflow')\n log.propagate = False\n sh = logging.StreamHandler(sys.stdout)\n log.addHandler(sh)\n\n # Handle writing to cloud storage\n if xFLAGS.log_to_file:\n fh = logging.StreamHandler(\n tf.gfile.GFile('{}/tensorflow.log'.format(xFLAGS.runlogdir), 'w'))\n if xFLAGS.delay_logging is not None:\n fh = DelayedLoggingHandler(\n delay=xFLAGS.delay_logging,\n capacity=10*1024,\n flushLevel=logging.WARNING,\n target=fh)\n log.addHandler(fh)\n\n tf.logging.info('Started: {}'.format(RUN_TIMESTAMP))\n tf.logging.info('Log dir: {}'.format(xFLAGS.runlogdir))\n tf.logging.info('Run name: {}'.format(run_name()))\n\n local_device_protos = device_lib.list_local_devices()\n devices = [x.name for x in local_device_protos]\n tf.logging.info('Available devices: {}'.format(devices))\n\n\ndef get_resample_prob(lr_schedule):\n \"\"\"Returns the resample probability.\"\"\"\n if xFLAGS.resample_prob_follows_lr:\n def resample_prob_following_lr():\n lr0 = xFLAGS.lr\n current_prob = np.min([xFLAGS.resample_prob * lr_schedule.lr() / lr0, 1])\n return current_prob\n return resample_prob_following_lr\n elif xFLAGS.resample_prob_decay_T is not None:\n if xFLAGS.resample_prob_decay_alpha is None:\n rp_alpha = 1. / xFLAGS.resample_prob\n else:\n rp_alpha = xFLAGS.resample_prob_decay_alpha\n def resample_prob_decaying():\n return schedules.linear_decay(\n xFLAGS.resample_prob,\n rp_alpha,\n xFLAGS.resample_prob_decay_T,\n lr_schedule.step)\n return resample_prob_decaying\n else:\n return xFLAGS.resample_prob\n\n\ndef get_tf_dataset(x, y, lr_schedule):\n \"\"\"Returns a batch-making Dataset object for the given data.\"\"\"\n if xFLAGS.iid_batches:\n resample_prob = get_resample_prob(lr_schedule)\n ds = tf.data.Dataset.from_generator(\n tfutils.create_iid_batch_generator(\n x, y, xFLAGS.steps, xFLAGS.batch_size, resample_prob),\n (x.dtype, y.dtype))\n else:\n ds = tf.data.Dataset.from_tensor_slices((x, y))\n ds = ds.shuffle(len(x))\n ds = ds.batch(xFLAGS.batch_size)\n\n ds = ds.prefetch(buffer_size=xFLAGS.prefetch_buffer_size)\n return ds\n\n\ndef tf_train(sess, x_train, y_train, base_model, tf_opt, lr_schedule, callbacks):\n \"\"\"TensorFlow training loop.\"\"\"\n step = 0\n epoch = 0\n\n train_ds = get_tf_dataset(x_train, y_train, lr_schedule)\n iterator = tf.data.Iterator.from_structure(train_ds.output_types,\n train_ds.output_shapes)\n next_batch = iterator.get_next()\n iterator_init_op = iterator.make_initializer(train_ds)\n\n model = tfutils.clone_keras_model_shared_weights(\n base_model, next_batch[0], next_batch[1])\n\n train_step = tf_opt.minimize(model.total_loss)\n # grads_and_vars = tf_opt.compute_gradients(model.total_loss)\n # train_step = tf_opt.apply_gradients(grads_and_vars)\n\n for callback in callbacks:\n callback.set_model(base_model)\n\n def counting_epochs():\n return xFLAGS.steps is None\n\n def should_train_next_epoch():\n if counting_epochs():\n return epoch < xFLAGS.epochs\n else:\n return should_train_next_step()\n\n def should_train_next_step():\n if counting_epochs():\n return True\n else:\n return step < xFLAGS.steps\n\n epoch_ended = False\n while should_train_next_epoch():\n for callback in callbacks:\n callback.on_epoch_begin(epoch)\n\n sess.run(iterator_init_op)\n try:\n while should_train_next_step():\n # This condition handles the following case:\n # - on_batch_begin_called\n # - epoch ends, so sess.run() throws OutOfRangeError and\n # the step is not actually taken, 'step' not advanced\n # - when looping around, we don't want to call on_batch_begin\n # again for the same step\n if epoch_ended:\n epoch_ended = False\n else:\n for callback in callbacks:\n callback.on_batch_begin(step)\n\n feed = tfutils.keras_feed_dict(\n model,\n x=None, y=None,\n feed_dict=lr_schedule.feed_dict(),\n learning_phase=tfutils.KERAS_LEARNING_PHASE_TRAIN)\n sess.run([train_step, model.updates], feed_dict=feed)\n\n for callback in callbacks:\n callback.on_batch_end(step)\n step += 1\n except tf.errors.OutOfRangeError:\n for callback in callbacks:\n callback.on_epoch_end(epoch)\n epoch += 1\n epoch_ended = True\n\n\ndef main(argv):\n if len(argv) > 1:\n print('Unrecognized parameters:', argv)\n sys.exit(1)\n\n if xFLAGS.nothing:\n sys.exit(0)\n init_flags()\n init_randomness()\n\n if xFLAGS.cpu:\n os.environ['CUDA_VISIBLE_DEVICES'] = ''\n else:\n os.environ['CUDA_VISIBLE_DEVICES'] = str(xFLAGS.gpu)\n\n x_train, y_train, x_test, y_test = get_data()\n\n init_logging()\n\n tbutils.save_run_flags(\n xFLAGS.runlogdir,\n additional_flags=xFLAGS.additional_flags)\n\n sess = tf.Session()\n K.set_session(sess)\n\n model = create_model(x_train.shape[1:])\n\n lr_tensor = tf.placeholder(tf.float32, shape=[], name='lr')\n tf_opt = get_optimizer(lr_tensor)\n lr_schedule = get_learning_rate_schedule(lr_tensor)\n callbacks = [lr_schedule]\n\n if xFLAGS.summaries:\n recorder = meas.MeasurementsRecorder(summary_dir=xFLAGS.runlogdir)\n add_callbacks(\n callbacks, recorder, model,\n x_train, y_train, x_test, y_test,\n lr_schedule)\n lr_schedule.set_recorder(recorder)\n\n tf.logging.info('Training...')\n\n sess.run(tf.global_variables_initializer(), feed_dict=lr_schedule.feed_dict())\n\n if xFLAGS.load_weights is not None:\n # Load the model weights instead of the whole model, because Keras\n # has a bug saving/loading models that use InputLayer.\n # https://github.com/keras-team/keras/issues/10417\n #\n # Only load the weights after calling the global variables initializer,\n # otherwise the loaded weights get overwritten.\n load_model_weights(xFLAGS.load_weights, model)\n\n tf_train(sess, x_train, y_train, model, tf_opt, lr_schedule, callbacks)\n\n if xFLAGS.save_final_flat_weights_vector:\n weights = model.get_weights()\n flat_weights = np.concatenate([np.reshape(t, [-1]) for t in weights])\n recorder.record_tensor('final_weights', flat_weights, step=-1)\n\n if xFLAGS.summaries:\n recorder.close()\n\n tf.logging.info('Done training!')\n\n save_model_weights(model)\n\n # Score trained model.\n scores = model.evaluate(x_test, y_test, verbose=xFLAGS.show_progress_bar)\n tf.logging.info('Test loss: {}'.format(scores[0]))\n tf.logging.info('Test accuracy: {}'.format(scores[1]))\n\n\nif __name__ == '__main__':\n tf.app.run(main)\n","repo_name":"guygurari/scope","sub_path":"scope/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":36952,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"77"} +{"seq_id":"43568417503","text":"from .ifuzzer import IFuzzer\nfrom fuzzowski import Session\nfrom fuzzowski.mutants.spike import *\n\n\nclass TelnetCLI(IFuzzer):\n \"\"\"\n Example module for fuzzing a CLI over Telnet (using the TelnetConnection Module)\n \"\"\"\n\n name = 'telnet_cli'\n\n @staticmethod\n def get_requests() -> List[callable]:\n return [TelnetCLI.commands]\n\n @staticmethod\n def define_nodes(*args, **kwargs) -> None:\n\n s_initialize('example_command')\n s_string(b'ping', fuzzable=False)\n s_delim(b' ', fuzzable=True, name='delim_space')\n s_string(b'1.2.3.4', fuzzable=True, name='ip')\n s_delim(b'\\r\\n', fuzzable=False)\n\n # --------------------------------------------------------------- #\n\n @staticmethod\n def commands(session: Session) -> None:\n session.connect(s_get('example_command'))\n","repo_name":"nccgroup/fuzzowski","sub_path":"fuzzowski/fuzzers/telnet_cli.py","file_name":"telnet_cli.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":670,"dataset":"github-code","pt":"77"} +{"seq_id":"17456719378","text":"from flask import render_template, Blueprint, request, redirect,jsonify, url_for,session\nimport requests\nfrom flask import flash\nimport app\n\nassignment_4 = Blueprint('assignment_4', __name__,\n static_folder='static',\n static_url_path='/assignment_4',\n template_folder='templates')\n\n\n\n\n\n\n@assignment_4.route('/assignment_4')\ndef assignment_4_page():\n query = 'select * from users'\n users_list = app.interact_db(query, query_type='fetch')\n return render_template('assignment4.html', users=users_list)\n\n# ------------------------------------------------- #\n\n# -------------------- INSERTION FORM --------------------- #\n@assignment_4.route('/insert_user', methods=['POST'])\ndef insert_user():\n user_name = request.form['user_name']\n user_ID = request.form['user_ID']\n user_password = request.form['user_password']\n user_nickName = request.form['user_nickName']\n user_Gender = request.form['user_Gender']\n user_email = request.form['user_email']\n user_age = request.form['user_age']\n\n query = \"select * FROM users WHERE user_ID='%s';\" % user_ID\n users_list = app.interact_db(query, query_type='fetch')\n\n if len(users_list) != 0:\n flash(\"User with id: \" + user_ID + \" already Exist\" ,'error')\n return redirect('/assignment_4')\n\n else:\n query = \"INSERT INTO users(user_name, user_nickName, user_email,user_Gender,user_ID,user_age,user_password) VALUES ('%s', '%s', '%s','%s', '%s', '%s', '%s')\" % (\n user_name, user_nickName, user_email, user_Gender, user_ID, user_age, user_password)\n app.interact_db(query=query, query_type='commit')\n flash(\"User with id: \" + user_ID + \" Successfully inserted\", 'success')\n return redirect('/assignment_4')\n# ------------------------------------------------- #\n\n# # -------------------- UPDATE FORM --------------------- #\n# # -------------------- UPDATE FORM --------------------- #\n@assignment_4.route('/update_user', methods=['POST'])\ndef update_user_func():\n user_ID = request.form['user_ID']\n\n if request.form['user_name'] != '':\n nameToUpdate=request.form['user_name']\n query = \"UPDATE users SET user_name = '%s' WHERE user_ID = '%s'\" % (nameToUpdate , user_ID)\n app.interact_db(query, query_type='commit')\n\n if request.form['user_nickName'] != '':\n nickNameToUpdate=request.form['user_nickName']\n query = \"UPDATE users SET user_nickName = '%s' WHERE user_ID = '%s'\" % (nickNameToUpdate , user_ID)\n app.interact_db(query, query_type='commit')\n\n\n if request.form['user_email'] != '':\n emailToUpdate = request.form['user_email']\n query = \"UPDATE users SET user_email = '%s' WHERE user_ID = '%s'\" % (emailToUpdate, user_ID)\n app.interact_db(query, query_type='commit')\n\n\n if request.form['user_Gender'] != '':\n GenderToUpdate = request.form['user_Gender']\n query = \"UPDATE users SET user_Gender = '%s' WHERE user_ID = '%s'\" % (GenderToUpdate, user_ID)\n app.interact_db(query, query_type='commit')\n\n\n if request.form['user_age'] != '':\n ageToUpdate = request.form['user_age']\n query = \"UPDATE users SET user_age = '%s' WHERE user_ID = '%s'\" % (ageToUpdate, user_ID)\n app.interact_db(query, query_type='commit')\n\n\n if request.form['user_password'] != '':\n passwordToUpdate = request.form['user_password']\n query = \"UPDATE users SET user_password = '%s' WHERE user_ID = '%s'\" % (passwordToUpdate, user_ID)\n app.interact_db(query, query_type='commit')\n flash(\"User with id: \" + user_ID + \" Successfully updated\",'success')\n return redirect('/assignment_4')\n\n\n\n\n# ------------------------------------------------- #\n# -------------------- DELETE --------------------- #\n# ------------------------------------------------- #\n@assignment_4.route('/delete_user', methods=['POST'])\ndef delete_user_func():\n user_ID = request.form['user_ID']\n\n query = \"select * FROM users WHERE user_ID='%s';\" % user_ID\n users_list = app.interact_db(query, query_type='fetch')\n if len(users_list) == 0:\n flash(\" user with id: \" + user_ID + \" does not exist\",'error')\n return redirect('/assignment_4')\n else:\n query = \"DELETE FROM users WHERE user_ID='%s';\" % user_ID\n app.interact_db(query, query_type='commit')\n flash(\"User with id: \" + user_ID +\" Successfully deleted\",'success')\n return redirect('/assignment_4')\n\n\n# ------------------------------------------------- #\n# ------------------------------------------------- #\n\n\n@assignment_4.route('/assignment4/users')\ndef jsonUserTable_func():\n query = 'select * from users'\n users_list = app.interact_db(query, query_type='fetch')\n return jsonify(users_list)\n\n\n@assignment_4.route('/assignment4/outer_sourse')\ndef outer_sourse_func():\n return render_template('assignment4_outer_source.html')\n\n\n@assignment_4.route('/fetch_backEnd')\ndef fetch_be_func():\n inputID = request.args['user_ID_BE']\n userRes= requests.get(f'https://reqres.in/api/users/{inputID}')\n userData=userRes.json()\n for userData_Key, userData_Values in userData.items():\n for key in userData_Values:\n if key == 'avatar':\n picture = userData_Values['avatar']\n if key == 'first_name':\n userFirstName=userData_Values['first_name']\n if key == 'last_name':\n userLastName = userData_Values['last_name']\n if key == 'email':\n userEmail = userData_Values['email']\n\n return render_template('assignment4_outer_source.html',userFirstName=userFirstName,userLastName=userLastName\n ,picture=picture, userEmail=userEmail)\n\n\n\n\n@assignment_4.route('/assignment4/restapi_users', defaults={'USER_ID': 319145959})\n@assignment_4.route('/assignment4/restapi_users/')\ndef restapi_func(USER_ID):\n if USER_ID==319145959:\n query = \"select * FROM users WHERE user_ID='319145959';\"\n users_list = app.interact_db(query, query_type='fetch')\n response = users_list[0]\n response = jsonify(response)\n return response\n\n\n query = \"select * FROM users WHERE user_ID='%s';\" % USER_ID\n users_list = app.interact_db(query, query_type='fetch')\n\n if len(users_list) != 0:\n response = users_list[0]\n else:\n response={\n 'success': False,\n 'error':'ID does not exist in the system'\n }\n response = jsonify(response)\n return response","repo_name":"ofirazulay/Assignment4_personal","sub_path":"assignment_4/assignment_4.py","file_name":"assignment_4.py","file_ext":"py","file_size_in_byte":6594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"36529475668","text":"import json\nimport os\nfrom PySide6 import QtCore, QtGui\nfrom PySide6.QtWidgets import QHBoxLayout, QListWidgetItem, QMessageBox, QProgressBar, QProgressDialog, QPushButton, QVBoxLayout, QWidget\nfrom BLabel import BLabel\nfrom SearchTable import SearchTable\nfrom SpectogramWidget import SpectogramWidget\nfrom WidgetDragDropFile import WidgetDragDropFile\nfrom AppLog import Log\nlog = Log()\n\nclass WidgetFiles(QWidget):\n def __init__(self, parent):\n super().__init__()\n\n self._parent = parent\n self._config = parent._config\n\n self._selected_file_path = None\n self._file_urls = {}\n self._file_id = 0\n self._parent._detector_file.detect_result.connect(self.updateResultTable)\n self._progress_value = 0\n self._spectogram_list = []\n\n layout = QVBoxLayout()\n layout.addWidget(BLabel(self._config.BUTTON_IMPORT, 14))\n \n self.view = WidgetDragDropFile(parent)\n self.view.fileDropped.connect(self.fileDropped)\n self.view.fileSelected.connect(self.fileSelected)\n layout.addWidget(self.view, stretch=1)\n\n # buttons\n layout_h = QHBoxLayout()\n self.button = QPushButton(\"Run Detection\")\n self.button.clicked.connect(self.analyzeFile)\n\n self.buttonClear = QPushButton(\"Clear Filelist\")\n self.buttonClear.clicked.connect(self.clearFileList)\n\n layout_h.addWidget(self.button)\n layout_h.addWidget(self.buttonClear)\n layout.addLayout(layout_h)\n\n # result table\n self.table_size = int(self._config.MAX_FILE_SIZE_SEC/self._config.FILE_DETECT_CHUNK_SEC)\n self.table = SearchTable(parent, [\"\" for i in range(1, self.table_size)])\n layout.addWidget(self.table, stretch=2)\n\n # button spectogram\n self.buttonSpectogram = QPushButton(\"Show Spectogram\")\n self.buttonSpectogram.clicked.connect(self.showSpectogram)\n self.buttonSpectogram.setVisible(False)\n layout.addWidget(self.buttonSpectogram)\n\n # progress bar\n css = []\n css.append(\"QProgressBar {text-align: center; padding: 1px; background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #bbb, stop: 0.4999 #999, stop: 0.5 #888, stop: 1 #999 ); width: 15px;}\")\n css.append(\"QProgressBar::chunk {background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #777, stop: 0.4999 #444, stop: 0.5 #555, stop: 1 #222 ); border-bottom-right-radius: 1px; border-bottom-left-radius: 0px; border: 0px solid black;}\")\n self.progressBar = QProgressBar(self)\n self.progressBar.setMinimum(0)\n self.progressBar.setMaximum(100)\n self.progressBar.setValue(0)\n self.progressBar.setStyleSheet(\" \".join(css))\n self.progressBar.setVisible(False)\n layout.addWidget(self.progressBar)\n\n # progress label\n self.progressLabel = BLabel(\"\", 10, None, parent._config.COLOR_FONT_DARK)\n self.progressLabel.setVisible(False)\n layout.addWidget(self.progressLabel)\n\n # footer\n label = BLabel(\"\", 12, None, parent._config.COLOR_FONT_DARK)\n self._parent._footer_labels.append(label)\n layout.addWidget(label)\n\n self.setLayout(layout)\n\n # timer for updating progress bar\n self.timer = QtCore.QTimer()\n self.timer.connect(self.timer, QtCore.SIGNAL(\"timeout()\"), self, QtCore.SLOT(\"updateProgressBar()\"))\n self.timer.setInterval(400)\n\n def addSpectogram(self, spectogram):\n self._spectogram_list.append(spectogram)\n if len(self._spectogram_list) > 2:\n self._spectogram_list.pop(0)\n\n def getSpectogram(self):\n return self._spectogram_list[-1]\n\n def getTimeWindow(self, max_slots=10):\n timeslots = []\n for i, selectedIndex in enumerate(self.table.selectedIndexes()):\n if (i < max_slots):\n coldata = selectedIndex.data().split(\" \")\n timeslot = coldata[0].replace(\"s\", \"\").split(\"-\")\n timeslot = list(map(lambda x: int(float(x)), timeslot))\n timeslots.append(timeslot)\n max_sec = max_slots * 3\n start = timeslots[0][0]\n end = timeslots[-1][1]\n if end - start > max_sec:\n return [start, start + max_sec]\n return [start, end]\n\n def showSpectogram(self, i):\n filepath = self._selected_file_path\n if len(self.table.selectedIndexes()) > 0 and filepath != None:\n timeWindow = self.getTimeWindow()\n self.addSpectogram(SpectogramWidget())\n self.getSpectogram().plot(filepath=filepath, mel_spec=True, window=timeWindow)\n self.getSpectogram().show()\n else:\n QMessageBox.warning(None, \"\", \"No file selected!\")\n\n def emptyResultTable(self):\n data = [\"\" for i in range(1, self.table_size)]\n self.table.setData(0, data, None)\n\n def getUniqueFilename(self, url):\n self._file_id += 1\n return str(self._file_id) + \". \" + url.split(\"/\")[-1]\n\n def getIcon(self, name):\n base_path = self._config.BASE_PATH + \"icons/\"\n icon_path = self._config.ICONS[name]\n return QtGui.QIcon(base_path + icon_path)\n\n def clearFileList(self):\n self._file_urls = {}\n self.view.clear()\n\n def fileDropped(self, l):\n for url in l:\n if os.path.exists(url):\n log.debug(url)\n filename = self.getUniqueFilename(url)\n self._file_urls[filename] = url\n self._selected_file_path = url\n item = QListWidgetItem(filename, self.view)\n item.setIcon(self.getIcon(self._config.BUTTON_IMPORT))\n item.setStatusTip(url)\n \n def fileSelected(self, l):\n for filename in l:\n if filename in self._file_urls:\n file_path = self._file_urls[filename]\n if os.path.exists(file_path):\n self._selected_file_path = file_path\n\n def toggleVisibility(self, widgetList):\n for w in widgetList:\n w.setVisible(not w.isVisible())\n\n def updateProgressBar(self):\n value = self._parent._detector_file.getProgress()\n if value == 0:\n self._progress_value += 1\n self.progressLabel.setText(\"Loading file...\")\n else:\n self._progress_value = value\n self.progressLabel.setText(\"Processing data...\")\n self.progressBar.setValue(self._progress_value)\n if value >= 100:\n self.timer.stop()\n self.progressLabel.setText(\"\")\n self.toggleVisibility([self.progressLabel, self.progressBar])\n self.buttonSpectogram.setVisible(True)\n\n def analyzeFile(self, i):\n log.debug(f\"WidgetFiles().analyzeFile(), file={self._selected_file_path}\")\n if (self._selected_file_path != None):\n self.emptyResultTable()\n self._progress_value = 0\n self.toggleVisibility([self.progressLabel, self.progressBar])\n self.buttonSpectogram.setVisible(False)\n self.timer.start()\n self._parent._detector_file.detect(1, self._selected_file_path)\n else:\n QMessageBox.warning(None, \"\", \"Select a file to analyze!\")\n\n def updateResultTable(self, result_json):\n items = json.loads(result_json)\n self.table.setData(0, items, None)","repo_name":"gorlang/BirdifyApp","sub_path":"src/WidgetFiles.py","file_name":"WidgetFiles.py","file_ext":"py","file_size_in_byte":7381,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"9171621648","text":"# -*- coding: utf-8 -*-\r\nimport sys\r\nimport os.path\r\n\r\n# Save the API_KEY to your home directory as a file named\r\n# SANDCAGE_API_KEY\r\napi_key_dir = os.path.expanduser('~')\r\napi_key_file = os.path.join(api_key_dir, 'SANDCAGE_API_KEY')\r\nwith open(api_key_file, 'r') as f:\r\n api_key = f.readline()\r\n \r\n\r\nsys.path.append(os.path.join(os.path.dirname(__file__), '../src'))\r\nfrom sandcage import SandCage\r\n\r\nsc = SandCage(api_key=api_key)\r\nresult = sc.schedule_files_service(\r\n {'jobs': [\r\n {'url': 'http://cdn.sandcage.com/p/a/img/logo.jpg',\r\n 'tasks': [\r\n {'actions': 'save'},\r\n {'actions': 'resize',\r\n 'filename': 'hello_world.jpg',\r\n 'width': 200},\r\n {'actions': 'crop',\r\n 'coords': '10,10,50,50'},\r\n {'reference_id': '1234567890',\r\n 'actions': 'rotate',\r\n 'degrees': 90},\r\n {'actions': 'cover',\r\n 'width': 60,\r\n 'height': 60,\r\n 'cover': 'middle,center'}]},\r\n {'url': 'http://cdn.sandcage.com/p/a/img/header_404.png',\r\n 'tasks': [\r\n {'actions': 'resize',\r\n 'height': 30}]}]})\r\n\r\nif result.status_code != 200:\r\n print('Http error occured with status code {}.'.format(result.status_code))\r\nelse:\r\n result_dict = result.json()\r\n print('Status: {}'.format(result_dict['status']))\r\n print('Request id: {}'.format(result_dict['request_id']))\r\n # Success or warning\r\n if result_dict['status'] == 'success' or result_dict['status'] == 'warning':\r\n # In case of warning, print out the warning messages\r\n if result_dict['status'] == 'warning':\r\n for msg in result_dict['warning_msg']:\r\n for (key, value) in msg.items():\r\n print('{}: {}'.format(key, value))\r\n print('')\r\n \r\n # Print out the tasks\r\n for task in result_dict['tasks']:\r\n for (key, value) in task.items():\r\n print('{}: {}'.format(key, value))\r\n print('')\r\n # In case of an error, print out the messages messages\r\n elif result_dict['status'] == 'error':\r\n for msg in result_dict['error_msg']:\r\n for (key, value) in msg.items():\r\n print('{}: {}'.format(key, value))\r\n print('')\r\n else:\r\n print('Unexpected status.')\r\n","repo_name":"sandcage/sandcage-api-python","sub_path":"examples/schedule_files.py","file_name":"schedule_files.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"77"} +{"seq_id":"30313170876","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport time\r\nfrom math import *\r\nfrom pprint import pprint\r\nfrom typing import Union\r\n\r\n#Décomposition QR avec houseolder\r\ndef householder_vectorized(a):\r\n v = a / (a[0] + np.copysign(np.linalg.norm(a), a[0]))\r\n v[0] = 1\r\n tau = 2 / (v.T @ v)\r\n return v,tau\r\ndef qr_decomposition(A: np.ndarray) -> Union[np.ndarray, np.ndarray]:\r\n m,n = A.shape\r\n R = A.copy()\r\n Q = np.identity(m)\r\n for j in range(0, n):\r\n v, tau = householder_vectorized(R[j:, j, np.newaxis])\r\n H = np.identity(m)\r\n H[j:, j:] -= tau * (v @ v.T)\r\n R = H @ R\r\n Q = H @ Q\r\n Q = Q[:n].T\r\n R = np.triu(R[:n])\r\n Qt = np.transpose(Q)\r\n return Q,R,Qt\r\n\r\n## Alternative-au-cocatenate\r\n\r\ndef concate (a,b):\r\n li,co = np.shape( a )\r\n a=np.ravel(a)\r\n b=np.ravel(b)\r\n V=[ ]\r\n X=['a']\r\n for x in a :\r\n X.append(x)\r\n for x in b :\r\n V.append(x)\r\n T=[]\r\n c=0 \r\n for x in range (1,li*co+1) :\r\n if x%co!=0:\r\n T.append(X[x])\r\n elif x%co==0:\r\n T.append(X[x])\r\n T.append(V[c])\r\n c=c+1\r\n a = np.array ([T]) \r\n a.resize(co,co+1)\r\n Ag=a\r\n Ag = np.array(Ag,dtype=float)\r\n return Ag\r\n\r\n## Generation de matrices aléatoires\r\ndef geneMa(n):\r\n \r\n p = 100\r\n if n >= p :\r\n p = n\r\n A = np.random.randint ( 1 , p , size = ( n , n ) )\r\n A=np.array(A,dtype=float)\r\n det = np.linalg.det(A)\r\n while det == 0 :\r\n A = np.random.randint ( 1 , p , size = ( n , n ) )\r\n A = np.array(A,dtype=float)\r\n det = np.linalg.det(A)\r\n At = np.transpose(A)\r\n A=At@A\r\n b = np.random.randint ( 1 , p , size = ( 1 , n ) )\r\n b = np.array(b,dtype=float)\r\n return A,b\r\n\r\n## Programme de la resolution de système\r\n\r\ndef resolutionSysTriSup (mat):\r\n P = np.array(mat)\r\n li , co = np.shape( P )\r\n global x\r\n x = np.zeros( li )\r\n for i in range ( li-1 , -1 , -1 ) : \r\n somme = 0\r\n for k in range ( li-1,i, -1 ) :\t\r\n somme = somme + P [ i , k ] * x[ k ] \r\n x [ i ] =( P [ i , li ] - somme ) / P [ i , i ]\r\n return x\r\n\r\ndef resolutionDiag ( mat ) :\r\n P = np.array ( mat )\r\n li , co = np.shape( P )\r\n y = np.zeros ( ( li ) )\r\n for i in range ( li ) :\r\n y [ i ] = ( P [ i , li ] ) / P [ i , i ]\r\n return y\r\n\r\ndef resolutionSysTriInf ( mat ) :\r\n P = np.array ( mat )\r\n li , co = np.shape( P )\r\n y = np.zeros ( ( li ) )\r\n for i in range ( li ) :\r\n somme = 0\r\n for k in range ( 0 , i + 1 ) :\r\n somme = somme + y [ k ] * P [ i , k ]\r\n y [ i ] = ( P [ i , li ] - somme ) / P [ i , i ]\r\n return y\r\n\r\n## different-type-de-décomposition-de-matrice\r\n\r\ndef Cholesky(A) :\r\n li , co = np.shape ( A )\r\n L = np.zeros (( li,co ))\r\n for i in range ( 0 , li ) : \r\n somme = 0\r\n for x in range (i): \r\n somme = somme + (L[i,x])**2 \r\n L [i,i] = (A[i,i] - somme)**0.5\r\n for c in range ( i+1 , li ) : \r\n somme1=0 \r\n for x in range (i):\r\n somme1 = somme1 + L[c,x]*L[i,x] \r\n L [c,i] = (A[c,i] - somme1)/L[i,i] \r\n A = np.array(A,dtype=float)\r\n L = np.array(L,dtype=float)\r\n Lt = np.transpose(L)\r\n Lt = np.array(Lt,dtype=float)\r\n return L,Lt\r\n\r\ndef Cholesky_Python (A):\r\n L = np.linalg.cholesky(A)\r\n Lt = np.transpose(L)\r\n return L,Lt\r\n\r\n#----different-type-de-résolution-d'équation-de-matrice---------\r\n\r\ndef ResolCholesky (A,B) :\r\n L,Lt = Cholesky(A)\r\n Ly = concate (L,B)\r\n y = resolutionSysTriInf ( Ly )\r\n aLy = concate (Lt,y)\r\n x = resolutionSysTriSup ( aLy )\r\n return x\r\n\r\ndef ResolCholesky_Python (A,B) :\r\n L,Lt = Cholesky_Python(A)\r\n Ly = concate (L,B)\r\n y = resolutionSysTriInf ( Ly )\r\n aLy = concate (Lt,y)\r\n x = resolutionSysTriSup ( aLy )\r\n return x\r\n\r\n#------------------Gauss---------------------------\r\ndef ReductionGauss ( mat ) :\r\n li,co = np.shape( mat )\r\n for k in range ( 0 , li-1 ) : \r\n for i in range ( k+1 , li ) :\r\n g = mat [ i , k ] / mat[ k , k]\r\n mat[ i , : ] = mat [ i , : ] - g*mat[ k , : ] \r\n return mat \r\n\r\ndef Gauss ( a , b ) :\r\n li,co = np.shape( a )\r\n Ag = concate ( a , b ) \r\n ReductionGauss ( Ag )\r\n resolutionSysTriSup ( Ag )\r\n return x\r\n\r\ndef Mg(n):\r\n Rd1,Bd=geneMa(n)\r\n x = Gauss (Rd1,Bd)\r\n return x \r\n\r\n#---Génération-de-matrice-aléatoire-pour-la-résolution--------\r\n\r\ndef AleaResolCholesky (n) :\r\n Rd1,Bd=geneMa(n)\r\n x = ResolCholesky (Rd1,Bd)\r\n return x\r\n\r\ndef AleaResolCholesky_Python (n) :\r\n Rd1,Bd=geneMa(n)\r\n x = ResolCholesky_Python (Rd1,Bd)\r\n return x\r\n\r\ndef AllResolv (n):\r\n Rd1,Bd=geneMa(n)\r\n x = ResolCholesky(Rd1,Bd)\r\n xP = ResolCholesky_Python(Rd1,Bd)\r\n return x,xP\r\n\r\n## Exercice 1\r\n\r\ndef DecompositionGS (A):\r\n n=len(A)\r\n R = np.zeros ([n,n])\r\n Q = np.zeros ([n,n])\r\n W = np.zeros ([n,n])\r\n S = 0\r\n R[0,0] = np.linalg.norm(A[:,0]) \r\n Q[:,0] = A[:,0]*(1/R[0,0])\r\n for j in range (1,n):\r\n S=0\r\n for i in range (0,j):\r\n R[i,j] = np.vdot(Q[:,i],A[:,j])\r\n S = S + R[i,j]*Q[:,i]\r\n W[:,j] = A[:,j]- S \r\n R[j,j] = np.linalg.norm(W[:,j]) \r\n Q[:,j] = W[:,j]*(1/R[j,j])\r\n Qt = np.transpose(Q)\r\n return Q,R,Qt\r\n \r\n\r\n\r\n## Exercice 2\r\n\r\ndef ResolGS(A,b) :\r\n Q,R,Qt = DecompositionGS (A)\r\n b = np.transpose(b)\r\n y = np.dot(Qt,b)\r\n X = concate(R,y)\r\n x = resolutionSysTriSup (X)\r\n return x\r\n\r\ndef RGS(n):\r\n A,b = geneMa(n)\r\n x = ResolGS(A,b)\r\n E = np.linalg.norm(A@x-np.ravel(b))\r\n print(E)\r\n\r\n\r\n## Resolution avec houseolder\r\n \r\ndef ResolHouse(A,b) :\r\n Q,R,Qt = qr_decomposition(A)\r\n b = np.transpose(b)\r\n y = np.dot(Qt,b)\r\n X = concate(R,y)\r\n x = resolutionSysTriSup (X)\r\n return x\r\n\r\ndef RHouse(n) :\r\n A,b = geneMa(n)\r\n x = ResolHouse(A,b)\r\n E = np.linalg.norm(A@x-np.ravel(b))\r\n print(E)\r\n\r\n## REsolution Qr python\r\n\r\ndef QrPython(A,b) :\r\n Q, R = np.linalg.qr(A)\r\n Qt = np.transpose(Q)\r\n b = np.transpose(b)\r\n y = np.dot(Qt,b)\r\n X = concate(R,y)\r\n x = resolutionSysTriSup (X)\r\n return x\r\n\r\ndef AllResolvListe (n):\r\n \r\n Rd1,Bd=geneMa(n)\r\n \r\n T0=time.time()\r\n x = ResolCholesky(Rd1,Bd)\r\n T1=time.time()\r\n T = round ( T1-T0 , 5 )\r\n E = np.linalg.norm(Rd1@x-np.ravel(Bd))\r\n\r\n T0=time.time()\r\n x = ResolCholesky_Python(Rd1,Bd)\r\n T1=time.time()\r\n Ta = round ( T1-T0 , 5 )\r\n Ea = np.linalg.norm(Rd1@x-np.ravel(Bd))\r\n\r\n T0=time.time()\r\n x = ResolGS(Rd1,Bd)\r\n T1=time.time()\r\n Tb = round ( T1-T0 , 5 )\r\n Eb = np.linalg.norm(Rd1@x-np.ravel(Bd))\r\n\r\n T0=time.time()\r\n xg = Gauss(Rd1,Bd)\r\n T1=time.time()\r\n Tg = round ( T1-T0 , 5 )\r\n Eg = np.linalg.norm(Rd1@xg-np.ravel(Bd))\r\n\r\n T0=time.time()\r\n xh = ResolHouse(Rd1,Bd)\r\n T1=time.time()\r\n Th = round ( T1-T0 , 5 )\r\n Eh = np.linalg.norm(Rd1@xg-np.ravel(Bd))\r\n\r\n T0=time.time()\r\n xp = QrPython(Rd1,Bd)\r\n T1=time.time()\r\n Tp = round ( T1-T0 , 5 )\r\n Ep = np.linalg.norm(Rd1@xg-np.ravel(Bd))\r\n \r\n return T,Ta,Tb,Tg,Th,Tp,E,Ea,Eb,Eg,Eh,Ep\r\n\r\n\r\n\r\n\r\nL=[]\r\nL1=[]\r\nL2=[]\r\nL3=[]\r\nL4=[]\r\nL5=[]\r\nL6=[]\r\nL7=[]\r\nL8=[]\r\nL9=[]\r\nL10=[]\r\nL11=[]\r\nL12=[]\r\n\r\n\r\nfor i in range (4,501,25) :\r\n L.append(float(i))\r\n T,Ta,Tb,Tg,Th,Tp,E,Ea,Eb,Eg,Eh,Ep = AllResolvListe(i)\r\n L1.append(T)\r\n L2.append(E)\r\n L3.append(Ta)\r\n L4.append(Ea)\r\n L5.append(Tb)\r\n L6.append(Eb)\r\n L7.append(Tg)\r\n L8.append(Eg)\r\n L9.append(Th)\r\n L10.append(Eh)\r\n L11.append(Tp)\r\n L12.append(Ep)\r\n\r\nx = L\r\ny1 = L1\r\ny2 = L3\r\ny3 = L5\r\ny4 = L7\r\ny5 = L9\r\ny6 = L11\r\n\r\nplt.title(\"Temps de traitement en fonction de la taille de la matrice\")\r\nplt.xlabel(\"Taille de la matrice\")\r\nplt.ylabel(\"Temps\")\r\nplt.plot(x,y1,label=\"Cholesky\")\r\nplt.plot(x,y2,label=\"Cholesky Python\")\r\nplt.plot(x,y3,label=\"Decomposition QR\")\r\nplt.plot(x,y4,label=\"Gauss\")\r\nplt.plot(x,y5,label=\"QR Houseolder\")\r\nplt.plot(x,y6,label=\"QR Python\")\r\nplt.legend()\r\nplt.show()\r\n\r\nx = L\r\ny1 = L2\r\ny2 = L4\r\ny3 = L6\r\ny4 = L8\r\ny5 = L10\r\ny6 = L12\r\n\r\nplt.title(\"Erreur en fonction de la taille de la matrice\")\r\nplt.xlabel(\"Taille de la matrice\")\r\nplt.ylabel(\"Erreurs\")\r\nplt.plot(x,y1,label=\"Cholesky\")\r\nplt.plot(x,y2,label=\"Cholesky Python\")\r\nplt.plot(x,y3,label=\"Decomposition QR\")\r\nplt.plot(x,y4,label=\"Gauss\")\r\nplt.plot(x,y5,label=\"QR Houseolder\")\r\nplt.plot(x,y6,label=\"QR Python\")\r\n\r\nplt.legend()\r\nplt.show()\r\n\r\n\r\n\r\n","repo_name":"Ramel2000/Travaux_Entretien","sub_path":"Décomposition_QR_Algorithme_de_Gram_Schmidt/Rapport.py","file_name":"Rapport.py","file_ext":"py","file_size_in_byte":8613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"71952984568","text":"import pretty_midi\nimport PySimpleGUI as sg\nimport os\nfrom matplotlib import pyplot as plt\n\nfrom interface.components.message_log import MessageLog\nfrom interface.components.message_log import LogLevel\nfrom interface.util.player import Player\nimport interface.util.midi_util as mu\nimport util.data_handling as dh\nfrom accompaniment_generator import AccompanimentGenerator\n\n\nclass MainWindow:\n def __init__(self, model_seq_secs=15, autosave=True, log_level=LogLevel.DEBUG):\n self.autosave = autosave\n self.player = Player()\n self.midi_filepath = None\n\n self.model_seq_secs = model_seq_secs\n self.selection_start = 0\n self.selection_end = self.selection_start + self.model_seq_secs\n\n self.pm = pretty_midi.PrettyMIDI()\n self.song_duration = 100\n self.tracks = []\n self.num_tracks = 0\n self.max_tracks = 4\n\n self.log_level=log_level\n self.playing = False\n self.recording = False\n self.window_vals = None\n self.main_dir = os.path.abspath(os.path.dirname(__file__))\n self.interface_dir = os.path.join(self.main_dir, 'interface')\n\n self.model_list = ['LSTM', 'LSTM VAE']\n self.model_paths = {self.model_list[0]: os.path.join(self.main_dir, 'examples', 'lstm_accompaniment'),\n self.model_list[1]: os.path.join(self.main_dir, 'examples', 'lstm_vae')}\n self.model_name = self.model_list[0]\n self.model_path = self.model_paths[self.model_name]\n self.model = None\n self.load_model()\n\n self.control_panel = [\n sg.Button('Import', key='-IMPORT-'),\n sg.Button('Save', key='-SAVE-'),\n sg.Button('Record', key='-RECORD-'),\n sg.Button('Previous', key='-PREVIOUS-'),\n sg.Button('Play/Pause', key='-PLAY-'),\n sg.Button('Next', key='-NEXT-'),\n sg.Button('Generate', key='-GENERATE-'),\n sg.Combo(self.model_list, default_value=self.model_list[0], s=(15,22), enable_events=True, readonly=True, k='-MODEL-')\n ]\n\n self.timeline = [\n [ sg.T('Selection Start:End -> ', size=(22,1), key='-TIMELINE_TEXT-'),\n sg.Input(default_text='0', size=(4,1), key='-SELECTION_START-', enable_events=True), sg.T('s:'),\n sg.Input(default_text='15', size=(4,1), key='-SELECTION_END-', enable_events=True), sg.T('s')],\n [ sg.Slider((0,100), key='-SLIDER-', orientation='h', enable_events=True, disable_number_display=True, size=(138,15), default_value=self.selection_start)]\n ]\n\n self.composer = [\n # [sg.Text('Track 1', size=(20,10)), sg.Graph(canvas_size=(1550, 250), graph_bottom_left=(0,0), graph_top_right=(400, 400), key='-GRAPH0-')],\n # [sg.Graph(canvas_size=(1550, 250), graph_bottom_left=(0,0), graph_top_right=(400, 400), key='-GRAPH0-')],\n # [sg.Image('/home/bryan/amici_model/coral_amici/src/interface/empty_track.png', key='-TRACK_IMG0-')],\n [sg.Image(os.path.join(self.interface_dir, 'empty_track.png'), key='-TRACK_IMG0-')],\n [sg.Image(os.path.join(self.interface_dir, 'empty_track.png'), key='-TRACK_IMG1-')],\n [sg.Image(os.path.join(self.interface_dir, 'empty_track.png'), key='-TRACK_IMG2-')],\n [sg.Image(os.path.join(self.interface_dir, 'empty_track.png'), key='-TRACK_IMG3-')],\n ]\n self.message_log = MessageLog(log_level=LogLevel.DEBUG)\n\n self.layout = [ self.control_panel,\n self.timeline,\n self.composer,\n self.message_log.get_component()\n ]\n\n \n self.event_callbacks = { \n '-IMPORT-': self.import_midi,\n '-SAVE-': self.save,\n '-RECORD-': self.record_midi,\n '-PREVIOUS-': self.previous,\n '-PLAY-': self.play_pause,\n '-NEXT-': self.next,\n '-GENERATE-': self.generate_accompaniment,\n '-SLIDER-': self.update_timeline,\n '-SELECTION_START-': self.update_selection_start,\n '-SELECTION_END-': self.update_selection_end,\n '-MODEL-': self.select_model,\n None: print\n }\n\n self.autosave_functions = ['-IMPORT-', '-SAVE-', '-RECORD-', '-GENERATE-' ]\n\n sg.theme('DarkBlue15')\n self.window = sg.Window('AMICI Composer', self.layout)\n\n def get_plot_img(self, sampling_frequency=100, notes_to_plot=1500, filename='track.png'):\n if self.pm:\n notes = self.pm.get_piano_roll(fs=sampling_frequency)\n plt.matshow(notes[:,:notes_to_plot])\n plt.axis('off')\n plt.savefig(filename, bbox_inches='tight', pad_inches=0)\n\n def test_import(self):\n self.midi_filepath = self.prompt('Enter the path to the MIDI file\\n(e.g. \\\"/home/bryan/amici/POP909-Dataset/POP909/001/001.mid\\\"):')\n\n seq_duration = self.model_seq_secs if self.model_seq_secs else -1\n self.pm, self.selection_start, self.selection_end = mu.import_and_select(self.midi_filepath, seq_duration)\n self.display_notification(LogLevel.INFO, f'Loaded {self.midi_filepath}')\n\n def run_interface(self):\n try:\n while True: \n # Display and interact with the Window\n event, self.window_vals = self.window.read()\n\n print(f'{event}, {self.window_vals}')\n\n try:\n self.event_callbacks[event]()\n except KeyError:\n self.display_notification(LogLevel.WARNING, f'Unknown event: {event}')\n\n # self.display_notification(LogLevel.DEBUG, f'{event}')\n # self.display_notification(LogLevel.DEBUG, f'{values}')\n\n if self.autosave and event in self.autosave_functions:\n self.save()\n\n if event == sg.WIN_CLOSED or event == 'Exit':\n self.display_notification(LogLevel.INFO, 'Shutting down...')\n break\n\n except KeyboardInterrupt:\n self.display_notification(LogLevel.INFO, 'Shutting down...')\n self.window.close()\n\n def display_notification(self, level, text):\n self.message_log.log(level, text)\n self.window[self.message_log.key].update(self.message_log.messages)\n\n def update_timeline(self):\n self.selection_start = int(self.window_vals['-SLIDER-'])\n self.selection_end = min(self.selection_start + 15, self.song_duration)\n # self.window['-TIMELINE_TEXT-'].update(f'Selection Start:End -> {self.selection_start}s : {self.selection_end}s')\n self.window['-SELECTION_START-'].update(f'{self.selection_start}')\n self.window['-SELECTION_END-'].update(f'{self.selection_end}')\n self.model.set_selection(self.selection_start)\n self.update_track_selections()\n\n def update_slider_range(self):\n self.window['-SLIDER-'].update(range=(0, self.song_duration - self.model_seq_secs))\n\n def update_selection_start(self):\n self.selection_start = int(self.window_vals['-SELECTION_START-'])\n self.selection_end = self.selection_start + self.model_seq_secs\n self.window['-SELECTION_END-'].update(self.selection_end)\n self.window['-SLIDER-'].update(self.selection_start)\n self.model.set_selection(self.selection_start)\n self.update_track_selections()\n\n def update_selection_end(self):\n self.selection_end = int(self.window_vals['-SELECTION_END-'])\n self.selection_start = max(0, self.selection_end - self.model_seq_secs)\n self.window['-SELECTION_START-'].update(self.selection_start)\n self.window['-SLIDER-'].update(self.selection_start)\n self.model.set_selection(self.selection_start)\n self.update_track_selections()\n\n def prompt(self, message, filepath=False):\n layout = [[sg.Text(f'{message}')], \n [sg.InputText(key='-IN-')], \n [sg.Submit(key='-PROMPT_SUBMIT-'), sg.Cancel(key='-PROMPT_CANCEL-')]] \n \n window = sg.Window('User Input', layout)\n while True:\n event, values = window.read() \n\n if event in ['-PROMPT_SUBMIT-', '-PROMPT_CANCEL-']:\n break\n # TODO: input validation here\n window.close()\n print('closing...')\n return values['-IN-']\n\n def update_track_crop(self, track_num):\n dh.plot_piano_roll(self.pm, tracks=(self.tracks[track_num][0],),\n start_time=self.selection_start, duration=self.model_seq_secs,\n axes=False, save_file=self.tracks[track_num][1], background_color='blue')\n self.window[f'-TRACK_IMG{track_num}-'].update(self.tracks[track_num][1])\n\n def update_track_selections(self):\n for track_num in range(self.num_tracks):\n self.update_track_crop(track_num)\n\n def add_track(self, instrument):\n if self.num_tracks >= self.max_tracks:\n self.display_notification(LogLevel.WARNING, f'Already reached max tracks({self.max_tracks})')\n return\n else: \n self.pm.instruments.append(instrument)\n img_file = os.path.join(self.interface_dir, f'TRACK_IMG{self.num_tracks}.png')\n self.tracks.append( (instrument.name, img_file) )\n self.update_track_crop(self.num_tracks)\n self.num_tracks += 1\n\n def import_midi(self, overwrite=True):\n self.midi_filepath = None\n\n # try:\n self.midi_filepath = self.prompt('Enter the path to the MIDI file\\n(e.g. \\\"/home/bryan/amici/POP909-Dataset/POP909/001/001.mid\\\"):')\n\n try:\n seq_duration = self.model_seq_secs if self.model_seq_secs else -1\n self.pm, (self.selection_start, self.selection_end) = mu.import_and_select(self.midi_filepath, seq_duration)\n self.song_duration = self.pm.get_end_time()\n self.model.set_input_file(self.midi_filepath)\n self.update_slider_range()\n\n for instrument in self.pm.instruments:\n if self.num_tracks >= self.max_tracks -1:\n self.display_notification(LogLevel.INFO, f'Reached max import tracks({self.max_tracks -1})')\n break\n \n self.add_track(instrument)\n\n self.display_notification(LogLevel.INFO, f'Loaded {self.midi_filepath}')\n except Exception as e:\n print(e)\n self.display_notification(LogLevel.WARNING, f'Unable to load {self.midi_filepath}\\nCheck path and try again.')\n return\n \n def record_midi(self):\n if self.recording:\n self.display_notification(LogLevel.INFO, 'Recording stopped.')\n self.recording = False\n else:\n self.recording = True\n self.display_notification(LogLevel.INFO, 'Recording started...')\n\n def previous(self):\n self.display_notification(LogLevel.DEBUG, 'Previous.')\n # decrement sequence pointers by seq_len if possible or go back to beginning\n \n def play_pause(self, start_time=0, stop_time=-1):\n if self.playing:\n self.player.stop()\n self.playing = False\n self.display_notification(LogLevel.INFO, 'Paused.')\n else:\n self.playing = True\n # self.play(values, start_time=self.selection_start, stop_time=self.selection_end)\n if self.midi_filepath:\n self.display_notification(LogLevel.INFO, 'Playing...')\n self.player.play(self.midi_filepath)\n else:\n self.display_notification(LogLevel.WARNING, 'No MIDI file selected/saved.')\n\n def next(self):\n self.display_notification(LogLevel.DEBUG, 'Next.')\n # increment sequence pointerssby seq_len if possible or go to end\n\n def load_model(self): \n self.model = AccompanimentGenerator(self.model_path, self.midi_filepath, 'test_generation.mid',\n sequence_seconds=15, start_secs=self.selection_start, skip_empty_intro=True,\n vocab_size=128, samples_per_sec=1, only_keep_melody_track=True)\n\n def select_model(self):\n if self.model_name != self.window_vals['-MODEL-']:\n self.model_name = self.window_vals['-MODEL-']\n self.load_model()\n \n def generate_accompaniment(self):\n # load accompaniment model\n self.display_notification(LogLevel.INFO, 'Generating accompaniment...')\n gen_inst = self.model.generate()\n self.add_track(gen_inst)\n \n def save(self):\n # Save pm to .mid file\n # TODO: use pikle to save pm memory for quicker loading later\n self.pm.write('amici_composition.mid')\n self.display_notification(LogLevel.INFO, 'Saved.')\n\n def delete_track(self):\n pass\n\n# Load File:\n# path = input('Enter the path to the MIDI file\\n(e.g. \"/home/bryan/amici/POP909-Dataset/POP909/001/001.mid\"):')\n# midi_data = pretty_midi.PrettyMIDI(path)\n\nif __name__ == '__main__':\n main_window = MainWindow()\n # main_window.test_import()\n main_window.run_interface()\n\n # load any large files into memory first, show splash screen\n # build main window\n # show main window\n # start interface loop","repo_name":"BryanJHealy/coral_amici","sub_path":"src/main_interface.py","file_name":"main_interface.py","file_ext":"py","file_size_in_byte":13279,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"16655559416","text":"from kaa.command import commandid\nfrom kaa.command import norec\nfrom kaa.command import norerun\nfrom kaa import document\nfrom kaa.ui.dialog import dialogmode\nfrom kaa.keyboard import *\n\nMoveSeparatorThemes = {\n 'basic': [],\n}\n\nmoveseparator_keys = {\n left: 'moveseparator.prev',\n up: 'moveseparator.prev',\n (ctrl, 'p'): 'moveseparator.prev',\n (ctrl, 'b'): 'moveseparator.prev',\n right: 'moveseparator.next',\n down: 'moveseparator.next',\n (ctrl, 'f'): 'moveseparator.next',\n (ctrl, 'n'): 'moveseparator.next',\n '\\r': 'moveseparator.done',\n '\\n': 'moveseparator.done',\n}\n\n\nclass MoveSeparatorMode(dialogmode.DialogMode):\n USE_UNDO = False\n\n @classmethod\n def build(cls, target):\n doc = document.Document()\n mode = cls()\n doc.setmode(mode)\n\n mode.org_wnd = target\n mode.target = target.splitter.parent\n\n with dialogmode.FormBuilder(doc) as f:\n f.append_text('caption',\n 'Hit cursor left/right key to resize window.')\n return doc\n\n def init_keybind(self):\n self.keybind.add_keybind(moveseparator_keys)\n\n def init_themes(self):\n super().init_themes()\n self.themes.append(MoveSeparatorThemes)\n\n def is_cursor_visible(self):\n return 0 # hide cursor\n\n def on_esc_pressed(self, wnd, event):\n self.done(wnd)\n\n def on_str(self, wnd, s, overwrite=False):\n pass\n\n @commandid('moveseparator.prev')\n @norec\n @norerun\n def prev(self, wnd):\n if wnd.document.mode.target:\n wnd.document.mode.target.separator_prev()\n\n @commandid('moveseparator.next')\n @norec\n @norerun\n def next(self, wnd):\n if wnd.document.mode.target:\n wnd.document.mode.target.separator_next()\n\n @commandid('moveseparator.done')\n @norec\n @norerun\n def done(self, wnd):\n # restore cursor\n org_wnd = wnd.document.mode.org_wnd\n org_wnd.activate()\n\n # Destroy popup window\n popup = wnd.get_label('popup')\n if popup:\n popup.destroy()\n\n org_wnd.activate()\n\n\ndef move_separator(wnd):\n doc = MoveSeparatorMode.build(wnd)\n kaa.app.show_dialog(doc)\n","repo_name":"kaaedit/kaa","sub_path":"kaa/ui/moveseparator/moveseparatormode.py","file_name":"moveseparatormode.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","stars":124,"dataset":"github-code","pt":"77"} +{"seq_id":"40674370240","text":"import logging\n\nimport numpy as np\n\nfrom aspire.basis import FFBBasis2D\nfrom aspire.classification import (\n Averager2D,\n BFRAverager2D,\n BFSRAverager2D,\n Class2D,\n ClassSelector,\n NeighborVarianceWithRepulsionClassSelector,\n RIRClass2D,\n TopClassSelector,\n)\nfrom aspire.image import Image\nfrom aspire.source import ImageSource\n\nlogger = logging.getLogger(__name__)\n\n\nclass ClassAvgSource(ImageSource):\n \"\"\"\n Source for denoised 2D images using class average methods.\n \"\"\"\n\n def __init__(\n self,\n src,\n classifier,\n class_selector,\n averager,\n ):\n \"\"\"\n Constructor of an object for denoising 2D images using class averaging methods.\n\n :param src: Source used for image classification.\n :param classifier: Class2D subclass used for image classification.\n Example, RIRClass2D.\n :param class_selector: A ClassSelector subclass.\n :param averager: An Averager2D subclass.\n \"\"\"\n self.src = src\n if not isinstance(self.src, ImageSource):\n raise ValueError(\n f\"`src` should be subclass of `ImageSource`, found {self.src}.\"\n )\n\n self.classifier = classifier\n if not isinstance(self.classifier, Class2D):\n raise ValueError(\n f\"`classifier` should be subclass of `Class2D`, found {self.classifier}.\"\n )\n\n self.class_selector = class_selector\n if not isinstance(self.class_selector, ClassSelector):\n raise ValueError(\n f\"`class_selector` should be instance of `ClassSelector`, found {class_selector}.\"\n )\n\n self.averager = averager\n if not isinstance(self.averager, Averager2D):\n raise ValueError(\n f\"`averager` should be instance of `Averager2D`, found {self.averager}.\"\n )\n\n # Flag for lazy eval, we'll classify once, on first touch.\n self._classified = False\n self._selected = False\n\n # Note n will potentially be updated after class selection.\n # Manage delayed setting `n` once.\n self._n_set = False\n\n super().__init__(\n L=self.averager.src.L,\n n=self.averager.src.n,\n dtype=self.averager.src.dtype,\n )\n\n # Any further operations should not mutate this instance.\n # Note, updating `n` is a special case for this source at this time.\n self._mutable = False\n\n @ImageSource.n.setter\n def n(self, n):\n \"\"\"\n Sets max image index `n` in `src` and associated\n `ImageAccessor`.\n\n :param n: Number of images.\n \"\"\"\n\n # Resets the protection of self._n exactly once after __init__.\n if (self._n is not None) and (not self._n_set):\n self._n = None\n self._n_set = True\n\n super()._set_n(n)\n\n def _classify(self):\n \"\"\"\n Perform the image classification (if not already done).\n \"\"\"\n\n # Short circuit\n if self._classified:\n logger.debug(f\"{self.__class__.__name__} already classified, skipping\")\n return\n\n (\n self.class_indices,\n self.class_refl,\n self.class_distances,\n ) = self.classifier.classify()\n self._classified = True\n\n @property\n def selection_indices(self):\n self._class_select()\n return super().selection_indices\n\n @selection_indices.setter\n def selection_indices(self, value):\n self.set_metadata([\"_selection_indices\"], value)\n\n @property\n def class_indices(self):\n \"\"\"\n Returns table of class image indices as `(src.n, n_nbors)`\n Numpy array.\n\n Each row reprsents a class, with the columns ordered by\n smallest `class_distances` from the reference image (zeroth\n columm).\n\n Note `n_nbors` is managed by `self.classifier` and used here\n for documentation.\n\n :return: Numpy array, integers.\n \"\"\"\n self._classify()\n return super().class_indices\n\n @class_indices.setter\n def class_indices(self, table):\n self.set_metadata(\n [\"_class_indices\"], [\",\".join(map(str, row)) for row in table]\n )\n\n @property\n def class_refl(self):\n \"\"\"\n Returns table of class image reflections as `(src.n, n_nbors)`\n Numpy array.\n\n Follows same layout as `class_indices` but holds booleans that\n are True when the image should be reflected before averaging.\n\n Note `n_nbors` is managed by `self.classifier` and used here\n for documentation.\n\n :return: Numpy array, boolean.\n \"\"\"\n self._classify()\n return super().class_refl\n\n @class_refl.setter\n def class_refl(self, table):\n # Convert boolean to (O, 1) integers.\n array_int = np.array(table, dtype=int)\n self.set_metadata(\n [\"_class_refl\"], [\",\".join(map(str, row)) for row in array_int]\n )\n\n @property\n def class_distances(self):\n \"\"\"\n Returns table of class image distances as `(src.n, n_nbors)`\n Numpy array.\n\n Follows same layout as `class_indices` but holds floats\n representing the distance (returned by classifier) to the\n zeroth image in each class.\n\n Note `n_nbors` is managed by `self.classifier` and used here\n for documentation.\n\n :return: Numpy array, self.dtype.\n \"\"\"\n self._classify()\n return super().class_distances\n\n @class_distances.setter\n def class_distances(self, table):\n self.set_metadata(\n [\"_class_distances\"], [\",\".join(map(str, row)) for row in table]\n )\n\n def _class_select(self):\n \"\"\"\n Uses the `class_selector` in conjunction with the classifier results\n to select the classes (and order) used for image averager,\n if not already done.\n \"\"\"\n\n # Short circuit\n if self._selected:\n logger.debug(\n f\"{self.__class__.__name__} already selected classes, skipping\"\n )\n return\n\n # Evaluate the classification network.\n if not self._classified:\n self._classify()\n\n # Perform class selection\n _selection_indices = self.class_selector.select(\n self.class_indices,\n self.class_refl,\n self.class_distances,\n )\n\n # Override the initial self.n\n # Some selectors will (dramatically) reduce the space of classes.\n if len(_selection_indices) != self.n:\n logger.info(\n f\"After selection process, updating maximum {len(_selection_indices)} classes from {self.n}.\"\n )\n # Note, setter should be inherited from base ImageSource.\n self.n = len(_selection_indices)\n\n self._selected = True\n self.selection_indices = _selection_indices\n\n def save(self, *args, **kwargs):\n \"\"\"\n Save metadata to STAR file.\n\n See `ImageSource.save` for documentation.\n \"\"\"\n # Evaluate any lazy actions.\n # This should populate relevant metadata.\n self._class_select()\n # Call parent `save` method.\n return super().save(*args, **kwargs)\n\n def _images(self, indices):\n \"\"\"\n Output images\n \"\"\"\n\n # Lazy evaluate the class selection\n if not self._selected:\n self._class_select()\n\n # Truncate the request if nessecary,\n # ie, when selection reduces `self.n`.\n indices = np.array(indices, dtype=int)\n selected = indices[indices < self.n]\n\n if len(indices) != len(selected):\n deselected = indices[indices >= self.n]\n logger.debug(\n f\"Dropping requested indices {deselected} following to selection process.\"\n )\n indices = selected\n\n # Remap to the selected ordering\n _indices = indices.copy() # Store original mapping\n indices = self.selection_indices[indices]\n\n # Check if there is a cache available from class selection component.\n # Note, we can use := for this in the branch directly, when Python>=3.8\n heap_inds = None\n # Check we are using the same averager before attempting to use heap.\n if hasattr(self.class_selector, \"heap\") and (\n self.averager == self.class_selector.averager\n ):\n # Then check if request matches anything in the heap.\n heap_inds = set(indices).intersection(self.class_selector.heap_ids)\n\n # Check if this src cached images.\n if self._cached_im is not None:\n logger.debug(f\"Loading {len(indices)} images from image cache\")\n im = Image(self._cached_im[indices, :, :])\n\n # Check for heap cached image sets from class_selector.\n elif heap_inds:\n logger.debug(f\"Mapping {len(heap_inds)} images from heap cache.\")\n\n # Images in heap_inds can be fetched from class_selector.\n # For others, create an indexing map that preserves\n # original order. Both of these dicts map requested image\n # id to location in the return array `im`.\n\n # Note, this stores inds from the remapped `indices`.\n indices_from_heap = {\n ind: i for i, ind in enumerate(indices) if ind in heap_inds\n }\n # Note, this stores _inds from the original `_indices`.\n # This allows the recusive call, which remaps the indices.\n indices_to_compute = {\n _ind: i\n for i, _ind in enumerate(_indices)\n if self.selection_indices[_ind] not in heap_inds\n }\n\n # Get heap dict once to avoid traversing heap in a loop.\n heap_dict = self.class_selector.heap_idx_map\n\n # Create an empty array to pack results.\n L = self.averager.src.L\n im = np.empty(\n (len(indices), L, L),\n dtype=self.averager.dtype,\n )\n\n # Recursively call `_images`.\n # `heap_inds` set should be empty in the recursive call,\n # and compute only remaining images (those not in heap).\n _compute_indices = list(indices_to_compute.keys())\n # Skip when empty (everything requested in heap).\n if len(_compute_indices):\n _imgs = self._images(_compute_indices)\n\n # Pack images computed from `_images` recursive call.\n _inds = list(indices_to_compute.values())\n im[_inds] = _imgs\n\n # Pack images from heap.\n for k, i in indices_from_heap.items():\n # map the image index to heap item location\n heap_loc = heap_dict[k]\n im[i] = self.class_selector.heap[heap_loc].image\n\n # Finally construct an Image.\n im = Image(im)\n\n else:\n # Perform image averaging for the requested images (classes)\n logger.debug(f\"Averaging {len(_indices)} images from source\")\n im = self.averager.average(\n self.class_indices[_indices], self.class_refl[_indices]\n )\n\n # Finally, apply transforms to resulting Images\n return self.generation_pipeline.forward(im, indices)\n\n\n# The following sub classes attempt to pack sensible defaults\n# into ClassAvgSource so that users don't need to\n# instantiate every component to get started.\n\n\nclass DebugClassAvgSource(ClassAvgSource):\n \"\"\"\n Source for denoised 2D images using class average methods.\n\n In this context Debug means defaulting to:\n * Using the defaults for `RIRClass2D`.\n * Using `TopClassSelector` to select all classes maintaining the same order as the input source.\n * Using `BFRAverager2D` with defaults on a single core.\n \"\"\"\n\n def __init__(\n self,\n src,\n n_nbor=10,\n num_procs=1, # Change to \"auto\" if your machine has many processors\n classifier=None,\n class_selector=None,\n averager=None,\n ):\n \"\"\"\n Instantiates with default debug paramaters.\n\n :param src: Source used for image classification.\n :param n_nbor: Number of nearest neighbors. Default 10.\n :param num_procs: Number of processors. Default of 1 runs serially.\n `None` attempts to compute a reasonable value\n based on available cores and memory.\n :param classifier: `Class2D` classifier instance.\n Default `None` creates `RIRClass2D`.\n See code for parameter details.\n :param class_selector: `ClassSelector` instance.\n Default `None` creates `TopClassSelector`.\n :param averager: `Averager2D` instance.\n Default `None` ceates `BFRAverager2D` instance.\n See code for parameter details.\n\n :return: ClassAvgSource instance.\n \"\"\"\n dtype = src.dtype\n\n if classifier is None:\n classifier = RIRClass2D(\n src,\n fspca_components=400,\n bispectrum_components=300, # Compressed Features after last PCA stage.\n n_nbor=n_nbor,\n large_pca_implementation=\"legacy\",\n nn_implementation=\"legacy\",\n bispectrum_implementation=\"legacy\",\n )\n\n if averager is None:\n averager = BFRAverager2D(\n FFBBasis2D(src.L, dtype=src.dtype),\n src,\n num_procs=num_procs,\n dtype=dtype,\n )\n\n if class_selector is None:\n class_selector = TopClassSelector()\n\n super().__init__(\n src=src,\n classifier=classifier,\n class_selector=class_selector,\n averager=averager,\n )\n\n\ndef DefaultClassAvgSource(\n src,\n n_nbor=50,\n num_procs=None,\n classifier=None,\n class_selector=None,\n averager=None,\n averager_src=None,\n version=None,\n):\n \"\"\"\n Source for denoised 2D images using class average methods.\n\n Accepts `version`, to dispatch ClassAvgSource with parameters\n below. Default `version` is latest available.\n\n :param src: Source used for image classification.\n :param n_nbor: Number of nearest neighbors. Default 50.\n :param num_procs: Number of processors. Use 1 to run serially.\n Default `None` attempts to compute a reasonable value\n based on available cores and memory.\n :param classifier: `Class2D` classifier instance.\n Default `None` creates `RIRClass2D`.\n See code for parameter details.\n :param class_selector: `ClassSelector` instance.\n Default `None` creates `NeighborVarianceWithRepulsionClassSelector`.\n :param averager: `Averager2D` instance.\n Default `None` ceates `BFSRAverager2D` instance.\n See code for parameter details.\n :param averager_src: Optionally explicitly assign source\n to BFSRAverager2D during initialization.\n Raises error when combined with an explicit `averager`\n argument.\n :param version: Optionally selects a versioned DefaultClassAvgSource.\n Defaults to latest available.\n :return: ClassAvgSource instance.\n \"\"\"\n\n _versions = {\n None: ClassAvgSourcev110,\n \"latest\": ClassAvgSourcev110,\n \"0.11.0\": ClassAvgSourcev110,\n }\n\n if version not in _versions:\n raise RuntimeError(f\"DefaultClassAvgSource version {version} not found.\")\n cls = _versions[version]\n\n return cls(\n src,\n n_nbor=n_nbor,\n num_procs=num_procs,\n classifier=classifier,\n class_selector=class_selector,\n averager=averager,\n averager_src=averager_src,\n )\n\n\nclass ClassAvgSourcev110(ClassAvgSource):\n \"\"\"\n Source for denoised 2D images using class average methods.\n\n Defaults to using Contrast based class selection (on the fly, compressed),\n avoiding neighbors of previous classes,\n and a brute force image alignment.\n\n Currently this is the most reasonable default for experimental data.\n \"\"\"\n\n def __init__(\n self,\n src,\n n_nbor=50,\n num_procs=None,\n classifier=None,\n class_selector=None,\n averager=None,\n averager_src=None,\n ):\n \"\"\"\n Instantiates ClassAvgSourcev11 with the following parameters.\n\n :param src: Source used for image classification.\n :param n_nbor: Number of nearest neighbors. Default 50.\n :param num_procs: Number of processors. Use 1 to run serially.\n Default `None` attempts to compute a reasonable value\n based on available cores and memory.\n :param classifier: `Class2D` classifier instance.\n Default `None` creates `RIRClass2D`.\n See code for parameter details.\n :param class_selector: `ClassSelector` instance.\n Default `None` creates `NeighborVarianceWithRepulsionClassSelector`.\n :param averager: `Averager2D` instance.\n Default `None` ceates `BFSRAverager2D` instance.\n See code for parameter details.\n :param averager_src: Optionally explicitly assign source\n to BFSRAverager2D during initialization.\n Raises error when combined with an explicit `averager`\n argument.\n\n :return: ClassAvgSource instance.\n \"\"\"\n dtype = src.dtype\n\n if classifier is None:\n classifier = RIRClass2D(\n src,\n fspca_components=400,\n bispectrum_components=300, # Compressed Features after last PCA stage.\n n_nbor=n_nbor,\n large_pca_implementation=\"legacy\",\n nn_implementation=\"sklearn\", # Note this is different than debug\n bispectrum_implementation=\"legacy\",\n )\n\n if averager is None:\n if averager_src is None:\n averager_src = src\n\n basis_2d = FFBBasis2D(averager_src.L, dtype=dtype)\n\n averager = BFSRAverager2D(\n composite_basis=basis_2d,\n src=averager_src,\n num_procs=num_procs,\n dtype=dtype,\n )\n elif averager_src is not None:\n raise RuntimeError(\n \"When providing an instantiated `averager`, cannot assign `averager_src`.\"\n )\n\n if class_selector is None:\n class_selector = NeighborVarianceWithRepulsionClassSelector()\n\n super().__init__(\n src=src,\n classifier=classifier,\n class_selector=class_selector,\n averager=averager,\n )\n","repo_name":"ComputationalCryoEM/ASPIRE-Python","sub_path":"src/aspire/denoising/class_avg.py","file_name":"class_avg.py","file_ext":"py","file_size_in_byte":18803,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"77"} +{"seq_id":"42294511624","text":"# separates the input list into parts\ndef merge_sort(items):\n #base case\n if len(items) <= 1:\n return items\n #list passed in will be split into half and assigned to left and right split\n middle_index = len(items) // 2\n left_split = items[:middle_index]\n right_split = items[middle_index:]\n #recursive function\n left_sorted = merge_sort(left_split)\n right_sorted = merge_sort(right_split)\n\n return merge(left_sorted, right_sorted)\n\n#helper function which joins the data up.\ndef merge(left, right):\n\n result = []\n # While loop which runs until there is a left and a right\n while(left and right):\n if left[0] < right[0]:\n result.append(left[0])# SInce we are choosing the smaller of the two\n left.pop(0)# We added the 1st elem so we need to remove it\n elif left[0] > right[0]:\n result.append(right[0])\n right.pop(0)\n #after while loop we depleated on eof out inputs, now add in the rest of the value to finish off the merge\n if left:\n result += left\n if right:\n result += right\n #returning the sorted list\n return result\n\n#TESTING-------\nunordered_list1 = [356, 746, 264, 569]\norderded_list1 = merge_sort(unordered_list1)\nprint(\"Undordered list 1:\\n\" + str( unordered_list1))\nprint(\"Ordered list 1:\\n\" + str(orderded_list1))\n\nunordered_list2 = [787, 677, 391, 318, 543, 717, 180, 113, 795, 19, 202, 534, 201, 370, 276, 975, 403, 624, 770, 595, 571, 268, 373]\nordered_list2 = merge_sort(unordered_list2)\nprint(\"Undordered list 2:\\n\" + str(unordered_list2))\nprint(\"Ordered list 2:\\n\" + str(ordered_list2))\n\nunordered_list3 = [860, 380, 151, 585, 743, 542, 147, 820, 439, 865, 924, 387]\nordered_list3 = merge_sort(unordered_list3)\nprint(\"Undordered list 3:\\n\" + str(unordered_list3))\nprint(\"Ordered list 3:\\n\" + str(ordered_list3))\n#------------\n","repo_name":"AndreiR01/Sorting-Algorithms","sub_path":"Merge Sort.py","file_name":"Merge Sort.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"27882796272","text":"import tweepy, json, requests\n\nBEARER_TOKEN=\"AAAAAAAAAAAAAAAAAAAAAP4hYwEAAAAArxtwzeiOgyvK9uAveTAZTgXas9A%3DWZEpItVlzdwTxC6CvfgIwsNmeW8xVA7sOJ9pyUPtVHbODwc8Ql\"\nACCESS_TOKEN=\"1488797460470272000-5H19MGvoWlSmMkmbs3ykxCa4tDu779\"\nACCESS_TOKEN_SECRET=\"z1aECz7pMRR2Wv6U8gv0IyUHxv0Dmg77vuHdfObxIvmgV\"\nCONSUMER_KEY=\"18k1Ep9RDUGyvbnrVseExDXQa\"\nCONSUMER_SECRET=\"JArpYJcFAJDe1Oos7Tus1kNRQFrzVsHSD2hvJBopV0dmtkFfVj\"\n\nauth = tweepy.AppAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\n# auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)\n\nauth = tweepy.OAuth1UserHandler(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)\napi = tweepy.API(auth)\n\nclient = tweepy.Client(bearer_token=BEARER_TOKEN,\n consumer_key=CONSUMER_KEY,\n consumer_secret=CONSUMER_SECRET,\n access_token=ACCESS_TOKEN,\n access_token_secret=ACCESS_TOKEN_SECRET,\n return_type=requests.Response,\n wait_on_rate_limit=True)\n\ntweets = client.search_recent_tweets(query=\"test lang:en\")","repo_name":"ianwle/backend","sub_path":"project/extractors/extractor_twitter.py","file_name":"extractor_twitter.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"37703827515","text":"import cv2\nfrom scipy.spatial import distance as dist\nimport numpy as np\nfrom collections import defaultdict\n\n\ndef order_points(pts):\n # sort the points based on their x-coordinates\n xSorted = pts[np.argsort(pts[:, 0]), :]\n\n # grab the left-most and right-most points from the sorted\n # x-roodinate points\n leftMost = xSorted[:2, :]\n rightMost = xSorted[2:, :]\n\n # now, sort the left-most coordinates according to their\n # y-coordinates so we can grab the top-left and bottom-left\n # points, respectively\n leftMost = leftMost[np.argsort(leftMost[:, 1]), :]\n (tl, bl) = leftMost\n\n # now that we have the top-left coordinate, use it as an\n # anchor to calculate the Euclidean distance between the\n # top-left and right-most points; by the Pythagorean\n # theorem, the point with the largest distance will be\n # our bottom-right point\n D = dist.cdist(tl[np.newaxis], rightMost, \"euclidean\")[0]\n (br, tr) = rightMost[np.argsort(D)[::-1], :]\n\n # return the coordinates in top-left, top-right,\n # bottom-right, and bottom-left order\n return np.array([tl, tr, br, bl], dtype=\"float32\")\n\n\ndef four_point_transform(image, pts):\n # obtain a consistent order of the points and unpack them\n # individually\n rect = order_points(pts)\n (tl, tr, br, bl) = rect\n\n # compute the width of the new image, which will be the\n # maximum distance between bottom-right and bottom-left\n # x-coordiates or the top-right and top-left x-coordinates\n widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))\n widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))\n maxWidth = max(int(widthA), int(widthB))\n\n # compute the height of the new image, which will be the\n # maximum distance between the top-right and bottom-right\n # y-coordinates or the top-left and bottom-left y-coordinates\n heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))\n heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))\n maxHeight = max(int(heightA), int(heightB))\n\n # now that we have the dimensions of the new image, construct\n # the set of destination points to obtain a \"birds eye view\",\n # (i.e. top-down view) of the image, again specifying points\n # in the top-left, top-right, bottom-right, and bottom-left\n # order\n dst = np.array([\n [0, 0],\n [maxWidth - 1, 0],\n [maxWidth - 1, maxHeight - 1],\n [0, maxHeight - 1]], dtype=\"float32\")\n\n # compute the perspective transform matrix and then apply it\n M = cv2.getPerspectiveTransform(rect, dst)\n warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))\n\n # return the warped image\n return warped\n\n\ndef get_contour_precedence(contour, cols):\n tolerance_factor = 10\n origin = cv2.boundingRect(contour)\n return ((origin[1] // tolerance_factor) * tolerance_factor) * cols + origin[0]\n\n\ndef get_4_corner(pts):\n top_left = list()\n top_right = list()\n bot_right = list()\n bot_left = list()\n for p in pts:\n rect = order_points(p)\n (tl, tr, br, bl) = rect\n top_left.append(tl.tolist())\n top_right.append(tr.tolist())\n bot_right.append(br.tolist())\n bot_left.append(bl.tolist())\n top_left = sorted(top_left, key=lambda x: (x[0], x[1]))\n top_right = sorted(top_right, key=lambda x: (x[0], x[1]))\n bot_left = sorted(bot_left, key=lambda x: (x[0], x[1]))\n bot_right = sorted(bot_right, key=lambda x: (x[0], x[1]))\n return [top_left[0], top_right[2], bot_right[3], bot_left[1]]\n\n\ndef draw_rectangle(img, pts_1, pst_2, h, w):\n x = pts_1.tolist()[0]\n cv2.rectangle(img, (x[0][0], x[0][1]), (x[0][0] + w, x[0][1] + h), 3)\n crop_img = img[x[0][1]: x[0][1] + h,x[0][0]: x[0][0] +w]\n return crop_img\n\n\ndef split_boxs(img):\n rows = np.hsplit(img, 5)\n cv2.imshow(\"Split\", rows[0])\n cv2.imshow(\"Split 2\", rows[1])\n\n\ndef get_circles(mssv, img):\n img_cnt, cnt, hier = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n for c in cnt:\n are = cv2.contourArea(c)\n if are > 10:\n cv2.drawContours(mssv, c, -1, (255, 0, 255), 1)\n peri = cv2.arcLength(c, True)\n approx = cv2.approxPolyDP(c, 0.02*peri, True)\n objCor = len(approx)\n x, y, w, h = cv2.boundingRect(approx)\n if objCor > 4: obj = 'Circle'\n cv2.rectangle(mssv, (x, y), (x+w, y+h), (0,255,0), 2)\n\n\ndef image_resize(image, width=None, height=None, inter=cv2.INTER_AREA):\n # initialize the dimensions of the image to be resized and\n # grab the image size\n dim = None\n (h, w) = image.shape[:2]\n\n # if both the width and height are None, then return the\n # original image\n if width is None and height is None:\n return image\n\n # check to see if the width is None\n if width is None:\n # calculate the ratio of the height and construct the\n # dimensions\n r = height / float(h)\n dim = (int(w * r), height)\n\n # otherwise, the height is None\n else:\n # calculate the ratio of the width and construct the\n # dimensions\n r = width / float(w)\n dim = (width, int(h * r))\n\n # resize the image\n resized = cv2.resize(image, dim, interpolation=inter)\n\n # return the resized image\n return resized\n\n\n# Load image, grayscale, Gaussian blur, Otsu's threshold\nimage = cv2.imread(\"IMG_6011.JPG\")\nimage = image_resize(image, 800, 800)\n\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\nblur = cv2.GaussianBlur(gray, (7, 7), 0)\nthresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]\n\n# Find contours and sort for largest contour\ncnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\ncnts = cnts[0] if len(cnts) == 2 else cnts[1]\ncnts = sorted(cnts, key=cv2.contourArea, reverse=True)\ndisplayCnt = None\n\nfor c in cnts:\n peri = cv2.arcLength(c, True)\n approx = cv2.approxPolyDP(c, 0.02 * peri, True)\n if len(approx) == 4:\n displayCnt = approx\n break\n\n# Obtain birds' eye view of image\nwarped = four_point_transform(image, displayCnt.reshape(4, 2))\n\n# Get 4 big square\ngray = cv2.cvtColor(warped.copy(), cv2.COLOR_BGR2GRAY)\nret, thresh = cv2.threshold(gray, 60, 255, cv2.THRESH_BINARY_INV)\nimg, contour, hierrachy = cv2.findContours(thresh, 1, 2)\nblack_point = list()\nboundary = list()\nfor c, cnt in enumerate(contour):\n area = cv2.contourArea(cnt)\n if area > 200:\n cv2.drawContours(warped, cnt, -1, (255, 255, 0), 3)\n peri = cv2.arcLength(cnt, True)\n approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)\n black_point.append(approx.reshape(4, 2))\n objCor = len(approx)\n x, y, w, h = cv2.boundingRect(approx)\n boundary.append((x, y, w, h))\n cv2.rectangle(warped, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\na = get_4_corner(black_point)\na = np.array(a)\nsecond = four_point_transform(warped, a)\n\n# get small square\nmask = cv2.inRange(second, (0, 0, 0, 0), (180, 255, 70, 0))\n\n_, cont, hier = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n\nmini_square = list()\nmini_bouding = list()\nmini_cont = list()\nfor ca in cont:\n area = cv2.contourArea(ca)\n if 40 < area < 100:\n cv2.drawContours(second, ca, -1, (255, 0, 255), 1)\n peri = cv2.arcLength(ca, True)\n approx = cv2.approxPolyDP(ca, 0.02 * peri, True)\n mini_square.append(approx)\n mini_cont.append(ca)\n x, y, w, h = cv2.boundingRect(approx)\n mini_bouding.append((x, y, w, h))\n\ncv2.imshow('çont', second)\n\nmini_cont.sort(key=lambda x: get_contour_precedence(x, second.shape[1]))\n# for i in range(len(mini_cont)):\n# second = cv2.putText(second, str(i), cv2.boundingRect(mini_cont[i])[:2], cv2.FONT_ITALIC, 1, [125])\n\n\n\nnew_pos = dict()\ncols = defaultdict(list)\ny_values = list()\n\ny_value = None\ncol = 1\nfor ca in mini_cont:\n area = cv2.contourArea(ca)\n if 40 < area < 100:\n peri = cv2.arcLength(ca, True)\n approx = cv2.approxPolyDP(ca, 0.02 * peri, True)\n x, y, w, h = cv2.boundingRect(approx)\n new_pos[(x, y, w, h)] = ca\n if y_value is None:\n y_value = y\n cols[col].append((x, y, w, h))\n continue\n elif y_value - 2 < y < y_value + 2:\n cols[col].append((x, y, w, h))\n else:\n col += 1\n cols[col].append((x, y, w, h))\n y_value = y\n\nlist_of_contour = defaultdict(list)\nfor column in cols:\n for c in cols[column]:\n second = cv2.putText(second, str(column), cv2.boundingRect(new_pos.get(c))[:2], cv2.FONT_ITALIC, 1, [125])\n list_of_contour[column].append(new_pos.get(c))\n\n# draw rectangle\ncv2.imshow('second', second)\nblocks = list()\nmssv = None\nma_de = None\nfor key in list(list_of_contour):\n if key == 1:\n for idx, val in enumerate(list_of_contour.get(key)):\n if idx == 0:\n pst_2 = list_of_contour.get(2)[0]\n mssv = draw_rectangle(second, val, pst_2, 160, 100)\n if idx == 1:\n pst_2 = list_of_contour.get(2)[1]\n ma_de = draw_rectangle(second, val, pst_2, 160, 60)\n\n if key == 2:\n continue\n if key == 6:\n continue\n\n for idx, val in enumerate(list_of_contour.get(key)):\n # if idx == 0:\n pst_2 = list_of_contour.get(key)[0]\n block = draw_rectangle(second, val, pst_2, 160, 70)\n blocks.append(block)\n\nmssv = cv2.cvtColor(mssv, cv2.COLOR_BGR2GRAY)\nmssv_thresh = cv2.threshold(mssv, 150, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]\n\n# for idx, b in enumerate(blocks):\n# cv2.imshow(f'block: {idx}', b)\n# cv2.imwrite(f'block{idx}.jpg', b)\n# cv2.imshow('second', second)\n# cv2.imshow('mssv', mssv)\n# cv2.imwrite(f'mssv.jpg', mssv)\n# cv2.imshow('mssv', mssv_thresh)\n# cv2.imwrite(f'mssv_thresh.jpg', mssv_thresh)\n#\n# cv2.imshow('ma de', ma_de)\n# cv2.imwrite(f'ma_de.jpg', ma_de)\n#\n# cv2.imwrite('col_num.jpg', second)\n#\n# plt.show()\ncv2.imshow('one', warped)\ncv2.imshow('second', second)\n\ncv2.waitKey(0)\n\n# circles = cv2.HoughCircles(image=gray, method=cv2.HOUGH_GRADIENT, dp=7.1,\n# minDist=10, param1=200, param2=15,\n# minRadius=1, maxRadius=10)\n\n# circles = cv2.HoughCircles(image=gray, method=cv2.HOUGH_GRADIENT, dp=7.3,\n# minDist=10, param1=200, param2=40,\n# minRadius=1, maxRadius=10)\n","repo_name":"kakuke1594/kivi","sub_path":"day1_20_08.py","file_name":"day1_20_08.py","file_ext":"py","file_size_in_byte":10479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"5479693436","text":"import mysql.connector\nfrom tkinter import messagebox\ndef product_insert_record(product_id, product_name, brand, quantity,price_unit):\n mydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n passwd=\"\",\n database=\"crm_test\"\n )\n\n if mydb:\n print(\"Connection Successful.\")\n else:\n print(\"No Connection.\")\n #print(product_id,product_name,brand,quantity,price_unit)\n\n\n mycursor = mydb.cursor()\n\n sql = \"INSERT INTO `product_details`(`product_id`, `product_name`, `brand`, `quantity`, `price_unit`) \" \\\n \"VALUES ( %s,%s,%s,%s,%s)\"\n val = (product_id, product_name, brand, quantity, price_unit)\n\n mycursor.execute(sql, val)\n\n mydb.commit()\n x = mycursor.rowcount\n messagebox.showinfo(\"Product Record\", \"records are inserted.{}\".format(x))\n","repo_name":"SushantE/Custmore_Management_System","sub_path":"insert_product_db.py","file_name":"insert_product_db.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":"6360571603","text":"from django.urls import path\nfrom .views import CompanyStage2View, CompanyStage3View, UserRegisterView, CompanyStage1View, VerifyView\n\napp_name = 'users'\n\nurlpatterns = [\n path('register/user/', UserRegisterView.as_view(), name='user_register'),\n path('register/company1/', CompanyStage1View.as_view(), name='company_register'),\n path('register//company2/', CompanyStage2View.as_view(), name='company_register2'),\n path('register//company3/', CompanyStage3View.as_view(), name='company_register3'),\n path('verify/', VerifyView.as_view(), name='email-verify'),\n]","repo_name":"trojan782/Gigamoni","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"43816855142","text":"from collections import defaultdict, Counter\nclass Solution:\n \"\"\"\n Given an m x n grid of characters board and a string word, return true if word exists in the grid.\n The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. \n The same letter cell may not be used more than once.\n \"\"\"\n def exist(self, board: List[List[str]], word: str) -> bool:\n # Just to a brute force DFS approach to solve this. Will be O(n*m*4^n)\n ROWS, COLS = len(board), len(board[0])\n # We will keep track of the path we take in a set, so we don't revisit already traversed coordinates\n path = set()\n def dfs(r, c, i):\n # If we have found the word...\n if i == len(word):\n return True \n # If either r/c is out of bounds, if the board letter doesn't match our word, or if the current coordinate was already previously traversed...\n if (\n min(r, c) < 0 # out of bounds, where if either r or c is negative, return false\n or r >= ROWS or c >= COLS # Out of bounds for if they're higher\n or word[i] != board[r][c] # board letter != word letter\n or (r, c) in path # board square already in path\n ):\n return False \n \n # At this point, we have found a square that is eligible and matches the next letter of our word \n # Record it's position in the path \n path.add((r, c))\n # Recursively check right, left, up, and down respectively, and see if any of those yield a valid word. If any path is true, word exists. Else false. \n res = (\n dfs(r + 1, c, i + 1)\n or dfs(r - 1, c, i + 1)\n or dfs(r, c + 1, i + 1)\n or dfs(r, c - 1, i + 1)\n )\n # Disassemble path for recursive steps, so future recursions have the proper path\n path.remove((r, c))\n return res\n \n # This next step is a little optimization (feels kinda hacky imo). \n # In this algo, we essentially run DFS on each square, and compare against each letter. Now how can we find a answer quicker? \n # First, find the frequency of each letter. Then check the frequency of the first and last letter on the board. \n # If the first letter is more frequent, we can reverse our word, and then run the algo. \n # If the new word is now reversed, it starts with a less frequent character, meaning we can quickly reject most of the stuff we come across. \n # Since most of our path space will be rejected, the quicker we can burn through them and find a correct answer, the faster we will be\n # The path is preserved and nothing is essentially changed by reversing the word. \n \n # First, find frequency of each word, and store it as a dictionary in count\n # This is complicated, so I will explain each part. map works like map(function, iterable)\n # So map(Counter, board) creates a list of Counter objects to each element in board. These Counter objects behave like dictionaries\n # sum(map(Counter, board), Counter()) adds up all the counts in Counter objects across board,\n # the second Counter() provides an empty counter to start the sum. \n # Finally, in defaultdict, the int means we default to 0, and if you try to access a key that doesn't exist, it returns 0.\n \n count = defaultdict(int, sum(map(Counter, board), Counter()))\n # Check frequency of first and last word. If first letter is more frequent, reverse the word\n if count[word[0]] > count[word[-1]]:\n word = word[::-1]\n \n # Brute force across whole space\n for r in range(ROWS):\n for c in range(COLS):\n if dfs(r, c, 0):\n return True \n # If we checked everything, return False. \n return False","repo_name":"aroy105/LeetCode","sub_path":"Backtracking/79-word_search.py","file_name":"79-word_search.py","file_ext":"py","file_size_in_byte":4035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"16523848900","text":"#!/usr/bin/env python3\nimport csv\nimport urllib.request\nimport datetime\n\n\nimport json\nfrom dateutil import parser\n\ndef get_matches(competition_id):\n # my api token\n headers={'X-Auth-Token': 'eaa1239b82654c72bd9d2541b8a042fc'}\n\n req = urllib.request.Request('http://api.football-data.org/v2/competitions/' + competition_id + '/matches', headers=headers)\n r = urllib.request.urlopen(req).read()\n\n #parse json into an array of matches\n matches=json.loads(r.decode('utf-8'))\n return matches\n\n\ndef write_results(results):\n\n date_as_string = datetime.datetime.now().strftime('%Y%m%d%s')\n filename='bbc/bbc_results_1_' + date_as_string + '.csv'\n fix_file = open(filename, 'w')\n print ('writing to ', filename)\n wr = csv.writer(fix_file, dialect='excel')\n wr.writerow(['FixtureDate', 'League','Fix_or_result', 'HomeTeam', 'AwayTeam', 'HTG_or_time', 'ATG'])\n for resultdate in results:\n wr.writerows([resultdate])\n \n fix_file.close()\n\nall_fixtures=[]\n\nfor competition in ['2021', '2016'] :\n matches = get_matches(competition)\n for m in matches['matches']:\n matchtime = parser.parse(m['utcDate']).strftime(\"%H:%M\")\n matchdate = parser.parse(m['utcDate']).strftime(\"%Y-%m-%d\")\n if m['score']['fullTime']['homeTeam'] is not None:\n all_fixtures.append ([matchdate,matches['competition']['name'], '2', m['homeTeam']['name'], m['awayTeam']['name'], \n m['score']['fullTime']['homeTeam'], m['score']['fullTime']['awayTeam']])\n else:\n all_fixtures.append ([matchdate,matches['competition']['name'], '1', m['homeTeam']['name'], m['awayTeam']['name'], \n matchtime, 'N/A'])\n\n#send fixtures to csv file in the same format as v2 of the bbc scraper\nwrite_results(all_fixtures)","repo_name":"wormwood/football","sub_path":"ETL/football-data-api.py","file_name":"football-data-api.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"14525211224","text":"#\n# @lc app=leetcode id=54 lang=python3\n#\n# [54] Spiral Matrix\n#\n\n# @lc code=start\nclass Solution:\n def spiralOrder(self, matrix: List[List[int]]) -> List[int]:\n total = len(matrix)*len(matrix[0])\n i_up = 0\n i_down = len(matrix)\n j_left = 0\n j_right = len(matrix[0])\n ans = []\n while(total >= 1):\n for k in range(j_left,j_right):\n ans.append(matrix[i_up][k])\n \n total -= 1\n i_up += 1\n for k in range(i_up,i_down):\n ans.append(matrix[k][j_right-1])\n \n total -= 1\n j_right -= 1\n if not (j_left < j_right and i_up < i_down):\n break\n for k in range(j_right - 1,j_left-1,-1):\n ans.append(matrix[i_down - 1][k])\n \n total -= 1\n \n i_down -= 1\n for k in range(i_down - 1,i_up-1,-1):\n ans.append(matrix[k][j_left])\n \n total -= 1\n \n j_left += 1\n # break\n return ans\n# @lc code=end\n\n","repo_name":"AbhiPatel2105/problem_solving","sub_path":"leetcode/54.spiral-matrix.py","file_name":"54.spiral-matrix.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":"5622215015","text":"import csv\nimport sklearn.neural_network\nimport yaml\n\nimport base_algorithm\nimport dataset\n\nclass Neural_Network (base_algorithm.Base_Algorithm):\n def __init__ (self):\n print (\"I'm going to run neural network\")\n base_algorithm.Base_Algorithm.__init__ (self)\n\n def load_parameters (self, filename):\n with open (filename, \"r\") as fd:\n dictionary = yaml.load (fd)\n result = dictionary [\"neural_network\"]\n print (\"Parameters of the neural network: {0}\".format (result))\n return result\n\n def open_results_file (self):\n results_file = open (\"neural-network_results_{0}.csv\".format (self.suffix), \"w\")\n results_writer = csv.writer (results_file, delimiter = ',', quoting = csv.QUOTE_NONNUMERIC, quotechar = '\"')\n header_row = [\n \"time\",\n \"run\",\n \"activation\",\n 'solver',\n \"alpha\",\n 'early.activation',\n 'max.iterations'\n ] + [\n 'hidden.layer.{0:d}.size'.format (index + 1) for index in range (len (self.parameters [\"hidden_layers_size\"]))\n ] + [\n \"num.iterations\",\n \"all.score\",\n ] + [\"partial.score.{}\".format (index) for index in range (dataset.DataSet.CLASS_COUNTER)] + [\n \"random.chance.win\"\n ]\n results_writer.writerow (header_row)\n return results_file, results_writer\n\n def open_classifier_file (self):\n NN_file = open (\"neural-network_classifier_{0}.csv\".format (self.suffix), \"w\")\n NN_writer = csv.writer (NN_file, delimiter = ',', quoting = csv.QUOTE_NONNUMERIC, quotechar = '\"')\n return NN_file, NN_writer\n\n def open_output_file (self):\n filename = 'neural-network_output_{0}.csv'.format (self.suffix)\n output_file = open (filename, 'w')\n output_writer = csv.writer (output_file, delimiter = ',', quoting = csv.QUOTE_NONNUMERIC, quotechar = '\"')\n header_row = [\n 'predicted.class.{}'.format (index + 1)\n for index in range (dataset.DataSet.CLASS_COUNTER)\n ] + [\n 'real.class.{}'.format (index + 1)\n for index in range (dataset.DataSet.CLASS_COUNTER)\n ] + [\n 'run'\n ]\n output_writer.writerow (header_row)\n return output_file, output_writer\n\n def run (self, fraction_test, index_repeat):\n train, test = dataset.split_data_sets_train_test (self.data_sets, fraction_test, self.RNG)\n clf = sklearn.neural_network.MLPClassifier (\n activation = self.parameters [\"activation\"],\n solver = self.parameters [\"solver\"],\n alpha = self.parameters [\"alpha\"],\n hidden_layer_sizes = self.parameters [\"hidden_layers_size\"],\n random_state = self.RNG,\n max_iter = self.parameters [\"max_iterations\"],\n early_stopping = self.parameters [\"early_stopping\"]\n )\n current_time, score, hit = self.run_classifier (clf, train, test, index_repeat)\n self.write_neural_network_results (current_time, index_repeat, clf, score, hit)\n self.write_neural_network_sructure (current_time, index_repeat, clf)\n\n def write_neural_network_results (self, current_time, index_repeat, clf, score, hit):\n row = [\n current_time,\n index_repeat,\n self.parameters [\"activation\"],\n self.parameters [\"solver\"],\n self.parameters [\"alpha\"],\n self.parameters [\"early_stopping\"],\n self.parameters [\"max_iterations\"]\n ] + self.parameters [\"hidden_layers_size\"] + [\n clf.n_iter_,\n ] + score + [\n hit\n ]\n self.results_writer.writerow (row)\n\n def write_neural_network_sructure (self, current_time, index_repeat, clf):\n row = [current_time, index_repeat, clf.out_activation_, clf.n_layers_, clf.n_outputs_]\n for matrix in clf.coefs_:\n for cr in matrix:\n row.extend (cr)\n for r in clf.intercepts_:\n row.extend (r)\n self.classifier_writer.writerow (row)\n\nif __name__ == '__main__':\n Neural_Network ()\n","repo_name":"plsm/optigrape-cluster-classification","sub_path":"classifier/neural-network.py","file_name":"neural-network.py","file_ext":"py","file_size_in_byte":4176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"71688283768","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import log_loss\n\n\ntrain = pd.read_csv('train.csv')\ntest = pd.read_csv('test.csv')\n\n# grab data from training\ntrain['Title'] = train['Name'].str.split(',', expand=True)[1]\ntrain['Title'] = train['Title'].str.split('.', expand=True)[0]\nmean_age_train = train[['Title', 'Age']].groupby('Title').mean()\n\n\n# grab data from testing\ntest['Title'] = test['Name'].str.split(',', expand=True)[1]\ntest['Title'] = test['Title'].str.split('.', expand=True)[0]\nmean_age_test = test[['Title', 'Age']].groupby('Title').mean()\n\n\n# add missing age data on training data\nmapping_train = dict(zip(mean_age_train.index, mean_age_train['Age']))\nfor i in range(len(train['Age'].isnull())):\n if train['Age'].isnull()[i]:\n train.loc[i, 'Age'] = mapping_train.get(train['Title'][i])\n\n\n# add missing data on testing data\nmapping_test = dict(zip(mean_age_test.index, mean_age_test['Age']))\nfor i in range(len(test['Age'].isnull())):\n if test['Age'].isnull()[i]:\n test.loc[i, 'Age'] = mapping_test.get(test['Title'][i])\n\n\n# drop no need data\ntrain.drop('Name', inplace=True, axis=1)\ntrain.drop('Cabin', inplace=True, axis=1)\ntrain.drop('Ticket', inplace=True, axis=1)\n\ntest.drop(414, inplace=True, axis=0)\ntest.drop('Name', inplace=True, axis=1)\ntest.drop('Cabin', inplace=True, axis=1)\ntest.drop('Ticket', inplace=True, axis=1)\ntest = test.fillna(28)\n\n# print(test.isnull().sum())\n# encoding train data\nsexual = train.values[:, 3].reshape(-1, 1)\nembarked = train.values[:, 8].reshape(-1, 1)\ntitle = train.values[:, 9].reshape(-1, 1)\n\nsexual_test = test.values[:, 2].reshape(-1, 1)\nembarked_test = test.values[:, 7].reshape(-1, 1)\ntitle_test = test.values[:, 8].reshape(-1, 1)\n\n\nencode = OneHotEncoder()\nx = encode.fit_transform(sexual).toarray()\ny = encode.fit_transform(embarked).toarray()\nz = encode.fit_transform(title).toarray()\n\nx_t = encode.fit(sexual).transform(sexual_test).toarray()\ny_t = encode.fit(embarked).transform(embarked_test).toarray()\nz_t = encode.fit(title).transform(title_test).toarray()\n\n\nsexual = np.hstack([train.values[:, 1].reshape(-1, 1), train.values[:, 2].reshape(-1, 1),\n x, train.values[:, 4].reshape(-1,\n 1), train.values[:, 5].reshape(-1, 1),\n train.values[:, 6].reshape(-1,\n 1), train.values[:, 7].reshape(-1, 1),\n y, z])\n\nsexual_test = np.hstack([test.values[:, 1].reshape(-1, 1), x_t, test.values[:, 3].reshape(-1, 1), test.values[:,\n 4].reshape(-1, 1), test.values[:, 5].reshape(-1, 1), test.values[:, 6].reshape(-1, 1), y_t, z_t])\n\n\ntrain = pd.DataFrame(sexual)\ntest = pd.DataFrame(sexual_test)\ntrain = train.astype('float')\ntest = test.astype('float')\n\n# train\ndata = train.iloc[:, 1:29].values.reshape(-1, 28)\ntarget = train.iloc[:, 0].values.reshape(-1, 1)\n\ntrain_data, test_data, train_target, test_target\\\n = train_test_split(data, target, test_size=0.25, random_state=13)\n\nLR = LogisticRegression()\nLR.fit(train_data, train_target.flatten())\n\n# predict\ntrain_pre = LR.predict(train_data)\ntrain_pre = pd.DataFrame(train_pre)\ntest_pre = LR.predict(test_data)\n\nprint('model score')\nprint('the train data set score is :%d' % (LR.score(train_data, train_pre)))\nprint('train data set performance :%.3f' % (log_loss(train_target, train_pre)))\nprint('the test data set score is :%d' % (LR.score(test_data, test_pre)))\nprint('test data set performance :%.3f' % (log_loss(test_target, test_pre)))\n\n# use model to predict test.csv data\ndata_test = test.iloc[:, 0:28].values.reshape(-1, 28)\npredict_test_data = LR.predict(data_test)\n\n\n# check the correctness of test data\ngender_submission = pd.read_csv('gender_submission.csv')\ngender_submission.drop(414, inplace=True, axis=0)\ngender_submission.drop('PassengerId', inplace=True, axis=1)\ngender_submission = gender_submission.astype('float')\n\ngender_submission = gender_submission.iloc[:, 0].values.reshape(-1, 1)\nprint('test data to gender submission performance :%.3f' %\n (log_loss(gender_submission, predict_test_data)))\n","repo_name":"austin20010423/kaggle-weather_and_titanic-model","sub_path":"titanic_training.py","file_name":"titanic_training.py","file_ext":"py","file_size_in_byte":4296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"36036630010","text":"import os\nimport itertools\nfrom datetime import datetime, timedelta\nimport tarfile\n\n\"\"\"\nCollections of file accessing functions and classes. Note for the\nspecial timestamp handling.\n\"\"\"\n\ndef getTarDatetime(filename):\n return datetime.strptime(filename[:20], \"%Y-%m-%d__%H-%M-%S\")\n\ndef getTarTimespan(fullpath):\n x = tarfile.open(fullpath)\n members = x.getnames()\n return (getImgDatetime(members[0]), getImgDatetime(members[-1]))\n \ndef getImgDatetime(filename):\n return datetime.strptime(filename[:20], \"%Y-%m-%d__%H:%M:%S\")\n \ndef getImages(tarfilename, open=True):\n untarred = tarfile.open(tarfilename)\n tarinfo = untarred.next()\n while not tarinfo == None:\n if open:\n fileobj = untarred.extractfile(tarinfo)\n yield (getImgDatetime(tarinfo.name), fileobj)\n else:\n yield getImgDatetime(tarinfo.name)\n tarinfo = untarred.next()\n\nclass ImageDirectory:\n \"\"\"\n Allows random access of the image frames in the tar files in the\n directory specified by path.\n \n - Supports a single session.\n \"\"\"\n def __init__(self, path):\n self.path = path\n self.files = []\n self.param = {}\n self.refresh()\n self.time_pointer = None\n \n def refresh(self):\n self.files = sorted(x for x in os.listdir(self.path) if x.endswith(\".tar\"))\n self.timespans = [getTarTimespan(os.path.join(self.path, x)) for x in self.files]\n if not self.files:\n raise Exception(\"%s does not contain any tar files\")\n\n self.param['start_time'] = self.timespans[0][0]\n self.param['end_time'] = self.timespans[-1][1]\n self.param['step'] = timedelta(seconds=10)\n \n def durationInSeconds(self):\n return self.duration * 24 *3600 + self.seconds\n \n def setParameter(self, attr, val, restart=False):\n self.param[attr] = val\n \n def jumpTo(self, t): \n for (i, (start, end)) in enumerate(self.timespans):\n if t <= end:\n self.file_pointer = i\n self.img_iterator = getImages(os.path.join(self.path, self.files[i]), open=True)\n return start\n \n def getNextFrameInStream(self, next_time):\n for (t, fileobj) in self.img_iterator:\n if next_time <= t:\n return t, len(fileobj.read())\n raise Exception(\"next_time %s is not in stream\" % str(next_time))\n \n def next(self):\n \n if self.time_pointer == None:\n self.time_pointer = self.param['start_time']\n self.jumpTo(self.time_pointer)\n \n next_time = self.time_pointer + self.param['step']\n timespan = self.timespans[self.file_pointer]\n if next_time >= self.param['end_time']:\n self.time_pointer = self.param['start_time']\n next_time = self.jumpTo(self.time_pointer)\n elif not (timespan[0] <= next_time <= timespan[1]):\n next_time = self.jumpTo(next_time)\n\n frame = self.getNextFrameInStream(next_time)\n self.time_pointer = frame[0]\n return frame\n \n def __iter__(self):\n return self\n","repo_name":"kenpu/stream-rt","sub_path":"sandbox/streamrt/fileaccessor.py","file_name":"fileaccessor.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"9647587439","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.contrib import admin\n\n# Register your models here.\n\nfrom app.models import SystemIP\n\nclass SystemAdmin(admin.ModelAdmin):\n list_display = [\"__unicode__\",\"nombre\",\"nombrecell\",\"ipv4\"]\n search_fields = [\"nombre\", \"ipv4\"]\n list_editable = [\"ipv4\"]\n class Meta:\n model = SystemIP\n\nadmin.site.register(SystemIP, SystemAdmin)\n","repo_name":"DerianD/iphs","sub_path":"app/admin.py","file_name":"admin.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":"31098521692","text":"import os\nimport re\n\nimport TestSCons\n\ntest = TestSCons.TestSCons()\n\nSConstruct_path = test.workpath('SConstruct')\n\ntest.Qt_dummy_installation()\n\ntest.Qt_create_SConstruct(SConstruct_path)\n\ntest.write('aaa.cpp', r\"\"\"\n#include \"my_qobject.h\"\nvoid aaa(void) Q_OBJECT\n\"\"\")\n\ntest.write('SConscript', r\"\"\"\nImport(\"env\")\nimport os\nenv.StaticLibrary('aaa.cpp')\n\"\"\")\n\ntest.run(stderr=None)\n\nmatch12 = r\"\"\"\nscons: warning: Generated moc file 'aaa.moc' is not included by 'aaa.cpp'\n\"\"\" + TestSCons.file_expr\n\nif not re.search(match12, test.stderr()):\n print(\"Did not find expected regular expression in stderr:\")\n print(test.stderr())\n test.fail_test()\n\nos.environ['QTDIR'] = test.QT\n\ntest.run(arguments='-n noqtdir=1')\n\n# We'd like to eliminate $QTDIR from the environment as follows:\n# del os.environ['QTDIR']\n# But unfortunately, in at least some versions of Python, the Environment\n# class doesn't implement a __delitem__() method to make the library\n# call to actually remove the deleted variable from the *external*\n# environment, so it only gets removed from the Python dictionary.\n# Consequently, we need to just wipe out its value as follows>\nos.environ['QTDIR'] = ''\ntest.run(stderr=None, arguments='-n noqtdir=1')\n\nmoc = test.where_is('moc')\nif moc:\n import os.path\n qtdir = os.path.dirname(os.path.dirname(moc))\n qtdir = qtdir.replace('\\\\', '\\\\\\\\' )\n\n expect = r\"\"\"\nscons: warning: Could not detect qt3, using moc executable as a hint \\(QT3DIR=%s\\)\nFile \"%s\", line \\d+, in (\\?|)\n\"\"\" % (qtdir, re.escape(SConstruct_path))\nelse:\n\n expect = r\"\"\"\nscons: warning: Could not detect qt3, using empty QT3DIR\nFile \"%s\", line \\d+, in (\\?|)\n\"\"\" % re.escape(SConstruct_path)\n\ntest.fail_test(not test.match_re(test.stderr(), expect))\n\ntest.pass_test()\n\n# Local Variables:\n# tab-width:4\n# indent-tabs-mode:nil\n# End:\n# vim: set expandtab tabstop=4 shiftwidth=4:\n","repo_name":"SCons/scons","sub_path":"test/QT/qt3/qt_warnings.py","file_name":"qt_warnings.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","stars":1830,"dataset":"github-code","pt":"77"} +{"seq_id":"877219160","text":"import json\nimport requests\nfrom classes.abstract_clases.abstract_classes import AbstractSuperJobAPI\nfrom secret_key import SECRET_KEY\n\n\nclass SuperJobAPI(AbstractSuperJobAPI):\n \"\"\" Class defines to get json file with searched vacancies in SupperJob\"\"\"\n def __init__(self, name):\n self.name = name\n\n def get_page_superjob(self, page=None, url_params=None):\n\n # Defining entering data\n headers = {'X-Api-App-Id': SECRET_KEY}\n url_params = {'page': page,\n 'count': 100,\n 'keyword': self.name}\n\n # pulling info from Superjob and transform it in json format\n request = requests.get('https://api.superjob.ru/2.0/vacancies',\n params=url_params,\n headers=headers)\n\n data = request.content.decode()\n\n json_object = json.loads(data)\n\n return json_object\n","repo_name":"MihailBashkatov/Course_work_4","sub_path":"classes/superjob/class_superjob_api.py","file_name":"class_superjob_api.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"38058234949","text":"# Import necessary libraries\r\nimport pandas as pd\r\nfrom sklearn.tree import DecisionTreeClassifier, export_text\r\n\r\n# Create a DataFrame with the provided data\r\ndata = pd.read_csv(r\"C:\\Users\\Srinivasa Rao\\Downloads\\employee(id3).csv\")\r\n\r\ndf = pd.DataFrame(data)\r\n\r\n# Convert categorical variables to numerical using one-hot encoding\r\nX = pd.get_dummies(df[['age', 'salary']])\r\ny = df['performance']\r\n\r\n# Create and fit the Decision Tree model\r\nmodel = DecisionTreeClassifier(criterion='entropy') # ID3 uses entropy as the criterion\r\nmodel.fit(X, y)\r\n\r\n# Display the decision tree rules\r\ntree_rules = export_text(model, feature_names=list(X.columns))\r\nprint(tree_rules)","repo_name":"PavaniChitturi04/DataMining","sub_path":"id3(1).py","file_name":"id3(1).py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"3554646092","text":"from django.urls import path\n\n\nfrom .views import category, post, tag\n\napp_name = 'blog'\n\n\nurlpatterns = [\n path('categories/', category.index, name='category-index'),\n path('posts/', post.DetailView.as_view(), name='post-detail'),\n path('tags/', tag.index, name='tag-index'),\n]\n","repo_name":"nasAtchia/clean-blog-django","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"72799227449","text":"'''\nLeetCode #567. Permutation in String\n\nGiven a string and a pattern, find out if the string contains any permutation of the pattern.\n\nWe use a HashMap to remember the frequencies of all characters in the given pattern\n\n* Our goal will be to match all the characters from this HashMap with a sliding window in the given string *\n\n1. Create a HashMap to calculate the frequencies of all characters in the pattern.\n2. Iterate through the string, adding one character at a time in the sliding window.\n3. If the character being added matches a character in the HashMap, decrement its frequency in the map.\n - If the character frequency becomes zero, we got a complete match.\n4. If at any time, the number of characters matched is equal to the number of distinct characters in the pattern (i.e., total characters in the HashMap),\n - we have gotten our required permutation and can RETURN TRUE.\n5. If the window size is greater than the length of the pattern, shrink the window to make it equal to the pattern's size.\n - At the same time, if the character going out was part of the pattern, put it back in the frequency HashMap.\n'''\ndef find_permutation(str1, pattern):\n windowStart = 0\n \n # we use matched to determine if we've reached the correct number of characters in pattern in the input string\n matched = 0\n \n char_frequency = {}\n \n # create a frequency map of the pattern string\n for char in pattern:\n if char not in char_frequency:\n char_frequency[char] = 0\n char_frequency[char] += 1\n \n # we begin iterating through the inputString\n for windowEnd in range(len(str1)):\n rightChar = str1[windowEnd]\n \n # if the current character we're on is in the frequency map of pattern\n if rightChar in char_frequency:\n # we decrement the frequency\n char_frequency[rightChar] -= 1\n \n # if the frequency reaches 0 - that means we've matched the number of this specific character in pattern\n # therefore we can increment matched\n if char_frequency[rightChar] == 0:\n matched += 1\n \n # if matched == len(char_frequency) - meaning all the characters and # of characters from pattern are IN the input string\n # we can return True\n if matched == len(char_frequency):\n return True\n\n # IF the window size is greater than the length of the pattern\n # we have to strink the window till the window matches the pattern's length\n if windowEnd >= len(pattern) - 1:\n # identify the character at the start of the window (left side)\n leftChar = str1[windowStart]\n \n # increment our starting pointer\n windowStart += 1\n \n # we ONLY care about the characters in pattern\n # so if leftChar is in the pattern frequency map\n if leftChar in char_frequency:\n # and the frequency of that character is 0\n if char_frequency[leftChar] == 0:\n # we need to reduce matched b/c our string no longer has all the characters in patter\n matched -= 1\n \n # if we iterated through the entire string and never found a permutation of patter in the inputString\n # we can return False\n return False\n\ndef main():\n print('Permutation exist: ' + str(find_permutation(\"oidbcaf\", \"abc\"))) # True\n print('Permutation exist: ' + str(find_permutation(\"odicf\", \"dc\"))) # False\n print('Permutation exist: ' + str(find_permutation(\"bcdxabcdy\", \"bcdyabcdx\"))) # True\n print('Permutation exist: ' + str(find_permutation(\"aaacb\", \"abc\"))) # True\n\n\nmain()\n","repo_name":"LennyGonz/LeetCode-Questions","sub_path":"Patterns/Sliding_Window/python/9_permutation_in_a_string.py","file_name":"9_permutation_in_a_string.py","file_ext":"py","file_size_in_byte":3511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"72064920890","text":"import numpy as np\n\nfrom pywatts.modules.generation.anomaly_generation_module import AnomalyGeneration\n\n\nclass PowerAnomalyGeneration(AnomalyGeneration):\n \"\"\"\n Module to define specific anomalies to be inserted into a power time series.\n \"\"\"\n\n def _anomaly_type1(self, target, indices, lengths, k=0):\n \"\"\"\n Anomaly type 1 that drops the power time series values to a negative value potentially followed by zero values\n before adding the missed sum of power to the end of the anomaly.\n \"\"\"\n for idx, length in zip(indices, lengths):\n if length <= 2:\n raise Exception(\"Type 1 power anomalies must be longer than 2.\")\n else:\n # WARNING: This could lead to a overflow quite fast?\n energy_at_start = target[:idx].sum() + k\n energy_at_end = target[:idx + length].sum() + k\n target[idx] = -1 * energy_at_start # replace first by negative peak\n target[idx + 1:idx + length - 1] = 0 # set other values to zero\n target[idx + length - 1] = energy_at_end # replace last with sum of missing values + k\n return target\n\n def _anomaly_type2(self, target, indices, lengths, softstart=True):\n \"\"\"\n Anomaly type 2 that drops the power time series values to potentially zero and adds the missed sum of power to\n the end of the anomaly.\n \"\"\"\n for idx, length in zip(indices, lengths):\n if length <= 1:\n raise Exception(\"Type 2 power anomalies must be longer than 1.\")\n else:\n if softstart:\n r = np.random.rand()\n energy_consumed = target[idx:idx + length].sum()\n target[idx] = r * target[idx]\n target[idx + 1:idx + length - 1] = 0\n target[idx + length - 1] = energy_consumed - target[idx]\n else:\n energy_consumed = target[idx:idx + length].sum()\n target[idx:idx + length - 1] = 0\n target[idx + length - 1] = energy_consumed\n return target\n\n def _anomaly_type3(self, target, indices, lengths,\n is_extreme=False, range_r=(0.01, 3.99), k=0):\n \"\"\"\n Anomaly type 3 that creates a negatives peak in the power time series.\n \"\"\"\n for idx, length in zip(indices, lengths):\n if length > 1:\n raise Exception(\"Type 3 power anomalies can't be longer than 1.\")\n else:\n if is_extreme:\n energy_consumed = target[:idx].sum()\n target[idx] = -1 * energy_consumed - k\n else:\n r = np.random.uniform(*range_r)\n target[idx] = -1 * r * target[idx - 1]\n return target\n\n def _anomaly_type4(self, target, indices, lengths, range_r=(0.01, 3.99)):\n \"\"\"\n Anomaly type 4 that creates a positive peak in the power time series.\n \"\"\"\n for idx, length in zip(indices, lengths):\n if length > 1:\n raise Exception(\"Type 4 power anomalies can't be longer than 1.\")\n else:\n r = np.random.uniform(*range_r)\n target[idx] = r * target[idx - 1]\n return target\n","repo_name":"KIT-IAI/pyWATTS","sub_path":"pywatts/modules/generation/power_anomaly_generation_module.py","file_name":"power_anomaly_generation_module.py","file_ext":"py","file_size_in_byte":3351,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"77"} +{"seq_id":"14452952331","text":"#!/usr/bin/env python\nimport argparse\nimport hashlib\nimport json\nimport math\nimport os\nimport pickle\nimport shutil\nfrom collections import OrderedDict\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\n\nimport load_policy\nfrom network_utils import ACTIVATION_FUNCTIONS, OPTIMIZERS, build_model\n\n\ndef build_behavior_cloning_subparser(subparser):\n DESCRIPTION = \"Train model using behavior cloning\"\n p = subparser.add_parser(\"behavior_cloning\", description=DESCRIPTION, help=DESCRIPTION)\n p.add_argument('dataset', type=str)\n\n\ndef build_dagger_subparser(subparser):\n DESCRIPTION = \"Train model using DAGGER\"\n p = subparser.add_parser(\"dagger\", description=DESCRIPTION, help=DESCRIPTION)\n p.add_argument('dataset', type=str)\n p.add_argument('expert', type=str, help=\"Reference expert if using DAGGER (.pkl)\")\n p.add_argument('envname', type=str)\n p.add_argument('--num-rollouts', type=int, default=20)\n p.add_argument('--max-timesteps', type=int)\n p.add_argument('--n-loops', type=int, default=5)\n\n\ndef build_argparser():\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--hidden-sizes', type=int, nargs='+', default=64)\n parser.add_argument('--max-epochs', type=int, default=30)\n parser.add_argument('--batch-size', type=int, default=64)\n parser.add_argument('--lr', type=float, default=0.001)\n parser.add_argument('--reg', type=float, default=0.01, help=\"Regularization strength on weights\")\n parser.add_argument('--seed', type=float, default=1234)\n parser.add_argument('-a', '--activation', type=str, choices=ACTIVATION_FUNCTIONS, help=\"Activation function to use. [{}]\".format(\", \".join(\n ACTIVATION_FUNCTIONS.keys())))\n parser.add_argument('-o', '--optimizer', type=str, choices=OPTIMIZERS, help=\"Optimizer to use. [{}]\".format(\", \".join(OPTIMIZERS.keys())))\n parser.add_argument('--name', type=str)\n parser.add_argument('-v', '--view', action='store_true')\n parser.add_argument('-f', '--force', action='store_true')\n\n subparser = parser.add_subparsers(title=\"Training method\", dest=\"method\")\n subparser.required = True\n build_behavior_cloning_subparser(subparser)\n build_dagger_subparser(subparser)\n\n return parser\n\n\ndef run_dagger(sess, env, expert_fn, inputs, outputs, num_rollouts, max_steps):\n model_observations = []\n expert_actions = []\n for n in range(num_rollouts):\n print('iter', n)\n obs = env.reset()\n done = False\n steps = 0\n while not done:\n model_action = np.squeeze(sess.run(outputs, feed_dict={inputs: obs[None, :]}))\n expert_action = expert_fn(obs[None, :])\n model_observations.append(obs)\n expert_actions.append(expert_action)\n obs, _, done, _ = env.step(model_action)\n steps += 1\n if steps % 100 == 0: print(\"%i/%i\" % (steps, max_steps))\n if steps >= max_steps:\n break\n return model_observations, np.squeeze(expert_actions)\n\n\ndef main():\n parser = build_argparser()\n args = parser.parse_args()\n print(args)\n print(\"Using tensorflow v.{}\".format(tf.VERSION))\n\n hyperparams = OrderedDict(sorted(vars(args).items()))\n del hyperparams['view']\n del hyperparams['force']\n del hyperparams['name']\n\n experiment_name = args.name\n if experiment_name is None:\n experiment_name = hashlib.sha256(repr(hyperparams).encode()).hexdigest()\n experiment_path = os.path.join(\".\", \"experiments\", experiment_name)\n if os.path.isdir(experiment_path):\n if not args.force:\n print(\"Experiment directory already exists. Use --force to overwrite. {}\".format(experiment_path))\n return\n else:\n shutil.rmtree(experiment_path)\n os.makedirs(experiment_path)\n with open(os.path.join(experiment_path, \"hyperparams.json\"), 'w') as json_file:\n json.dump(hyperparams, json_file)\n\n tf.set_random_seed(hyperparams['seed'])\n np.random.seed(hyperparams['seed'])\n\n expert_data = pickle.load(open(hyperparams['dataset'], 'rb'))\n observations = expert_data['observations']\n actions = np.squeeze(expert_data['actions'])\n\n print(\"Original dataset size : {}\".format(observations.shape[0]))\n\n input_size = observations.shape[1]\n output_size = actions.shape[1]\n print(\"Input size: {}; Output size: {}\".format(input_size, output_size))\n\n expert_fn = None\n n_loops = 1\n if hyperparams['method'] == \"dagger\":\n expert_fn = load_policy.load_policy(hyperparams[\"expert\"])\n import gym\n env = gym.make(args.envname)\n max_steps = hyperparams['max_timesteps'] or env.spec.timestep_limit\n num_rollouts = hyperparams['num_rollouts']\n n_loops = hyperparams['n_loops']\n\n inputs = tf.placeholder(tf.float32, [None, input_size], name=\"inputs\")\n targets = tf.placeholder(tf.float32, [None, output_size], name=\"targets\")\n\n # Build FFNN\n outputs = build_model(inputs, input_size, args.hidden_sizes, output_size, hyperparams[\"activation\"], reg=hyperparams['reg'])\n outputs = tf.identity(outputs, name=\"output\")\n\n # MSE\n mse = tf.reduce_mean(tf.reduce_sum(tf.square(outputs - targets), axis=1), name=\"loss\")\n # Regularization\n reg_variables = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)\n reg_loss = tf.reduce_sum(reg_variables)\n # Total loss\n loss = mse + reg_loss\n\n optimizer = OPTIMIZERS[hyperparams['optimizer']]\n train_step = optimizer(args.lr).minimize(loss)\n\n with tf.Session() as sess:\n\n saver = tf.train.Saver()\n\n tf.global_variables_initializer().run()\n\n losses = []\n\n for i in range(n_loops):\n for epoch in range(hyperparams['max_epochs']):\n n_data = observations.shape[0]\n epoch_ids = np.arange(n_data)\n np.random.shuffle(epoch_ids)\n batches_per_epoch = int(math.ceil(n_data / min((hyperparams['batch_size'], n_data))))\n\n epoch_losses = []\n for batch_idx in range(batches_per_epoch):\n batch_ids = epoch_ids[batch_idx*hyperparams['batch_size']:(batch_idx+1)*hyperparams['batch_size']]\n train_loss, _ = sess.run([loss, train_step], feed_dict={inputs: observations[batch_ids], targets: actions[batch_ids]})\n epoch_losses.append(train_loss)\n\n train_loss = np.mean(epoch_losses)\n losses.append(train_loss)\n print(\"Epoch: {} - train loss: {}\".format(epoch, train_loss))\n saver.save(sess, os.path.join(experiment_path, \"model.ckpt\"))\n\n if hyperparams['method'] == \"dagger\":\n print(\"Iteration {} finished. Collecting more data using DAGGER.\".format(i))\n model_observations, expert_actions = run_dagger(sess, env, expert_fn, inputs, outputs, num_rollouts, max_steps)\n observations = np.concatenate((observations, model_observations))\n actions = np.concatenate((actions, expert_actions))\n\n print(\"Training finished!\")\n\n with open(os.path.join(experiment_path, \"losses.pkl\"), 'wb') as losses_file:\n pickle.dump(losses, losses_file)\n\n if args.view:\n fig = plt.figure()\n method_name = hyperparams['method']\n dataset_name = os.path.split(hyperparams['dataset'])[1]\n fig.suptitle(\"{} using dataset: {}\".format(method_name, dataset_name))\n\n ax = fig.add_subplot('111')\n ax.set_xlabel('Iterations')\n ax.set_ylabel('MSE')\n\n ax.plot(np.arange(len(losses)), losses, label=\"train loss\")\n\n plt.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ppoulin91/cs294","sub_path":"hw1/train_nn.py","file_name":"train_nn.py","file_ext":"py","file_size_in_byte":7722,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"9660131026","text":"# template: https://alysivji.github.io/reactive-dashboards-with-dash.html\n# standard library\nimport os\n\n# dash libs\nimport dash\nfrom dash.dependencies import Input, Output\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly.graph_objs as go\n\n# additional libs\nimport pandas as pd\nfrom sqlalchemy import create_engine\nfrom datetime import datetime, timedelta\n\n# sqlalchemy funcs\nfrom models import Station, Device, Turnstile, data_frame\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.types import INTEGER\nfrom sqlalchemy import func\n\n# set params\n# connString = os.environ['DB_URI']\nconnString = 'sqlite:///mta\\\\mta_sample1718.db'\nconn = create_engine(connString, echo=True)\n\ndef make_session(engine=conn):\n Session = sessionmaker(bind=conn)\n session = Session()\n return session\n\n###########################\n# Data Manipulation / Model\n###########################\ndef to_ts(date_str):\n '''convert string date ie. 2018-01-01 00:00:00 to unix timestamp\n WARNING: may need to consider TIMEZONE, db used NY timezone'''\n date_dt = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')\n return int((date_dt - datetime(1970, 1, 1)) / timedelta(seconds=1))\n\ndef get_station_summary(start_date='2018-01-01 00:00:00', end_date='2018-02-01 00:00:00'):\n start_ts = to_ts(start_date)\n end_ts = to_ts(end_date)\n session = make_session(conn)\n query = session.query(Station.name, func.sum(Turnstile.entry), func.sum(Turnstile.exit)).\\\n filter(Turnstile.device_id==Device.id).filter(Device.station_id==Station.id).\\\n filter(Turnstile.timestamp>=start_ts, Turnstile.timestamp<=end_ts).\\\n filter(Station.name.isnot(None)).\\\n group_by(Station.name).all()\n df = pd.DataFrame(query, columns=['station', 'entry', 'exit'])\n df['volume'] = df['entry'] + df['exit']\n df = df.sort_values('volume', ascending=False)\n #print(df.head())\n return df\n\ndf = get_station_summary()\n\n#########################\n# Dashboard Layout / View\n# Wire-frame components in this section, data will be populated via Model and Controller\n#########################\n\ndef generate_table(dataframe, max_rows=10):\n '''Given dataframe, return template generated using Dash components'''\n return html.Table(\n # Header\n [html.Tr([html.Th(col) for col in dataframe.columns])] +\n\n # Body\n [html.Tr([\n html.Td(dataframe.iloc[i][col]) for col in dataframe.columns\n ]) for i in range(min(len(dataframe), max_rows))]\n )\n\n\n# Set up Dashboard and create layout\napp = dash.Dash()\napp.css.append_css({\n \"external_url\": \"https://codepen.io/chriddyp/pen/bWLwgP.css\"\n})\n\ncolors = {\n 'background': '#111111',\n 'text': '#7FDBFF'\n}\n\napp.layout = html.Div(style={'backgroundColor': colors['background']}, children=[\n html.H1(\n children='Station Summary',\n style={\n 'textAlign': 'center',\n 'color': colors['text']\n }\n ),\n \n html.Div(children='Dash: A web application framework for Python.', style={\n 'textAlign': 'center',\n 'color': colors['text']\n }),\n\n dcc.Graph(\n id='top-station-entry-vs-exit',\n figure={\n 'data': [\n go.Scatter(\n x=df[df['station'] == i]['entry'],\n y=df[df['station'] == i]['exit'],\n mode='markers',\n opacity=0.7,\n marker={\n 'size': 15,\n 'line': {'width': 0.5, 'color': 'white'}\n },\n name=i\n ) for i in df.station.unique()\n ],\n 'layout': go.Layout(\n xaxis={'title': 'Entry'},\n yaxis={'title': 'Exit'},\n margin={'l': 40, 'b': 40, 't': 10, 'r': 10},\n legend={'x': 0, 'y': 1},\n hovermode='closest'\n )\n } \n ),\n\n generate_table(df)\n\n])\n\n\n#############################################\n# Interaction Between Components / Controller\n#############################################\n\n\n\n\n# start Flask server\nif __name__ == '__main__':\n app.run_server(\n debug=True,\n #host='0.0.0.0',\n port=8050\n )","repo_name":"Ritaotao/djmtattl","sub_path":"dhmtattl/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"17933217912","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom django.conf.urls import url\nfrom . import views\nfrom django.views.decorators.csrf import csrf_exempt\n\nurlpatterns = [\n\turl('^$', views.index, name='index'),\n\turl('^cluster/$',views.cluster, name='cluster'),\n\turl('^login/$',views.login, name='login'),\n\turl('^getshapefiles/$',views.getshapefiles, name='getshapefiles'),\n\turl('^shapefilename/$',views.shapefilename, name='shapefilename'),\n\turl('^uploadzipshapefile/$',views.uploadzipshapefile, name='uploadzipshapefile'),\n\turl('^webgl/$',views.webgl, name='webgl')\n]\n","repo_name":"navagis-sid/copy","sub_path":"navagiscore/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"21607940762","text":"#tenha uma tupla totalmente preenchida com uma contagem por extenso \n# de 0 até 20.\n# seu programa deverá ler um numero pelo teclado entre 0 e 20 e mostra-lo por extenso.\n\ncontagem_usuario = int(input(\"Digite um número de 0 até 20: \"))\ncontagem = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze', 'treze', 'quatorze', 'quinze', 'dezesseis', 'dezessete', 'dezoito', 'dezenove', 'vinte')\n\nfor i in contagem: \n if contagem_usuario >= 0 and contagem_usuario <= 20:\n numero = contagem[contagem_usuario]\n else:\n contagem_usuario = int(input(\"Número inválido. Digite um número de 0 até 20: \"))\n\nprint(f\"Você digitou o número {contagem_usuario}, esse número por extenso é assim: {numero}\")","repo_name":"turquetti/learningPython","sub_path":"Curso_em_Video/Mundo 3/desafio072.py","file_name":"desafio072.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"26534683947","text":"#!/usr/bin/env python\n# Modify version...\nimport datetime\nimport os\nimport re\nimport subprocess\nimport sys\n\nPROJECT_DIRECTORY = os.path.join(os.path.dirname(__file__), \"..\")\n\n\ndef main(argv):\n source_dir = argv[1]\n version = argv[2]\n history_path = os.path.join(PROJECT_DIRECTORY, \"HISTORY.rst\")\n with open(history_path) as fh:\n history = fh.read()\n today = datetime.datetime.today()\n today_str = today.strftime(\"%Y-%m-%d\")\n history = history.replace(\".dev0\", \" (%s)\" % today_str)\n with open(history_path, \"w\") as fh:\n fh.write(history)\n\n planemo_mod_path = os.path.join(PROJECT_DIRECTORY, source_dir, \"__init__.py\")\n with open(planemo_mod_path) as fh:\n mod = fh.read()\n mod = re.sub(r\"__version__ = '[\\d\\.]*\\.dev0'\", \"__version__ = '%s'\" % version, mod)\n with open(planemo_mod_path, \"w\") as fh:\n mod = fh.write(mod)\n shell([\"git\", \"commit\", \"-m\", \"Version %s\" % version, \"HISTORY.rst\", \"%s/__init__.py\" % source_dir])\n shell([\"git\", \"tag\", version])\n\n\ndef shell(cmds, **kwds):\n p = subprocess.Popen(cmds, **kwds)\n return p.wait()\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","repo_name":"galaxyproject/planemo","sub_path":"scripts/commit_version.py","file_name":"commit_version.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","stars":83,"dataset":"github-code","pt":"77"} +{"seq_id":"20117697019","text":"# _*_ encoding:utf-8 _*_\n__author__ = 'lizhe'\n__time__ = '2018/05/06 10:22'\nimport requests\ndata = {\n \"wd\":\"中国\"\n}\nheader ={\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.90 Safari/537.36 2345Explorer/9.3.2.17331',\n}\n# 使用request库传参时不需要使用urlencode函数去编码成byte类型数据,库自动去编码。get方法参数是params=,post方法是data=\nresponse = requests.get(\"http://www.baidu.com/s\",params=data,headers = header)\n\n# print(response.text)#.text输出str类型数据,可能自动匹配的解码方式不对,造成乱码\n# print(response.content.decode(\"utf-8\"))#response.content输出byte类型,硬盘与网络上传输的数据都是byte类型,可以自己定义解码方式\n# print(response.url)\n# print(response.status_code)\n#\nwith open(\"baidu.html\",'w',encoding='utf-8') as file:\n file.write(response.content.decode(\"utf-8\"))\n\n","repo_name":"lixiaozhe666/pythonCourseDemo","sub_path":"demoRequestGet.py","file_name":"demoRequestGet.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"24079418727","text":"import speech_recognition as sr\r\nimport pyttsx3\r\nimport datetime\r\nimport webbrowser\r\nfrom tkinter import *\r\nfrom PIL import Image,ImageTk\r\nimport requests\r\nimport json\r\nfrom os import startfile\r\nimport speedtest\r\n\r\n\r\ndef speak(audio):\r\n engine=pyttsx3.init()\r\n voices=engine.getProperty('voices')\r\n engine.setProperty('voice','voices[0].id')\r\n engine.say(audio)\r\n engine.runAndWait()\r\ndef Greet():\r\n hour=datetime.datetime.now().hour\r\n if hour>=0 and hour<12:\r\n speak(\"Hello,Good Morning\")\r\n print(\"Hello,Good Morning\")\r\n elif hour>=12 and hour<18:\r\n speak(\"Hello,Good Afternoon\")\r\n print(\"Hello,Good Afternoon\")\r\n else:\r\n speak(\"Hello,Good Evening\")\r\n print(\"Hello,Good Evening\")\r\n speak(\"I am vision. How can I help you\")\r\n print(\"I am vision. How can I help you\")\r\ndef invokeVision():\r\n Query = recognise().lower()\r\n if \"hello vision\" in Query:\r\n Greet()\r\n return True\r\ndef getQuery():\r\n while(True):\r\n Query=recognise().lower()\r\n if \"hello vision\" in Query:\r\n Greet()\r\n elif \"open google\" in Query:\r\n speak(\"What do you want to search from google?\")\r\n google_search = recognise().lower()\r\n speak(\"searching\"+ google_search)\r\n webbrowser.open(\"https://www.google.com/search?q=\" + google_search)\r\n continue\r\n elif \"open youtube\" in Query:\r\n speak(\"WHat do you want to search from youtube\")\r\n yt_search = recognise().lower()\r\n speak(\"seearching\"+yt_search)\r\n webbrowser.open(\"https://www.youtube.com/results?search_query=\" + yt_search)\r\n continue\r\n elif \"show me the latest news around the world\" in Query:\r\n speak(\"fetching latest news\")\r\n webbrowser.open(\"https://www.thehindu.com/\")\r\n speak(\"Here are some headlines from the hindu\")\r\n continue\r\n elif \"weather\" in Query:\r\n apiKey = \"get your api by signing up\"\r\n url = \"http://api.openweathermap.org/data/2.5/weather?\"\r\n speak(\"Enter your city name : \")\r\n cityName = input(\"Enter your city name : \")\r\n fullUrl = url + \"appid=\" + apiKey + \"&q=\" + cityName\r\n output = requests.get(fullUrl)\r\n temp=output.json()\r\n print(temp)\r\n if temp[\"cod\"] != \"404\":\r\n x = temp['main']\r\n x1 = temp['coord']\r\n speak(\"Here is the weather forecast of \")\r\n speak(cityName)\r\n print(\"Weather forecast in \", cityName, \":\")\r\n print(\"Current temperature :\", int((x['temp'] - 273.15)), '\\N{DEGREE SIGN}'\"C\")\r\n print(\"Humidity :\", x['humidity'], \"%\")\r\n print(\"Pressure :\", x['pressure'], \"hPa\")\r\n print(\"Located at \", x1['lon'], \"longitude and \", x1['lat'], \"latitude\")\r\n continue\r\n elif \"what is the time now\" in Query:\r\n hour =datetime.datetime.now().hour\r\n speak(hour)\r\n speak(\"hours\")\r\n min=datetime.datetime.now().minute\r\n print(hour, \"Hrs\", min, \"minutes\")\r\n speak(min)\r\n speak(\"minutes\")\r\n continue\r\n elif \"tell me today's date\" in Query:\r\n date=datetime.date.today()\r\n speak(date)\r\n print(\"Today's date :\",date)\r\n continue\r\n elif \"from playlist\" in Query:\r\n speak(\"Which song do you want to hear?\")\r\n gaana_search = recognise().lower()\r\n speak(\"Playing \" + gaana_search)\r\n webbrowser.open(\"https://gaana.com/search/\" + gaana_search)\r\n continue\r\n elif \"play movie\" in Query:\r\n speak(\"Which movie do you want to play?\")\r\n movie = recognise().lower()\r\n speak(\"Playing \" + movie)\r\n startfile(\"movie path (sample path - E:\\\\movies\\\\\" + movie + \".mkv\")\r\n continue\r\n elif \"from map\" in Query:\r\n speak(\"Which place do you want to search from maps?\")\r\n map_search = recognise().lower()\r\n webbrowser.open(\"https://www.google.com/maps/place/\" + map_search)\r\n continue\r\n elif \"speed test\" in Query:\r\n speak(\"Checking internet speed\")\r\n speed = speedtest.Speedtest()\r\n download = speed.download()\r\n upload = speed.upload()\r\n print(\"Download speed : \", download/1000000,\"Mbps\")\r\n print(\"Upload speed : \", upload/1000000,\"Mbps\")\r\n continue\r\n elif \"from windows\" in Query:\r\n speak(\"Which app do you want to open?\")\r\n app_name = recognise().lower()\r\n startfile(\"enter your desktop path (sample path - c:\\\\users\\\\\\\\desktop)\" + app_name)\r\n elif \"tata\" in Query:\r\n speak(\"Bye. See you soon again\")\r\n print(\"Bye. See you soon again\")\r\n exit()\r\ndef recognise():\r\n s=sr.Recognizer()\r\n with sr.Microphone() as input:\r\n print(\"Listening.......\")\r\n audio = s.listen(input)\r\n try:\r\n print(\"Recognising....\")\r\n query=s.recognize_google(audio,language='en-in')\r\n except Exception :\r\n print(\"Can you say that again \")\r\n return \"none\"\r\n return query\r\nif __name__ =='__main__':\r\n while(True):\r\n if(invokeVision()):\r\n break;\r\n getQuery()\r\n","repo_name":"Naveen-Kumar-AA/Virtual-Assisstant-Vision-","sub_path":"Virtual assistant.py","file_name":"Virtual assistant.py","file_ext":"py","file_size_in_byte":5493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"46619256906","text":"'''\nhttps://leetcode.com/problems/bus-routes/submissions/\n'''\n\n\nclass Solution(object):\n def numBusesToDestination(self, routes, source, target):\n \"\"\"\n :type routes: List[List[int]]\n :type source: int\n :type target: int\n :rtype: int\n \"\"\"\n to_routes = collections.defaultdict(set)\n for idx, route in enumerate(routes):\n for j in route:\n to_routes[j].add(idx)\n bfs = [(source, 0)]\n seen = set([source])\n for stop, bus in bfs:\n if stop == target:\n return bus\n for i in to_routes[stop]:\n for location in routes[i]:\n if location not in seen:\n bfs.append((location, bus+1))\n seen.add(location)\n routes[i] = []\n return -1\n\n\n\n\n\n\n'''\nSuccess\nDetails \nRuntime: 404 ms, faster than 65.75% of Python online submissions for Bus Routes.\nMemory Usage: 51.3 MB, less than 100.00% of Python online submissions for Bus Routes.\n\n'''","repo_name":"dongbo910220/leetcode_","sub_path":"Graph/815. Bus Routes Hard.py","file_name":"815. Bus Routes Hard.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"33024365320","text":"#!/home/epereira/anaconda3/bin/python\n\n###############################################################################\n### 1. Set env\n###############################################################################\n\nimport argparse\nfrom Bio import SeqIO\nimport pysam\n\n###############################################################################\n### 2. Parse input data and optional arguments\n###############################################################################\n\nparser = argparse.ArgumentParser(prog='get_abund.py', \\\n description='Estimate BGC coverage')\n\nparser.add_argument(\"--input_gbk\", help=\"Input gbk file\")\nparser.add_argument(\"--input_bam\", help=\"Input bam file\")\nparser.add_argument(\"--sample_name\", help=\"Sample name\")\nparser.add_argument(\"--output_tsv\", help=\"Output tsv file\")\n\nargs = parser.parse_args()\ninput_gbk = args.input_gbk\ninput_bam = args.input_bam\nsample_name = args.sample_name\noutput_tsv = args.output_tsv\n\n###############################################################################\n### 3. Define GBK perser function\n###############################################################################\n\ndef get_features(record, feature_name, qualifier_name):\n for feature in record.features:\n if feature.type == feature_name:\n return feature.qualifiers[qualifier_name][0]\n\ndef get_feature_location(record, feature_name):\n for feature in record.features:\n if feature.type == feature_name:\n return [int(feature.location.start), int(feature.location.end)]\n\ndef gbk_parser(input_gbk):\n\n acc2x = dict() \n with open(input_gbk, \"r\") as gbk_handle:\n for record in SeqIO.parse(gbk_handle, \"genbank\"):\n acc = record.annotations['accessions'][0]\n bgc_class = get_features(record,\"cand_cluster\", \"product\")\n contg_edge = get_features(record,\"cand_cluster\", \"contig_edge\") \n location = get_feature_location(record,\"cand_cluster\")\n acc2x[acc] = {\"acc\": acc, \"bgc_class\": bgc_class, \"contg_edge\": contg_edge, \"start\":location[0], \"end\":location[1]}\n \n return(acc2x)\n\n###############################################################################\n### 4. Compute coverage function\n###############################################################################\n\ndef custom_coverage(input_bam_handle, gbk_parser_out):\n\n coverage_dict = dict()\n seq_names = list(gbk_parser_out.keys())\n for i in seq_names:\n input_bam_cov = input_bam_handle.count_coverage(gbk_parser_out[i][\"acc\"], \\\n gbk_parser_out[i][\"start\"], \\\n gbk_parser_out[i][\"end\"],\n quality_threshold = 0)\n n = 0\n for j in range (4):\n n += len([x for x in input_bam_cov[j] if x != 0])\n \n coverage_dict[i] = n/(gbk_parser_out[i][\"end\"] - gbk_parser_out[i][\"start\"]) \n return(coverage_dict)\n\n###############################################################################\n### 5. Perse GBK\n###############################################################################\n\ngbk_parser_out = gbk_parser(input_gbk)\n \n###############################################################################\n### 6. Compute coverage\n###############################################################################\n\ninput_bam_handle = pysam.AlignmentFile(input_bam, \"rb\")\ncoverage_out = custom_coverage(input_bam_handle, gbk_parser_out)\ninput_bam_handle.close()\n\n###############################################################################\n### 7. Format output\n###############################################################################\n\noutput = dict()\nfor i in gbk_parser_out.keys():\n gbk_parser_out[i][\"coverage\"] = coverage_out[i]\n gbk_parser_out[i][\"sample\"] = sample_name\n output[i] = list(gbk_parser_out[i].values())\n\n###############################################################################\n### 5. Compute coverage\n###############################################################################\n\nwith open(output_tsv, 'w') as f:\n [f.write('{0}\\n'.format(\"\\t\".join(map(str,value)))) for value in output.values()]\n\n\n\n","repo_name":"pereiramemo/bgc_annot","sub_path":"src/get_cov.py","file_name":"get_cov.py","file_ext":"py","file_size_in_byte":4163,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"32284808999","text":"\"\"\"\n @author Vortexx2\n Problem 1382 - Balance a BST\n\n Runtime - 851 ms\n Memory Usage - 20.5 MB\n\"\"\"\nfrom typing import Optional\nfrom math import floor\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 Solution:\n def balanceBST(self, root: TreeNode) -> TreeNode:\n if not root:\n return None\n\n self.inorder = []\n self.inorderTraversal(root)\n\n return self.constructBalancedBST(0, len(self.inorder))\n\n def inorderTraversal(self, root: Optional[TreeNode]) -> None:\n\n if not root:\n return\n\n self.inorderTraversal(root.left)\n self.inorder.append(root.val)\n self.inorderTraversal(root.right)\n\n def constructBalancedBST(self, start: int, end: int) -> Optional[TreeNode]:\n\n if start == end:\n return None\n\n mid = floor((start + end) / 2)\n\n root = TreeNode(self.inorder[mid])\n root.left = self.constructBalancedBST(start, mid)\n root.right = self.constructBalancedBST(mid + 1, end)\n\n return root\n","repo_name":"Vortexx2/DSA-questions","sub_path":"leetcode/medium/1382-balance-bst/arr.py","file_name":"arr.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"12030400273","text":"'''\r\nCreated on 20. 4. 2015\r\n\r\n@author: Kapsak\r\n'''\r\n\r\nfrom ylpa import \\\r\n Plate, Node, PlateSegment, PlateLoadUniform, \\\r\n ParametricStudy, YieldLine, Parameter, \\\r\n ParamNode, ParamPlate, YLPATreeView, \\\r\n Reinforcement\r\n\r\nb = 2.5\r\na = 2.\r\nreinf = 0.01\r\n\r\nn1 = Node(x=0., y=0., w=0.)\r\nn2 = Node(x=2 * b, y=0., w=0.)\r\nn3 = Node(x=2 * b, y=2 * a, w=0.)\r\nn4 = Node(x=0., y=2 * a, w=0.)\r\n\r\nn5 = Node(x=0.5 * b, y=a, w=1.)\r\nn6 = Node(x=1.5 * b)\r\n\r\nsg1 = PlateSegment(node_nos=[1, 2, 6, 5])\r\nsg2 = PlateSegment(node_nos=[2, 3, 6])\r\nsg3 = PlateSegment(node_nos=[3, 4, 5, 6])\r\nsg4 = PlateSegment(node_nos=[4, 1, 5])\r\n\r\nyl = [YieldLine(1, 5), YieldLine(4, 5), YieldLine(6, 5), YieldLine(2, 6), YieldLine(3, 6),\r\n YieldLine(1, 2), YieldLine(2, 3), YieldLine(3, 4)]\r\n\r\nreinforcement = [Reinforcement(p1=reinf, p2=reinf, p1u=reinf, p2u=reinf,\r\n d1_1=0.04, d1_2=0.03, d1_1u=0.04, d1_2u=0.03, node_name='reinforcement')]\r\n\r\nplate = Plate(nodes=[n1, n2, n3, n4, n5, n6],\r\n segments=[sg1, sg2, sg3, sg4],\r\n yield_lines=yl,\r\n plastic_moment_def_type=\"ortho_reinf_dep\",\r\n load=[PlateLoadUniform()],\r\n reinforcement=reinforcement,\r\n p1=0.01,\r\n p2=0.01,\r\n p2u=0.01,\r\n h=0.15,\r\n d1_1=0.04,\r\n d1_2=0.030,\r\n d1_1u=0.04,\r\n d1_2u=0.030,)\r\n\r\npstudy = ParametricStudy(plate=plate,\r\n optimization_constrain_value=0.02,\r\n node_params=[\r\n Parameter(base_value=0.2 * b, minimum=0.01, maximum=b - 0.01),\r\n Parameter(base_value=a, minimum=0.01, maximum=2 * a - 0.01),\r\n Parameter(base_value=b + 0.8 * b, minimum=b + 0.01, maximum=2 * b - 0.01),\r\n ],\r\n plate_params=[\r\n Parameter(base_value=0.005, minimum=0.0, maximum=0.02),\r\n Parameter(base_value=0.005, minimum=0.0, maximum=0.02),\r\n Parameter(base_value=0.005, minimum=0.0, maximum=0.02),\r\n Parameter(base_value=0.005, minimum=0.0, maximum=0.02),\r\n ],\r\n param_nodes=[ParamNode(node_no=5, trait_name=\"x\", param_no=1, multiplier=1., base_value=0.),\r\n ParamNode(node_no=5, trait_name=\"y\", param_no=2, multiplier=1., base_value=0.),\r\n ParamNode(node_no=6, trait_name=\"x\", param_no=3, multiplier=1., base_value=0.)],\r\n param_plate=[ParamPlate(trait_name=\"p1\", param_no=1, multiplier=1, base_value=0., reinf_layout_name='reinforcement'),\r\n ParamPlate(trait_name=\"p2\", param_no=2, multiplier=1, base_value=0., reinf_layout_name='reinforcement'),\r\n ParamPlate(trait_name=\"p1u\", param_no=3, multiplier=1, base_value=0., reinf_layout_name='reinforcement'),\r\n ParamPlate(trait_name=\"p2u\", param_no=4, multiplier=1, base_value=0., reinf_layout_name='reinforcement'),\r\n ]\r\n )\r\n\r\nview = YLPATreeView(root=pstudy)\r\nview.configure_traits()\r\n","repo_name":"Vancikv/YLPA","sub_path":"ylpa/examples/ex14_constrained_optimization.py","file_name":"ex14_constrained_optimization.py","file_ext":"py","file_size_in_byte":3451,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"18316529456","text":"#!/usr/bin/python3.5\n\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.webdriver.support.select import Select\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom threading import Thread\nimport os\nimport re\nimport socket\nimport requests\nimport queue\nimport time\nimport sys\nimport argparse\nimport datetime\nfrom datetime import timedelta, date\n\n\ndef searchDate(daten, pattern):\n \n #main page\n urlBegin = \"http://clerkrecorder.co.santa-cruz.ca.us/\"\n phanthonPath = \"/usr/bin/phantomjs\"\n daten2 = daten.replace('/', '.')\n filename1 = \"csv/\" + daten2 + \".csv\"\n \n txtDate = \"[\" + daten + \"]:\"\n print (txtDate, pattern, filename1)\n \n \n #field to save in cvs file\n docNumber = \"\" \n yyyy = daten[6:]\n mm = daten[:2]\n dd = daten[3:5]\n recordDate = yyyy + \"-\" + mm + \"-\" + dd \n docType = \"docType\"\n grantor = \"\"\n grantee = \"\"\n county = \"santa-cruz\"\n state = \"CA\"\n \n print (txtDate, \"open main page ..\")\n \n browser = webdriver.PhantomJS(phanthonPath)\n browser.get(urlBegin)\n #wait for load\n time.sleep(3) \n soup1 = BeautifulSoup(browser.page_source, \"html.parser\")\n #print (soup1)\n #click on ack, si esta iendo a la segunbda pagina des pues de dar click en ack\n browser.find_element_by_id('cph1_lnkAccept').click()\n time.sleep(3)\n #print (\"--------------------------------------------------------\")\n soup1 = BeautifulSoup(browser.page_source, \"html.parser\")\n #print (soup1)\n \n #Click on menu 'Real Estate\n element = browser.find_element_by_link_text('Real Estate').click()\n \n time.sleep(2)\n #ver si hizo el roll over \n \n soup1 = BeautifulSoup(browser.page_source, \"html.parser\")\n print (\"------------------------despues del roll over--------------------------------\")\n \n \n #click on Search state real index\n browser.find_element_by_id('x:273746300.10:adr:2.1').click()\n time.sleep(4)\n soup1 = BeautifulSoup(browser.page_source, \"html.parser\")\n print (soup1)\n browser.save_screenshot('screenie.png')\n #aqui me quede\n #quitar esto \n return \n \n \n \n #click on button to start\n browser.find_element_by_class_name(\"productLink\").click();\n \n #wait for load\n time.sleep(5)\n \n #select patter to search\n el = browser.find_element_by_id('vps:docType2')\n time.sleep(1)\n print (\"Set pattern and date to search in main page..\")\n for option in el.find_elements_by_tag_name('option'):\n \n if option.text == pattern: \n option.click()\n break\n \n \n time.sleep(1)\n \n #set date to text field\n datetxt = browser.find_element_by_id(\"vps:beginDate2\")\n datetxt.send_keys(daten) \n \n time.sleep(3)\n \n #click on button search\n print (\"Search records for date...\", daten)\n browser.find_element_by_xpath(\"//*[@src ='/pc/images/search_v3.gif']\").click()\n time.sleep(3)\n \n \n #open file to write results\n FILE1 = open(filename1, \"w\")\n cont = 0\n print (\"Proccess results...\")\n #proccess current page, and click next button until complete it\n while True :\n \n #get current page\n soup5 = BeautifulSoup(browser.page_source, \"html.parser\")\n \n #search tables with results\n tables = soup5.findAll( \"table\", {\"style\":\"margin:5px;\"} )\n \n \n contTbl =1\n #proccess each table\n for table in tables: \n contTbl = contTbl + 1\n #proccess each row\n found = 0\n for row in table.findAll(\"tr\"):\n \n #get all columns for this row\n cells = row.findAll(\"td\")\n \n #get text from column and clean it\n cells = [ele.text.strip() for ele in cells]\n \n \n #this is the row for document\n if re.search('Document Number' ,cells[0] ) and len (cells) == 1 : \n _, docNumber = cells[0].split(':')\n docNumber = docNumber.replace(' ', '') \n #this is the row for grantor and grante\n if row.findAll(\"td\", {\"class\" :\"grantor_grantee\"}) and len (cells) == 2 : \n # I found what I need \n found = 1\n brs = row.findAll(\"br\") \n listGrantor =[]\n listGrantee = []\n f1 = 0\n \n for br in brs:\n if str(br) == \"
\" :\n f1 = 1\n continue\n #remove invalid tags\n txt = str(br)\n txt = txt.replace(\"
\",\"\")\n txt = txt.replace(\"
\",\"\")\n #split it\n txt2 = txt.split (\"
\")\n if f1 == 0 : \n listGrantor= listGrantor + txt2\n else :\n listGrantee= listGrantee + txt2\n \n #remove spaces and empty strings\n listGrantor = [i.strip() for i in listGrantor]\n listGrantor = [j for j in listGrantor if len(j) > 1]\n listGrantee = [i.strip() for i in listGrantee]\n listGrantee = [j for j in listGrantee if len(j) > 1]\n \n #remove duplicate values\n listGrantor2 = set(listGrantor)\n listGrantee2 = set(listGrantee)\n #print (\"grantor\", listGrantor2)\n #print (\"grantee\", listGrantee2)\n \n #write on file if i found what i need in this table\n if found == 1 : \n #txt1 = docNumber + \",\"+ recordDate + \",\" + docType + \",\" + grantor + \",\"+ grantee + \",\"+county +\",\" + state + \"\\n\"\n txt1 = recordDate + \",\" + docNumber + \",\"+ docType + \",\"\n \n #grantor\n for grantor in listGrantor2:\n txt2 = \"Grantor\" + \",\" + grantor + \",Unavailable,\" + county +\",\" + state + \"\\n\"\n txt3 = txt1 + txt2\n FILE1.write(txt3)\n #grantee\n for grantee in listGrantee2:\n txt2 = \"Grantee\" + \",\" + grantee + \",Unavailable,\" + county +\",\" + state + \"\\n\"\n txt3 = txt1 + txt2\n FILE1.write(txt3)\n \n \n #break #to test first page\n #rewiew if next button exists on current page\n try :\n if browser.find_element_by_xpath(\"//*[@src ='/pc/images/nextPage_v3.gif']\") :\n cont = cont + 1\n except (NoSuchElementException): # if not , break the loop\n break\n \n #ckick on next button\n browser.find_element_by_xpath(\"//*[@src ='/pc/images/nextPage_v3.gif']\").click()\n time.sleep(2)\n print (\"Results from page:\", cont, \"completed\")\n \n \n #close driver and file \n browser.quit()\n FILE1.close()\n \n \n print (txtDate,\"completed\")\n\ndef validateDate( date_text, formatn ):\n try:\n datetime.datetime.strptime(date_text, formatn)\n except ValueError:\n print(\"Incorrect data format for date \",date_text,\"it should be \" ,formatn )\n return -1\n else :\n return 1\n \ndef main():\n \n #prepare arguments to read\n parser = argparse.ArgumentParser()\n parser.add_argument('-f', '--From', help='from date to search mmddyyyy', required=True)\n parser.add_argument('-t', '--To', help='To date to search mmddyyyy', required=True)\n parser.add_argument('-n', '--Number', help='n jobs to run simultaneous, e.i. 2 day n= 2, 3 days n = 3 ..', default = 1, type=int)\n args = parser.parse_args()\n \n maxTreats = args.Number \n #validate dates\n if validateDate(args.From, \"%m%d%Y\" ) == -1 :\n return\n \n if validateDate(args.To, \"%m%d%Y\" ) == -1 :\n return\n \n #create range of dates\n end_date = datetime.datetime.strptime(args.To, \"%m%d%Y\") \n start_date = datetime.datetime.strptime(args.From, \"%m%d%Y\") \n \n day_count = (end_date - start_date).days + 1\n #commands to run \n Q1 = queue.Queue()\n daterange = []\n pattern = \"DEED|DEED OF TRUST|RECONVEYANCE\"\n for single_date in (start_date + timedelta(n) for n in range(day_count)):\n \n datetxt = single_date.strftime(\"%m/%d/%Y\")\n \n #if csv file already exist for this day , omit it \n dattmp = datetxt.replace('/', '.')\n filename2 = dattmp + \".csv\" \n filename2 = \"csv/\"+filename2 \n if os.path.isfile(filename2):\n print (\"Report for day:\", datetxt, \" has been already ran, result is on file:\",filename2)\n continue \n daterange.append(datetxt) \n Q1.put(datetxt)\n \n \n #run n jobs at the same time\n while not Q1.empty() :\n \n treats = []\n for i in range (maxTreats) :\n \n if Q1.empty() :\n break\n \n daten = Q1.get()\n print (\"processing ... \", daten)\n t = Thread (target=searchDate, args=(daten, pattern) ) \n \n treats.append(t)\n t.start()\n \n for t1 in treats:\n t1.join() \n \n print (\"Process finished\")\n \n\nif __name__ == '__main__':\n \n main()\n","repo_name":"gurbanoma/webscrap","sub_path":"santa3.py","file_name":"santa3.py","file_ext":"py","file_size_in_byte":9975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"3104837629","text":"#coding=utf-8\nfrom uliweb import settings\nfrom weto.session import Session\nfrom uliweb.utils.common import import_attr, application_path\n\ndef get_session(key=None):\n options = dict(settings.get('SESSION_STORAGE', {}))\n options['data_dir'] = application_path(options['data_dir'])\n if 'url' not in options:\n _url = (settings.get_var('ORM/CONNECTION', '') or\n settings.get_var('ORM/CONNECTIONS', {}).get('default', {}).get('CONNECTION', ''))\n if _url:\n options['url'] = _url\n\n #process Session options\n session_storage_type = settings.SESSION.type\n Session.force = settings.SESSION.force\n\n serial_cls_path = settings.SESSION.serial_cls\n if serial_cls_path:\n serial_cls = import_attr(serial_cls_path)\n else:\n serial_cls = None\n\n session = Session(key, storage_type=session_storage_type,\n options=options, expiry_time=settings.SESSION.timeout, serial_cls=serial_cls)\n return session\n","repo_name":"zhangchunlin/shapps","sub_path":"shapps/auth/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"77"} +{"seq_id":"17913979026","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@author : 王晨懿\n@studentID : 1162100102\n@time : 2019/6/7\n\n法律文本预处理\n\n法律的结构:Law -> Chapter -> Section -> Entry\n个别法律没有Chapter和Section\n\"\"\"\nimport os\nimport re\nimport json\n\nimport config\n\nFLAG_Chapter = 1\nFLAG_Section = 2\nFLAG_Entry = 3\n\n\ndef index_all(lst, val):\n return [i for i, v in enumerate(lst) if v == val]\n\n\nclass Law(object):\n\n def __init__(self, name, lines, mark, load=None):\n if load is not None:\n \"\"\"json -> class\"\"\"\n self.name = load['name']\n self.has_chapter = load['has_chapter']\n self.chapters = [Chapter(None, None, load=x) for x in load['chapters']]\n return\n\n # 解析文本\n self.name = name\n self.chapters = []\n\n first_entry = mark.index(FLAG_Entry)\n first_chapter = first_entry - 1\n while first_chapter >= 0:\n if mark[first_chapter] == FLAG_Chapter:\n break\n first_chapter -= 1\n if first_chapter < 0:\n for i in range(first_entry, len(lines)):\n if mark[i] == FLAG_Chapter:\n first_chapter = i\n break\n if first_chapter < 0:\n self.has_chapter = False\n lines, mark = lines[first_entry:], mark[first_entry:]\n self.chapters = [Chapter(lines, mark)]\n else:\n self.has_chapter = True\n lines, mark = lines[first_chapter:], mark[first_chapter:]\n chapter_idx = index_all(mark, FLAG_Chapter)\n self.chapters = [Chapter(lines[a:b], mark[a:b]) for a, b in\n zip(chapter_idx, (chapter_idx + [len(lines)])[1:])]\n\n def dumps(self):\n \"\"\"class -> json\"\"\"\n this = dict()\n this['name'] = self.name\n this['has_chapter'] = self.has_chapter\n this['chapters'] = [cpt.dumps() for cpt in self.chapters]\n return this\n\n\nclass Chapter(object):\n def __init__(self, lines, mark, load=None):\n if load is not None:\n \"\"\"json -> class\"\"\"\n self.title = load['title']\n self.name = load['name']\n self.has_section = load['has_section']\n self.sections = [Section(None, None, load=x) for x in load['sections']]\n return\n\n # 解析文本\n self.title = lines[0] if mark[0] == FLAG_Chapter else ''\n self.name = ''\n if mark[0] == FLAG_Chapter:\n self.name = ''.join(re.split('\\s+', re.search('第[\\u4E00-\\u9FA5]+?章(.+)', lines[0]).group(1)))\n # self.name = list(segmentor.segment(self.name))\n lines, mark = lines[1:], mark[1:]\n\n section_idx = index_all(mark, FLAG_Section)\n self.has_section = False if len(section_idx) == 0 else True\n\n self.sections = [Section(lines[a:b], mark[a:b]) for a, b in\n zip(section_idx, (section_idx + [len(lines)])[1:])] if self.has_section else [\n Section(lines, mark)]\n\n def dumps(self):\n \"\"\"class -> json\"\"\"\n this = dict()\n this['title'] = self.title\n this['name'] = self.name\n this['has_section'] = self.has_section\n this['sections'] = [sc.dumps() for sc in self.sections]\n return this\n\n\nclass Section(object):\n def __init__(self, lines, mark, load=None):\n if load is not None:\n \"\"\"json -> class\"\"\"\n self.title = load['title']\n self.name = load['name']\n self.entrys = [Entry(None, None, load=x) for x in load['entrys']]\n return\n\n # 解析文本\n self.title = lines[0] if mark[0] == FLAG_Section else ''\n self.name = ''\n if mark[0] == FLAG_Section:\n self.name = ''.join(re.split('\\s+', re.search('第[\\u4E00-\\u9FA5]+?节(.+)', lines[0]).group(1)))\n # self.name = list(segmentor.segment(self.name))\n entry_idx = index_all(mark, FLAG_Entry)\n self.entrys = [Entry(lines[a:b], mark[a:b]) for a, b in zip(entry_idx, (entry_idx + [len(lines)])[1:])]\n\n def dumps(self):\n \"\"\"class -> json\"\"\"\n this = dict()\n this['title'] = self.title\n this['name'] = self.name\n this['entrys'] = [e.dumps() for e in self.entrys]\n return this\n\n\nclass Entry(object):\n def __init__(self, lines, mark, load=None):\n if load is not None:\n \"\"\"json -> class\"\"\"\n self.title = load['title']\n self.content = load['content']\n self.lines = load['lines']\n self.lst = load['lst']\n self.keywords = load['keywords']\n self.segment = []\n self.candidate = []\n self.tfidf, self.textrank = load['tfidf'], load['textrank']\n return\n\n ## 解析文本\n # 标题\n self.title = re.search('第[\\u4E00-\\u9FA5]+?条', lines[0]).group()\n # 文本\n self.content = re.search('第[\\u4E00-\\u9FA5]+?条(.+)', lines[0]).group(1).strip().replace(' ', '')\n self.lines = '\\n'.join(lines)\n # 分点的内容\n self.lst = []\n # 分词结果\n self.segment = []\n # 候选词\n self.candidate = []\n # tf-idf方法 textrank方法 提取的概括词\n self.tfidf, self.textrank = [], []\n for line in lines[1:]:\n m = re.match(r'(\\w+)(.+)', line)\n if m is None:\n self.content += line.replace(' ', '')\n else:\n self.lst.append(m.group(1).strip().replace(' ', ''))\n\n self.keywords = []\n\n def dumps(self):\n \"\"\"class -> json\"\"\"\n this = dict()\n this['title'] = self.title\n this['content'] = self.content\n this['lines'] = self.lines\n this['lst'] = self.lst\n this['keywords'] = self.keywords\n this['tfidf'], this['textrank'] = self.tfidf, self.textrank\n return this\n\n\ndef preprocessed():\n filepath_lst = os.listdir(config.text_path)\n law_lst = []\n for file in filepath_lst:\n with open(os.path.join(config.text_path, file), 'r', encoding='gbk', errors=\"ignore\")as f:\n lines = [line.strip().replace('\\u3000', ' ') for line in f.readlines()]\n lines = [line for line in lines if len(lines) > 0 and not line.startswith('北大法宝')]\n\n mark = [0] * len(lines)\n for i, line in enumerate(lines):\n if re.match('第[\\u4E00-\\u9FA5]+?章', line) is not None:\n mark[i] = FLAG_Chapter\n elif re.match('第[\\u4E00-\\u9FA5]+?节', line) is not None:\n mark[i] = FLAG_Section\n elif re.match('第[\\u4E00-\\u9FA5]+?条', line) is not None:\n mark[i] = FLAG_Entry\n\n name = os.path.splitext(file)[0]\n law = Law(name, lines, mark)\n law_lst.append(law)\n print(len(law_lst), 'files')\n return law_lst\n\n\ndef save_data(law_lst, path=config.save_path):\n for law in law_lst:\n with open(os.path.join(config.data_path, 'law_preprocessed', law.name + '.json'), 'w',\n encoding='utf-8')as json_f:\n json.dump(law.dumps(), json_f, indent=4, ensure_ascii=False)\n\n with open(path, 'w', encoding='utf-8')as f:\n for law in law_lst:\n json.dump(law.dumps(), f, ensure_ascii=False)\n f.write('\\n')\n\n\ndef load_data(path=config.save_path):\n with open(path, 'r', encoding='utf-8')as f:\n lines = f.readlines()\n trees = [Law(None, None, None, load=json.loads(x)) for x in lines]\n return trees\n\n\nif __name__ == '__main__':\n laws = preprocessed()\n save_data(laws)\n","repo_name":"CheneyW/LegalKnowledgeMap","sub_path":"preprocessed/parse_law_file.py","file_name":"parse_law_file.py","file_ext":"py","file_size_in_byte":7675,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"37076576008","text":"# GUI: graphic user interface\r\n# pip install pyqt5\r\n# 구글링 qt designer download - https://build-system.fman.io/qt-designer-download\r\n# 맥 : Designer 탭 - Preferences - Docked window - OK\r\n\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5 import uic\r\nimport sys\r\nimport urllib.request as req\r\nfrom bs4 import BeautifulSoup\r\nfrom PyQt5.QtGui import QPixmap # GUI 창에 이미지 띄우기\r\n\r\nui_file = \"./movie.ui\" # Qt Designer에서 미리 창 만들어서 ui파일 저장하기\r\nclass MainDialog(QDialog): # 창\r\n def __init__(self):\r\n QDialog.__init__(self, None)\r\n uic.loadUi(ui_file, self)\r\n\r\n self.button.clicked.connect(self.crawling_movie) # Qt Designer에서 objectName\r\n\r\n def crawling_movie(self):\r\n\r\n code = req.urlopen(\"http://www.cgv.co.kr/movies/\")\r\n soup = BeautifulSoup(code, \"html.parser\")\r\n title = soup.select(\"div.sect-movie-chart strong.title\")\r\n img = soup.select(\"span.thumb-image > img\")\r\n\r\n for i in range(len(title)):\r\n\r\n getattr(self, \"txt{}\".format(i+1)).setText(\"{}위 : {}\".format(i+1, title[i].string)) # getattr()은 변수라도 문자열 포맷팅을 쓸 수 있게 해주는 함수\r\n\r\n img_url = img[i].attrs[\"src\"]\r\n img_open = req.urlopen(img_url).read() # 특이한 점\r\n pixmap = QPixmap()\r\n pixmap.loadFromData(img_open)\r\n pixmap = pixmap.scaled(185, 260) # html문서 보면서 이미지 사이즈 조정\r\n getattr(self, \"img{}\".format(i+1)).setPixmap(pixmap)\r\n\r\n\r\nQApplication.setStyle(\"fusion\") # 오류방지\r\napp = QApplication(sys.argv)\r\nmain_dialog = MainDialog()\r\nmain_dialog.show()\r\nsys.exit(app.exec_())\r\n","repo_name":"mjkimcs/portfolio","sub_path":"GUI/13c_PyQt5_무비차트.py","file_name":"13c_PyQt5_무비차트.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"35886393512","text":"import csv\nimport json\nfrom functools import reduce\n\nnodes = []\nlinks = []\narea = []\n\nrun_function = lambda x, y: x if y in x else x + [y]\n\n# with open('../gisbok_lo.csv', errors='ignore') as f:\n# Reader = csv.DictReader(f)\n# for row in Reader:\n# area.append(row[\"area\"])\n#\n# setArea = set(area)\n# print(setArea)\n\nl = ['Domain Applications', 'Data Management', 'Programming and Development', 'Cartography and Visualization', 'Foundational Concepts', 'Knowledge Economy', 'Analytics and Modeling', 'Data Capture', 'Computing Platforms', 'GIS&T and Society']\n\n\nwith open('../gisbok_lo.csv', errors='ignore') as f:\n Reader = csv.DictReader(f)\n for row in Reader:\n group = l.index(row[\"area\"]) + 1\n node1 = {\"id\": row[\"area\"], \"group\": group}\n nodes.append(node1)\n node2 = {\"id\": row[\"theme\"], \"group\": group}\n nodes.append(node2)\n node3 = {\"id\": row[\"topic\"], \"group\": group}\n nodes.append(node3)\n node4 = {\"id\": row[\"learning_objective\"], \"group\": group}\n nodes.append(node4)\n link1 = {\"source\": row[\"area\"], \"target\": row[\"theme\"], \"value\": 10}\n links.append(link1)\n link2 = {\"source\": row[\"theme\"], \"target\": row[\"topic\"], \"value\": 10}\n links.append(link2)\n link3 = {\"source\": row[\"topic\"], \"target\": row[\"learning_objective\"], \"value\": 10}\n links.append(link3)\n\n\nprint(nodes)\n\ntrue_nodes = reduce(run_function, [[], ] + nodes)\n# print(true_nodes)\n\ntrue_link = reduce(run_function, [[], ] + links)\nprint(true_link)\n\ndata = {\"nodes\": true_nodes, \"links\": true_link}\nfilename = 'force_graph.json'\nfilename2 = 'links.json'\nwith open(filename, 'w+') as file_obj:\n json.dump(data, file_obj)\n\nwith open(filename2, 'w+') as file_obj:\n json.dump(true_link, file_obj)\n\n\n","repo_name":"UrbanDS/GIS-KG","sub_path":"3d-graph/formData.py","file_name":"formData.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"77"} +{"seq_id":"29381895619","text":"# Diccionario de productos con su información\nproductos = {\n 1: {\"nombre\": \"Juego Pokemon X para Nintendo 3DS\", \"precio\": 33.77},\n 2: {\"nombre\": \"Nintendo 3DS XL\", \"precio\": 203},\n 3: {\"nombre\": \"Juego Mario Kart 7 para Nintendo 3DS\", \"precio\": 27.58},\n 4: {\"nombre\": \"PlayStation 4\", \"precio\": 348.00},\n 5: {\"nombre\": \"FIFA 16, PlayStation 4\", \"precio\": 51.19}\n}\n\n# Carrito de compras\ncarrito = []\n\ndef agregar_producto(producto, cantidad):\n carrito.append((producto, cantidad))\n\ndef imprimir_productos():\n for item in carrito:\n producto = productos[item[0]]\n nombre = producto[\"nombre\"]\n precio = producto[\"precio\"]\n cantidad = item[1]\n print(f\"Producto: {nombre} - Cantidad: {cantidad} - Precio unitario: ${precio}\")\n\ndef hacer_checkout():\n descuento = 0\n for item in carrito:\n producto = productos[item[0]]\n precio = producto[\"precio\"]\n cantidad = item[1]\n subtotal = precio * cantidad\n if item[0] in [1, 2, 3] and len(carrito) >= 3:\n # Aplicar descuento del 20% si se agregaron los productos 1, 2 y 3 al carro\n descuento += subtotal * 0.2\n elif item[0] in [4, 5] and len(carrito) >= 2:\n # Aplicar descuento del 15% si se agregaron los productos 4 y 5 al carro\n descuento += subtotal * 0.15\n\n total = sum([producto[\"precio\"] * cantidad for producto, cantidad in carrito])\n total -= descuento\n\n print(f\"Total a pagar: ${round(total, 1)}\")\n\n# Loop principal\nwhile True:\n accion = input(\"Ingrese 'agregar', 'ver' o 'checkout': \")\n \n if accion == \"agregar\":\n entrada = input(\"Ingrese el producto y la cantidad en el formato 'producto,cantidad': \")\n producto, cantidad = map(int, entrada.split(\",\"))\n if producto in productos.keys() and cantidad > 0:\n agregar_producto(producto, cantidad)\n else:\n print(\"Producto o cantidad inválidos. Intente nuevamente.\")\n elif accion == \"ver\":\n imprimir_productos()\n elif accion == \"checkout\":\n hacer_checkout()\n break\n else:\n print(\"Acción no válida. Intente nuevamente.\")\n","repo_name":"pabloschwarzenberg/grader","sub_path":"hito2_ej4/hito2_ej4_85a82796d6fd778e566d327c4772cdda.py","file_name":"hito2_ej4_85a82796d6fd778e566d327c4772cdda.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"11202415582","text":"import pytest\nimport logging\nimport unittest.mock as mock\nimport telegram_log\n\n\nclass MockLoggingHandler(logging.Handler):\n def __init__(self, *args, **kwargs):\n self.messages = {'debug': [], 'info': [], 'warning': [], 'error': [],\n 'critical': []}\n super(MockLoggingHandler, self).__init__(*args, **kwargs)\n\n def emit(self, record):\n \"Store a message from ``record`` in the instance's ``messages`` dict.\"\n try:\n self.messages[record.levelname.lower()].append(record.getMessage())\n except Exception:\n self.handleError(record)\n\n def reset(self):\n self.acquire()\n try:\n for message_list in self.messages.values():\n message_list.clear()\n finally:\n self.release()\n\n\n@pytest.fixture\ndef handler():\n handler = telegram_log.handler.TelegramLog('token',\n 'chat_id', logging.DEBUG)\n telegram_log.handler.logger.handlers = []\n telegram_log.handler.logger.addHandler(MockLoggingHandler())\n telegram_log.handler.logger.level = logging.DEBUG\n return handler\n\n\ndef test_emit(handler):\n record = logging.makeLogRecord({'msg': 'hello'})\n\n with mock.patch('requests.post') as patch:\n handler.emit(record)\n\n assert patch.called\n assert patch.call_count == 1\n assert patch.call_args[1]['json']['chat_id'] == 'chat_id'\n assert 'hello' in patch.call_args[1]['json']['text']\n assert patch.call_args[1]['json']['parse_mode'] == 'HTML'\n","repo_name":"axce1/telegram_log","sub_path":"tests/test_handlers.py","file_name":"test_handlers.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"10372200816","text":"import math\n\nimport scrapy\nfrom scrapy import Request\nfrom scrapy.crawler import CrawlerProcess\n\n\nclass WebCrawler(scrapy.Spider):\n name = 'spider'\n start_urls = ['https://getlatka.com/']\n\n def parse(self, response):\n\n #extracting all table rows from the webpage\n for row in response.css('table.data-table_table__2P6Tl tr')[1:]:\n columns = row.css('td')\n name = columns[1].css('a.cells_link__2252j::text').extract()\n revenue = columns[2].css('::text').extract()\n funding = columns[3].css('::text').extract()\n valuation = columns[4].css('::text').extract()\n cashflow = columns[5].css('span::text').extract()\n founder = columns[6].css('a.cells_name__KCAFe::text').extract()\n teamsize = columns[7].css('::text').extract()\n age = columns[8].css('::text').extract()\n location = columns[9].css('::text').extract()\n industry = columns[10].css('a.home_ellipses__2KmVe::text').extract()\n asof = columns[11].css('::text').extract()\n\n yield{\n 'Name': ''.join(name).strip(),\n 'Revenue': ''.join(revenue).strip(),\n 'Funding': ''.join(funding).strip(),\n 'Valuation': ''.join(valuation).strip(),\n 'CashFlow': ''.join(cashflow).strip(),\n 'Founder': ''.join(founder).strip(),\n 'TeamSize': ''.join(teamsize).strip(),\n 'Age': ''.join(age).strip(),\n 'Location': ''.join(location).strip(),\n 'Industry': ''.join(industry).strip(),\n 'AsOf': ''.join(asof).strip(),\n }\n\n #we get the url to the next page using the next button at the bottom of the page\n next_urls = response.xpath('//a[@class=\"pagination_button__1f2SL pagination_special_button__3cnmT\"]/@href').extract()\n texts = response.xpath('//a[@class=\"pagination_button__1f2SL pagination_special_button__3cnmT\"]/text()').extract()\n next_page = response.urljoin(next_urls[-1])\n next_text = texts[-1].strip()\n\n if next_text == 'Next':\n yield Request(next_page, callback=self.parse)\n\n\nprocess = CrawlerProcess({\n 'FEED_FORMAT': 'json',\n 'FEED_URI': 'output.json',\n})\n\nprocess.crawl(WebCrawler)\nprocess.start()\n# python multiprocessing library is not supported with scrapy. hence parallel processing can not be done.\n# beautifulSoup could have been used for parallel processing","repo_name":"harsh-surya/scrapper","sub_path":"latkaScrapper/spiders/spider1.py","file_name":"spider1.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"13559939582","text":"#encoding:utf-8\r\n### This script group the scripts and draw the poly or rectangle text area\r\nimport numpy as np\r\n\r\nclass GroupsGen():\r\n def __init__(self,proposals,scores,img_size):\r\n self.proposals = proposals\r\n self.scores = scores\r\n self.img_size = img_size\r\n self.heights = self.proposals[:, 3] - self.proposals[:, 1] + 1\r\n def meet_v_iou(self,index1,index2):\r\n h1=self.heights[index1]\r\n h2=self.heights[index2]\r\n y0=max(self.proposals[index1,1],self.proposals[index2,1])\r\n y1=min(self.proposals[index1,3],self.proposals[index2,3])\r\n over_height=max(0,y1-y0+1)\r\n overlaps=over_height/min(h1,h2)\r\n similarity=min(h1,h2)/max(h1,h2)\r\n if overlaps>=0.7 and similarity>=0.7:\r\n return True\r\n else:\r\n return False\r\n\r\n def get_right_adj(self,index):\r\n ###get the right adjacent proposal\r\n box=self.proposals[index]\r\n results=[]\r\n for pix in range(min(int(box[2])+1,self.img_size[1]-1),min(int(box[2])+1+32,self.img_size[1])):\r\n adj_box_indexes=self.boxes_table[pix]\r\n for adj_box_index in adj_box_indexes:\r\n if self.meet_v_iou(index,adj_box_index) and not(self.graph[:,adj_box_index].any()):#禁止被多个节点定义为右邻居\r\n results.append(adj_box_index)\r\n if len(results)!=0:\r\n return results\r\n return results\r\n\r\n def get_left_adj(self,index):\r\n ###get the left adjacent proposal\r\n box=self.proposals[index]\r\n results=[]\r\n if int(box[0])==0:\r\n return results\r\n for pix in range(int(box[0])-1,max(int(box[0])-1-32,0)-1,-1):\r\n adj_box_indexes=self.boxes_table[pix]\r\n for adj_box_index in adj_box_indexes:\r\n if self.meet_v_iou(index,adj_box_index):\r\n results.append(adj_box_index)\r\n if len(results)!=0:\r\n return results\r\n return results\r\n\r\n def is_conn_node(self,index,right_adj_index):\r\n ### for the proposal[index],if the left adjacent proposal of proposal[right_adj_index] is proposal[index] itself\r\n left_adjs=self.get_left_adj(right_adj_index)\r\n if self.scores[index]>=np.max(self.scores[left_adjs]):\r\n return True\r\n else:\r\n print(\"index:{}---right_adj_index:{}---find is_not_conn_node!!!\".format(index,right_adj_index))\r\n return False\r\n\r\n def graph_build(self):\r\n ### build the neigbour graph\r\n boxes_table=[[] for _ in range(self.img_size[1])]\r\n for index,box in enumerate(self.proposals):\r\n boxes_table[int(box[0])].append(index)\r\n self.boxes_table=boxes_table\r\n\r\n self.graph=np.zeros((self.proposals.shape[0],self.proposals.shape[0]),np.bool)\r\n for index,box in enumerate(self.proposals):\r\n right_adjs=self.get_right_adj(index)\r\n if len(right_adjs)==0:\r\n continue\r\n right_adj_index=right_adjs[np.argmax(self.scores[right_adjs])]\r\n if self.is_conn_node(index,right_adj_index):\r\n self.graph[index,right_adj_index]=True\r\n\r\n def groups_gen(self):\r\n self.graph_build()\r\n ### group the proposals as the neighbour graph\r\n groups=[]\r\n for index in range(self.graph.shape[0]):\r\n if self.graph[index,:].any() and not(self.graph[:,index].any()):\r\n #若proposals[index]右侧有相邻proposal,而左侧没有,且找到一个group的起点\r\n node=index\r\n groups.append([node])\r\n while self.graph[node,:].any(): #如node右侧有相邻proposal\r\n node=np.where(self.graph[node,:])[0][0]#node更新为右侧相邻proposal\r\n groups[-1].append(node)\r\n return groups\r\n\r\ndef fit_y(X,Y,x1,x2):\r\n ### fit the line from points(X,Y), and return the (y1,y2) for (x1,x2)\r\n if np.sum(X==X[0])==len(X): #所有X坐标都一样\r\n return Y[0],Y[0]\r\n p=np.poly1d(np.polyfit(X,Y,1))\r\n return p(x1),p(x2)\r\n\r\ndef filter_poly(text_polys,score_polys):\r\n poly_num=text_polys.shape[0]\r\n heights=np.zeros((poly_num,1),np.float32)\r\n widths=np.zeros((poly_num,1),np.float32)\r\n for index,poly in enumerate(text_polys):\r\n heights[index]=(abs(poly[5]-poly[1])+abs(poly[7]-poly[3]))/2.0\r\n widths[index]=(abs(poly[2]-poly[0])+abs(poly[6]-poly[4]))/2.0\r\n ###filter:\r\n keep_index=np.where((widths/heights>=0.5)&(score_polys>0.9)&(widths>32))[0]\r\n return keep_index\r\n\r\ndef proposal2poly(proposals,scores,x_left_fixed,x_right_fixed,img_size,output_mode='rect'):\r\n #draw the text area from the grouped proposals\r\n # output_mode: 'rect'=draw rectangle;'poly'=draw poly\r\n groups_calc=GroupsGen(proposals,scores,img_size)\r\n groups=groups_calc.groups_gen()\r\n text_polys=np.zeros((len(groups),8),np.float32)\r\n score_polys=np.zeros((len(groups),1),np.float32)\r\n if output_mode=='rect':\r\n for index,group in enumerate(groups):\r\n boxes=proposals[group]\r\n x0= x_left_fixed[group][0] #每组x方向的左、右边界,采用经offset修正过的坐标\r\n x1 = x_right_fixed[group][-1]\r\n lt_y, rt_y = fit_y(boxes[:, 0], boxes[:, 1], x0, x1) # 计算左上、右上y值\r\n lb_y, rb_y = fit_y(boxes[:, 2], boxes[:, 3], x0, x1) # 计算左下、右下y值\r\n score_polys[index]=scores[group].sum()/float(len(group)) #计算本组平均分\r\n text_polys[index,0]=x0\r\n text_polys[index,1]=min(lt_y,rt_y) #这里实际是矩形,目的是尽量少的切割掉文字,而不是与label poly的吻合最佳\r\n text_polys[index,2]=x1\r\n text_polys[index,3]=min(lt_y,rt_y)\r\n text_polys[index,4]=x1\r\n text_polys[index,5]=max(rb_y,lb_y)\r\n text_polys[index,6]=x0\r\n text_polys[index,7]=max(rb_y,lb_y)\r\n else:\r\n for index,group in enumerate(groups):\r\n boxes=proposals[group]\r\n x0= x_left_fixed[group][0] #每组x方向的左、右边界,采用经offset修正过的坐标\r\n x1 = x_right_fixed[group][-1]\r\n lt_y, rt_y = fit_y(boxes[:, 0], boxes[:, 1], x0, x1) # 计算左上、右上y值\r\n lb_y, rb_y = fit_y(boxes[:, 2], boxes[:, 3], x0, x1) # 计算左下、右下y值\r\n score_polys[index]=scores[group].sum()/float(len(group)) #计算本组平均分\r\n text_polys[index,0]=x0\r\n text_polys[index,1]=lt_y\r\n text_polys[index,2]=x1\r\n text_polys[index,3]=rt_y\r\n text_polys[index,4]=x1\r\n text_polys[index,5]=rb_y\r\n text_polys[index,6]=x0\r\n text_polys[index,7]=lb_y\r\n keep_index=filter_poly(text_polys,score_polys)\r\n text_polys=text_polys[keep_index]\r\n score_polys=score_polys[keep_index]\r\n text_polys=text_polys.astype(np.int)\r\n return text_polys,score_polys","repo_name":"huoyeqianxun/CTPN","sub_path":"proposal2poly.py","file_name":"proposal2poly.py","file_ext":"py","file_size_in_byte":7026,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"77"} +{"seq_id":"29438789119","text":"# completa el código de la función\ndef suma_divisores(n):\n a=0\n for i in range(1,n):\n if n%i==0:\n a+=i\n if a==1:\n return(a, True)\n else:\n return(a, False)\n \n\n ","repo_name":"pabloschwarzenberg/grader","sub_path":"tema3_ej1/tema3_ej1_5d0654ab551826ca51091d3355af98b2.py","file_name":"tema3_ej1_5d0654ab551826ca51091d3355af98b2.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":"74332489527","text":"\"\"\"\nConstants used by motopy.\n\nThis is a part of motopy.\n\"\"\"\nimport numpy as np\n# token's types:\n# block. if..else, for, while, etc.\nTT_BLOCK = \"block\"\n# command. load, save.\nTT_CMD = \"cmd\"\n# end of line. \"\\r\" | \"\\n\"\n# token.text used to store comment.\nTT_EOL = \"eol\"\n# identifier\nTT_ID = \"id\"\n# keyword\nTT_KW = \"kw\"\n# number. int, float or complex\nTT_NUM = \"num\"\n# operation and expression\nTT_OP = \"op\"\n# string \nTT_STR = \"str\"\n# format string\nTT_FMT_STR = 'fmt_str'\n# symbol\nTT_SYM = \"sym\"\n# entry\nTT_ROOT = \"root\"\n# code annotation\nTT_CODE = 'code'\n\n\n# see: MATLAB Operators and Special Characters\nop_priors = {\n '()': 0, '[]': 0, '{}': 0,\n '.' : 1,\n '+?': 2, '-?': 2, '~': 2,\n \"'\" : 3, \".'\" : 3, '^' : 3, '.^' : 3,\n '*' : 4, '/': 4, '\\\\': 4, '.*' : 4, './': 4,'.\\\\': 4, \n '+' : 5, '-' : 5,\n ':' : 6,\n '<' : 7, '<=': 7, '>' : 7, '>=' : 7, '==' : 7, '~=' : 7, \n '&' : 8,\n '|' : 9,\n '&&' : 10, \n '||' : 11, \n '=' : 12,\n ',' : 13,\n ';' : 14,\n}\n\nop_dict = {\n '~': 'not ',\n '^' : '**', \n '.^' : '**', \n '.*' : '*', \n './': '/',\n '~=' : '!=', \n '&&' : 'and', \n '||' : 'or'\n}\n\n\"\"\" `func_name_dict` is used to replace the function name simply.\n\"\"\"\nfunc_name_dict = {\n 'abs': 'np.abs',\n 'acos': 'np.arccos',\n 'all': 'all',\n 'any': 'any',\n 'asin': 'np.arcsin',\n 'atan': 'np.arctan',\n 'ceil': 'np.ceil',\n 'cos': 'np.cos',\n 'diag': 'np.diag',\n 'disp': 'print',\n 'eye': 'np.eye',\n 'exp': 'np.exp',\n 'fft': 'np.fft.fft',\n 'fix': 'np.fix',\n 'floor': 'np.floor',\n 'ifft': 'np.fft.ifft',\n 'inv': 'linalg.inv',\n 'linspace': 'np.linspace',\n 'log': 'np.log',\n 'log10': 'np.log10',\n 'log2': 'np.log2',\n 'mod': 'np.mod',\n 'ndims': 'np.ndim',\n 'numel': 'np.size',\n 'num2str': 'str',\n 'pinv': 'linalg.pinv',\n 'rand': 'random.rand',\n 'rank': 'linalg.matrix_rank',\n 'round': 'np.round',\n 'sin': 'np.sin',\n 'sort': 'np.sort',\n 'sqrt': 'np.sqrt',\n 'unique': 'np.unique',\n}\n\nbinary_operators = ['.', '^', '.^', '*', '/', '\\\\', '.*', './', '.\\\\', '+', '-', ':', '<', '<=', '>', '>=', '==', '~=', '&', '|', '&&', '||', '=']\nleft_unary_operators = ['+?', '-?', '~', '!']\nright_unary_operators = [\"'\", \".'\"]\n\nbracket_pairs = {'(':')', '[':']', '{':'}'} \n\nmatlab_blocks = [\"if\", \"elseif\", \"else\", \"switch\", \"case\", \"otherwise\",\n \"for\", \"while\", \"try\", \"catch\", \"parfor\", \"function\"]\n\nfctrl_keywords = ['break', 'continue', 'return']\n\n# matlab keywords\nmatlab_keywords = [\n \"if\", \"elseif\", \"else\", \"switch\", \"case\", \"otherwise\",\n \"for\", \"while\", \"try\", \"catch\", \"break\", \"return\", \"continue\",\n \"pause\", \"parfor\", \"end\", 'function'\n]\n\nmatlab_commands = ['clc', 'clf', 'close', 'clear', 'load', 'save', 'global']\n\nvalue_dict = {\n 'true':'True',\n 'false':'False',\n 'inf': 'np.Inf',\n 'Inf': 'np.Inf',\n 'nan': 'np.NaN',\n 'NaN': 'np.NaN'\n}","repo_name":"falwat/motopy","sub_path":"motopy/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":2903,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"16003845001","text":"import time\nfrom selenium import webdriver\n\ndriver = webdriver.Chrome(executable_path=\"C:\\Dev\\Resources\\chromedriver\\chromedriver.exe\") \n\n# Load James Quick's typing game page.\ndriver.get('https://learnbuildtype.netlify.com/');\n\n# Allow the page to load. \ntime.sleep(5) \n\n# Start the game after the home page loads. \ndriver.find_element_by_tag_name('body').send_keys('s') \n\n# Set your desired score for the typing game\ndesiredScore = 303\n\n# Once the game has started this loop grabs the randomCharcter to type and enters it. The desiredScore is\n# how many times this loop will run. Each loop adds a score of 1. So 303 loops will give a score of 303. \nfor i in range(desiredScore):\n rc = (driver.find_element_by_id('randomCharacter')).text\n driver.find_element_by_tag_name('body').send_keys(rc) \n\n# Give the game time to complete (30 Seconds) and allow the user to input a playerName to save. \ntime.sleep(45) \n\n# Shut the chromeDriver down.\ndriver.quit()\n\n","repo_name":"nickpaisley/scoreBot","sub_path":"scoreBot.py","file_name":"scoreBot.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"23598645739","text":"from abc import abstractmethod\nfrom typing import List, Dict, Tuple\n\nimport pyqtgraph as pg\n\nfrom vnpy.trader.ui import QtCore, QtGui, QtWidgets\nfrom vnpy.trader.object import BarData\n\nfrom .base import BLACK_COLOR, UP_COLOR, DOWN_COLOR, PEN_WIDTH, BAR_WIDTH\nfrom .manager import BarManager\n\n\nclass ChartItem(pg.GraphicsObject):\n \"\"\"\"\"\"\n\n def __init__(self, manager: BarManager) -> None:\n \"\"\"\"\"\"\n super().__init__()\n\n self._manager: BarManager = manager\n\n self._bar_picutures: Dict[int, QtGui.QPicture] = {}\n self._item_picuture: QtGui.QPicture = None\n\n self._black_brush: QtGui.QBrush = pg.mkBrush(color=BLACK_COLOR)\n\n self._up_pen: QtGui.QPen = pg.mkPen(\n color=UP_COLOR, width=PEN_WIDTH\n )\n self._up_brush: QtGui.QBrush = pg.mkBrush(color=UP_COLOR)\n\n self._down_pen: QtGui.QPen = pg.mkPen(\n color=DOWN_COLOR, width=PEN_WIDTH\n )\n self._down_brush: QtGui.QBrush = pg.mkBrush(color=DOWN_COLOR)\n\n self._rect_area: Tuple[float, float] = None\n\n # Very important! Only redraw the visible part and improve speed a lot.\n self.setFlag(self.ItemUsesExtendedStyleOption)\n\n # Force update during the next paint\n self._to_update: bool = False\n\n @abstractmethod\n def _draw_bar_picture(self, ix: int, bar: BarData) -> QtGui.QPicture:\n \"\"\"\n Draw picture for specific bar.\n \"\"\"\n pass\n\n @abstractmethod\n def boundingRect(self) -> QtCore.QRectF:\n \"\"\"\n Get bounding rectangles for item.\n \"\"\"\n pass\n\n @abstractmethod\n def get_y_range(self, min_ix: int = None, max_ix: int = None) -> Tuple[float, float]:\n \"\"\"\n Get range of y-axis with given x-axis range.\n\n If min_ix and max_ix not specified, then return range with whole data set.\n \"\"\"\n pass\n\n @abstractmethod\n def get_info_text(self, ix: int) -> str:\n \"\"\"\n Get information text to show by cursor.\n \"\"\"\n pass\n\n def update_history(self, history: List[BarData]) -> None:\n \"\"\"\n Update a list of bar data.\n \"\"\"\n self._bar_picutures.clear()\n\n bars: List[BarData] = self._manager.get_all_bars()\n for ix, bar in enumerate(bars):\n self._bar_picutures[ix] = None\n\n self.update()\n\n def update_bar(self, bar: BarData) -> None:\n \"\"\"\n Update single bar data.\n \"\"\"\n ix: int = self._manager.get_index(bar.datetime)\n\n self._bar_picutures[ix] = None\n\n self.update()\n\n def update(self) -> None:\n \"\"\"\n Refresh the item.\n \"\"\"\n if self.scene():\n self._to_update = True\n self.scene().update()\n\n def paint(\n self,\n painter: QtGui.QPainter,\n opt: QtWidgets.QStyleOptionGraphicsItem,\n w: QtWidgets.QWidget\n ) -> None:\n \"\"\"\n Reimplement the paint method of parent class.\n\n This function is called by external QGraphicsView.\n \"\"\"\n rect = opt.exposedRect\n\n min_ix: int = int(rect.left())\n max_ix: int = int(rect.right())\n max_ix: int = min(max_ix, len(self._bar_picutures))\n\n rect_area: tuple = (min_ix, max_ix)\n if (\n self._to_update\n or rect_area != self._rect_area\n or not self._item_picuture\n ):\n self._to_update = False\n self._rect_area = rect_area\n self._draw_item_picture(min_ix, max_ix)\n\n self._item_picuture.play(painter)\n\n def _draw_item_picture(self, min_ix: int, max_ix: int) -> None:\n \"\"\"\n Draw the picture of item in specific range.\n \"\"\"\n self._item_picuture = QtGui.QPicture()\n painter: QtGui.QPainter = QtGui.QPainter(self._item_picuture)\n\n for ix in range(min_ix, max_ix):\n bar_picture: QtGui.QPicture = self._bar_picutures[ix]\n\n if bar_picture is None:\n bar: BarData = self._manager.get_bar(ix)\n bar_picture = self._draw_bar_picture(ix, bar)\n self._bar_picutures[ix] = bar_picture\n\n bar_picture.play(painter)\n\n painter.end()\n\n def clear_all(self) -> None:\n \"\"\"\n Clear all data in the item.\n \"\"\"\n self._item_picuture = None\n self._bar_picutures.clear()\n self.update()\n\n\nclass CandleItem(ChartItem):\n \"\"\"\"\"\"\n\n def __init__(self, manager: BarManager) -> None:\n \"\"\"\"\"\"\n super().__init__(manager)\n\n def _draw_bar_picture(self, ix: int, bar: BarData) -> QtGui.QPicture:\n \"\"\"\"\"\"\n # Create objects\n candle_picture: QtGui.QPicture = QtGui.QPicture()\n painter: QtGui.QPainter = QtGui.QPainter(candle_picture)\n\n # Set painter color\n if bar.close_price >= bar.open_price:\n painter.setPen(self._up_pen)\n painter.setBrush(self._black_brush)\n else:\n painter.setPen(self._down_pen)\n painter.setBrush(self._down_brush)\n\n # Draw candle shadow\n if bar.high_price > bar.low_price:\n painter.drawLine(\n QtCore.QPointF(ix, bar.high_price),\n QtCore.QPointF(ix, bar.low_price)\n )\n\n # Draw candle body\n if bar.open_price == bar.close_price:\n painter.drawLine(\n QtCore.QPointF(ix - BAR_WIDTH, bar.open_price),\n QtCore.QPointF(ix + BAR_WIDTH, bar.open_price),\n )\n else:\n rect: QtCore.QRectF = QtCore.QRectF(\n ix - BAR_WIDTH,\n bar.open_price,\n BAR_WIDTH * 2,\n bar.close_price - bar.open_price\n )\n painter.drawRect(rect)\n\n # Finish\n painter.end()\n return candle_picture\n\n def boundingRect(self) -> QtCore.QRectF:\n \"\"\"\"\"\"\n min_price, max_price = self._manager.get_price_range()\n rect: QtCore.QRectF = QtCore.QRectF(\n 0,\n min_price,\n len(self._bar_picutures),\n max_price - min_price\n )\n return rect\n\n def get_y_range(self, min_ix: int = None, max_ix: int = None) -> Tuple[float, float]:\n \"\"\"\n Get range of y-axis with given x-axis range.\n\n If min_ix and max_ix not specified, then return range with whole data set.\n \"\"\"\n min_price, max_price = self._manager.get_price_range(min_ix, max_ix)\n return min_price, max_price\n\n def get_info_text(self, ix: int) -> str:\n \"\"\"\n Get information text to show by cursor.\n \"\"\"\n bar: BarData = self._manager.get_bar(ix)\n\n if bar:\n words: list = [\n \"Date\",\n bar.datetime.strftime(\"%Y-%m-%d\"),\n \"\",\n \"Time\",\n bar.datetime.strftime(\"%H:%M\"),\n \"\",\n \"Open\",\n str(bar.open_price),\n \"\",\n \"High\",\n str(bar.high_price),\n \"\",\n \"Low\",\n str(bar.low_price),\n \"\",\n \"Close\",\n str(bar.close_price)\n ]\n text: str = \"\\n\".join(words)\n else:\n text: str = \"\"\n\n return text\n\n\nclass VolumeItem(ChartItem):\n \"\"\"\"\"\"\n\n def __init__(self, manager: BarManager) -> None:\n \"\"\"\"\"\"\n super().__init__(manager)\n\n def _draw_bar_picture(self, ix: int, bar: BarData) -> QtGui.QPicture:\n \"\"\"\"\"\"\n # Create objects\n volume_picture: QtGui.QPicture = QtGui.QPicture()\n painter: QtGui.QPainter = QtGui.QPainter(volume_picture)\n\n # Set painter color\n if bar.close_price >= bar.open_price:\n painter.setPen(self._up_pen)\n painter.setBrush(self._up_brush)\n else:\n painter.setPen(self._down_pen)\n painter.setBrush(self._down_brush)\n\n # Draw volume body\n rect: QtCore.QRectF = QtCore.QRectF(\n ix - BAR_WIDTH,\n 0,\n BAR_WIDTH * 2,\n bar.volume\n )\n painter.drawRect(rect)\n\n # Finish\n painter.end()\n return volume_picture\n\n def boundingRect(self) -> QtCore.QRectF:\n \"\"\"\"\"\"\n min_volume, max_volume = self._manager.get_volume_range()\n rect: QtCore.QRectF = QtCore.QRectF(\n 0,\n min_volume,\n len(self._bar_picutures),\n max_volume - min_volume\n )\n return rect\n\n def get_y_range(self, min_ix: int = None, max_ix: int = None) -> Tuple[float, float]:\n \"\"\"\n Get range of y-axis with given x-axis range.\n\n If min_ix and max_ix not specified, then return range with whole data set.\n \"\"\"\n min_volume, max_volume = self._manager.get_volume_range(min_ix, max_ix)\n return min_volume, max_volume\n\n def get_info_text(self, ix: int) -> str:\n \"\"\"\n Get information text to show by cursor.\n \"\"\"\n bar: BarData = self._manager.get_bar(ix)\n\n if bar:\n text: str = f\"Volume {bar.volume}\"\n else:\n text: str = \"\"\n\n return text\n","repo_name":"vnpy/vnpy","sub_path":"vnpy/chart/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":9237,"program_lang":"python","lang":"en","doc_type":"code","stars":22169,"dataset":"github-code","pt":"77"} +{"seq_id":"25764781687","text":"# using setDefault to set the default value of a dictionary entry\n\nnew_dict = {'name': 'samson', 'best-color': 'blue', 'favourite-musician': 'Ed sheeran'}\nnew_dict.setdefault('favourtie-car', 'tesla')\n# before changing the value of favourite car\nprint(new_dict)\nnew_dict['favourite-car'] = 'Maseratti'\n \n# after changing the value of favourite car\nprint(new_dict)","repo_name":"sammyodiagbe/python-stroll","sub_path":"07/03 setDeault.py","file_name":"03 setDeault.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"16531609553","text":"\n#!/usr/bin/env python3\n\"\"\"\ndecode for machine translation:\n\"\"\"\nimport tensorflow as tf\nSelfAttention = __import__('1-self_attention').SelfAttention\n\n\nclass RNNDecoder(tf.keras.layers.Layer):\n \"\"\"\n decode for machine translation:\n \"\"\"\n\n def __init__(self, vocab, embedding, units, batch):\n \"\"\"\n constructor function\n \"\"\"\n super().__init__()\n self.vocab = vocab\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 self.F = tf.keras.layers.Dense(vocab)\n\n def call(self, x, s_prev, hidden_states):\n \"\"\"\n call function\n \"\"\"\n attention = SelfAttention(self.units)\n context_vector, attention_weights = attention(s_prev, hidden_states)\n x = self.embedding(x)\n attention_vector = tf.concat([tf.expand_dims(context_vector, 1), x],\n axis=-1)\n output, state = self.gru(attention_vector)\n output = tf.reshape(output, (-1, output.shape[2]))\n x = self.F(output)\n return x, state\n","repo_name":"AhmedOmi/holbertonschool-machine_learning","sub_path":"supervised_learning/0x11-attention/2-rnn_decoder.py","file_name":"2-rnn_decoder.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"71477652729","text":"import logging\nimport socket\nimport tornado\n\nfrom core import login_handler\nfrom core import shortcut_server_model as M\n\nclass HomeHandler(login_handler.BaseHandler):\n \"\"\"\n This handler is to showing the home page of the server \n \"\"\"\n @tornado.web.authenticated\n def get(self):\n data = {\n 'title': 'Shortcut Server: %s' % socket.gethostname(),\n 'channels': M.model.channels,\n 'connections': M.model.connections,\n }\n self.render('home.html', **data)\n\n\nclass ConsoleHandler(login_handler.BaseHandler):\n \"\"\"\n This handler is to display a console page for debugging/monitoring\n \"\"\"\n @tornado.web.authenticated\n def get(self):\n data = {\n 'title': 'Shortcut Console: %s' % socket.gethostname(),\n 'channels': M.model.channels,\n }\n self.render('console.html', **data)\n\n","repo_name":"yjpark/shortcut","sub_path":"server/core/server_handler.py","file_name":"server_handler.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"7496940627","text":"import json\nfrom pathlib import Path\n\nimport numpy as np \nfrom PIL import Image\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\nimport torchvision.transforms.functional as F_t\n\nfrom sklearn.preprocessing import LabelEncoder\n\nimport timm\n\ntorch.manual_seed(100)\nhas_cuda = torch.cuda.is_available()\ndevice = torch.device(\"cuda\" if has_cuda else \"cpu\")\n\ndevice\n\n\"\"\"## Study image data\"\"\"\n\ntrainset_path = Path('/data/data-sets/CatBreeds/Oxford-IIIT/catonly_train/')\ntestset_path = Path('/data/data-sets/CatBreeds/Oxford-IIIT/catonly_test/')\n\n# list contents in images/\ncat_breeds = []\nfor i in trainset_path.iterdir():\n breed_tag = i.name\n if breed_tag not in cat_breeds:\n cat_breeds.append(breed_tag)\n\nN = len(cat_breeds)\nprint(N)\n\nlab_enc = LabelEncoder()\nlab_enc.fit(cat_breeds)\n\nordered_labels = lab_enc.inverse_transform(np.arange(N)).tolist()\nprint(ordered_labels)\n\nwith open('ordered_labels.json', 'w') as f:\n json.dump(ordered_labels, f)\n\n\"\"\"## Create dataset instance\"\"\"\n\ntfcats = transforms.Compose([\n transforms.RandomAffine(degrees=25, translate=(0.1, 0.1), scale=(0.9, 1.1), interpolation=F_t.InterpolationMode.BICUBIC),\n transforms.Resize(256, interpolation=F_t.InterpolationMode.BICUBIC),\n transforms.CenterCrop(224),\n transforms.GaussianBlur(kernel_size=3),\n transforms.RandomHorizontalFlip(p=0.5),\n transforms.ToTensor(),\n transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),\n])\n\ntfcats_eval = transforms.Compose([\n transforms.Resize(256, interpolation=F_t.InterpolationMode.BICUBIC),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),\n])\n\nclass CustomDataset(Dataset):\n \n def __init__(self, image_folder, tf):\n self.image_folder = image_folder\n self.tf = tf\n\n self.samples = []\n for p in image_folder.glob('*/*.png'):\n cls_name = p.parent.name\n cls_idx = lab_enc.transform([cls_name])[0]\n self.samples.append([p, cls_idx])\n\n def __len__(self):\n return len(self.samples)\n\n def __getitem__(self, idx):\n img_path, cls_idx = self.samples[idx]\n img = Image.open(img_path)\n # apply image transform\n tsr = self.tf(img)\n return tsr, cls_idx;\n\ntrainset = CustomDataset(image_folder=trainset_path, tf=tfcats)\ntestset = CustomDataset(image_folder=testset_path, tf=tfcats_eval)\nprint(len(trainset), len(testset))\n\n# TEST by retrieving one sample from Dataset\na, b = trainset[99]\nprint(a.shape, a.min(), a.max(), b)\n\n# Create DataLoader\ntrain_loader = torch.utils.data.DataLoader(trainset,\n batch_size=128,\n shuffle=True,\n drop_last=True,\n num_workers=0)\ntest_loader = torch.utils.data.DataLoader(testset, batch_size=16, drop_last=False)\n\n# TEST by retrieving one batch from DataLoader\nfor a, b in train_loader:\n print(a.shape, b)\n break\n\n\"\"\"## Convolutional Neural Network \"\"\"\n\nprint(timm.list_models('*mobilenet*'))\n\nmodel = timm.create_model('mobilenetv3_small_100', pretrained=True, num_classes=N)\n\nsum(p.numel() for p in model.parameters() if p.requires_grad)\n\nfrom timm.data import resolve_data_config\n\nconfig = resolve_data_config({}, model=model)\n\nconfig\n\nmodel = model.to(device)\n# print(model)\n\n# optimizer\noptimizer = torch.optim.SGD(model.parameters(),\n lr=0.001,\n momentum=0.9,\n weight_decay=1e-4)\n\n# TEST by feeding a dummy input\nx = torch.empty((1,3,224,224), device=device)\ny = model(x)\nprint(x.shape, '->', y.shape)\n\n\"\"\"## Train/Test Functions\"\"\"\n\ndef train(model, device, train_loader, optimizer, epoch):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n y = model(data)\n output = F.log_softmax(y, dim=1)\n loss = F.nll_loss(output, target)\n loss.backward()\n optimizer.step()\n if batch_idx % 10 == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n\ndef test(model, device, test_loader):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n y = model(data)\n output = F.log_softmax(y, dim=1)\n test_loss += F.nll_loss(output, target, reduction='sum').item()\n pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader.dataset)\n acc = 100. * correct / len(test_loader.dataset)\n\n print('Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset), acc))\n return acc\n\n\"\"\"### Start Train/Test, save model(s)\"\"\"\n\nn_epochs = 50\n\nacc_history = []\nfor i in range(1, n_epochs + 1):\n train(model=model, device=device, train_loader=train_loader, optimizer=optimizer, epoch=i)\n acc = test(model=model, device=device, test_loader=test_loader)\n acc_history.append(acc)\n\nmodel_scripted = torch.jit.script(model)\nmodel_scripted.save('model_scripted.pt')\n\n\"\"\"### Visualize loss and accuray\"\"\"\n\nimport matplotlib.pyplot as plt\n#from sklearn.metrics import confusion_matrix\n#from sklearn.metrics import plot_confusion_matrix\n\ndef viewAccuracyGraph(accuracy_history):\n plt.plot(accuracy_history, color='orange')\n plt.title('Test Accuracy', fontsize=25)\n plt.xlabel('Epoch', fontsize=18)\n plt.ylabel('Accuracy', fontsize=18)\n\nviewAccuracyGraph(acc_history)\n\n","repo_name":"itsAmyHong/Cat-Breed-Identifier","sub_path":"cat_classify.py","file_name":"cat_classify.py","file_ext":"py","file_size_in_byte":6086,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"26089365091","text":"import os\nimport re\nimport json\nimport logging\nfrom __init__ import __version__\nfrom discord import Embed, Color, Member, User\nfrom datetime import datetime\nfrom math import ceil\n\n__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n\n# ASSERTIONS\n\ndef assert_type(value, *types, otherwise=TypeError):\n if not type(value) in types:\n if otherwise == TypeError:\n raise TypeError(\"Expected {} when passed value '{}', found {} instead\".format(\n \", \".join([str(t) for t in types]), value, type(value))\n )\n else:\n return otherwise\n return value\n\ndef assert_class(value, *classes, otherwise=TypeError):\n if not value.__class__ in classes:\n if otherwise == TypeError:\n raise TypeError(\"Expected {} when passed value '{}', found {} instead\".format(\n \", \".join([str(c) for c in classes]), value, value.__class__)\n )\n else:\n return otherwise\n return value\n\n# DATABASE\n\nfrom db import DatabaseManager\nclass DBM(DatabaseManager):\n def __init__(self):\n super().__init__('toontracker.db')\n\n def create_section(self, module, section_name, arguments):\n return super().create_table(module.__class__.__name__ + '_' + section_name, arguments)\n\n def get_section(self, module, section_name):\n for table in self.tables:\n if table.name == module.__class__.__name__ + '_' + section_name:\n return table\ndatabase = DBM()\n\n# CONFIG\n\nclass Config:\n @staticmethod\n def open_file(mode):\n try:\n file = open(os.path.join(__location__, 'config.json'), mode)\n except FileNotFoundError:\n created_file = open(os.path.join(__location__, 'config.json'), 'w+')\n created_file.write('{}')\n created_file.close()\n file = open(os.path.join(__location__, 'config.json'), mode)\n print('config.json was not found, so the file was created.')\n content = json.loads(file.read().decode('utf-8'))\n file.close()\n try:\n file = open(os.path.join(__location__, 'profiles', content['profile']), mode)\n except (KeyError, FileNotFoundError) as e:\n if isinstance(e, FileNotFoundError):\n print('[!!!] Tried to open profile \"{}\", but the profile couldn\\'t be found.'.format(content['profile']))\n file = open(os.path.join(__location__, 'config.json'), mode)\n return file\n\n @classmethod\n def get_setting(cls, setting, otherwise=None):\n try:\n file = cls.open_file('rb')\n content = json.loads(file.read().decode('utf-8'))\n return content.get(setting, otherwise)\n except json.JSONDecodeError:\n print('[!!!] Tried to read setting \"{}\", but {} did not have valid JSON content.'.format(\n setting, os.path.basename(file.name))\n )\n return otherwise\n finally:\n file.close()\n\n @classmethod\n def get_module_setting(cls, module, setting, otherwise=None):\n pss = cls.get_setting(module)\n if not pss or pss.get(setting, None) == None:\n return otherwise\n return pss[setting]\n\n @classmethod\n def get_user_ranks(cls):\n user_ranks = {int(user_id): rank for user_id, rank in cls.get_setting('user_ranks').items()}\n return user_ranks or {}\n\n @classmethod\n def get_rank_of_user(cls, user):\n return cls.get_user_ranks().get(user, 0)\n\n @classmethod\n def get_users_with_rank(cls, rank):\n users = []\n for u, r in cls.get_user_ranks().items():\n if r >= rank:\n users.append(u)\n return users\n\n # Convenience method that gets top rank between\n # both the individual user and their roles.\n # This takes a Member object, unlike the other Config methods.\n @classmethod\n def get_rank_of_member(cls, member):\n if member.__class__ == Member:\n return max([cls.get_rank_of_user(member.id)] + [cls.get_rank_of_role(role.id) for role in member.roles])\n elif member.__class__ == User:\n return cls.get_rank_of_user(member.id)\n else:\n raise TypeError('\"member\" argument should be discord.Member or discord.User')\n\n @classmethod\n def get_role_ranks(cls):\n role_ranks = {int(role_id): rank for role_id, rank in cls.get_setting('role_ranks').items()}\n return role_ranks or {}\n\n @classmethod\n def get_rank_of_role(cls, role):\n return cls.get_role_ranks().get(role, 0)\n\n @classmethod\n def get_roles_with_rank(cls, rank):\n roles = []\n for l, r in cls.get_role_ranks().items():\n if r >= rank:\n roles.append(l)\n return roles\n\n @classmethod\n def set_setting(cls, setting, value):\n try:\n file = cls.open_file('r+b')\n content = json.loads(file.read().decode('utf-8'))\n content[setting] = value\n file.seek(0, 0)\n file.write(json.dumps(content, indent=4, sort_keys=True).encode('utf-8'))\n file.truncate()\n except json.JSONDecodeError:\n print('[!!!] Tried to write value \"{}\" to setting \"{}\", but {} did not have valid JSON content.'.format(\n value, setting, os.path.basename(file.name))\n )\n finally:\n file.close()\n\n @classmethod\n def set_module_setting(cls, module, setting, value):\n settings = cls.get_setting(module)\n if settings == None:\n settings = {}\n settings[setting] = value\n cls.set_setting(module, settings)\n\n @classmethod\n def set_user_rank(cls, user, rank):\n user_ranks = cls.get_user_ranks()\n user_ranks[user] = rank\n cls.set_setting('user_ranks', user_ranks)\n\n @classmethod\n def set_role_rank(cls, role, rank):\n role_ranks = cls.get_role_ranks()\n role_ranks[role] = rank\n cls.set_setting('role_ranks', user_ranks)\n\n\nSHORT_TIME = re.compile(r'(?P[0-9]+)(?P[smhdwMy])')\nLENGTHS = {\n 's': 1,\n 'm': 60,\n 'h': 3600,\n 'd': 86400,\n 'w': 604800,\n 'M': 2629743,\n 'y': 31556926\n}\nFULL = {\n 's': 'seconds',\n 'm': 'minutes',\n 'h': 'hours',\n 'd': 'days',\n 'w': 'weeks',\n 'M': 'months',\n 'y': 'years'\n}\ndef get_short_time_length(time):\n match = SHORT_TIME.match(time)\n if not match:\n raise ValueError('time must be formatted as number + letter (e.g. 15s, 2y, 1w, 7d, 24h)')\n return LENGTHS[match.group('char')] * int(match.group('num'))\ndef get_short_time_unit(time):\n match = SHORT_TIME.match(time)\n if not match:\n raise ValueError('time must be formatted as number + letter (e.g. 15s, 2y, 1w, 7d, 24h)')\n return FULL[match.group('char')]\ndef get_long_time(time):\n match = SHORT_TIME.match(time)\n if not match:\n raise ValueError('time must be formatted as number + letter (e.g. 15s, 2y, 1w, 7d, 24h)')\n return '{} {}'.format(match.group('num'), FULL[match.group('char')])\n\ndef get_time_from_seconds(seconds, *, one_unit_limit=False, short=False):\n if int(seconds) <= 60:\n if int(seconds) == 60:\n return '1 minute' if not short else '1m'\n else:\n return '{} seconds'.format(int(seconds)) if not short else '{}s'.format(int(seconds))\n elif int(seconds / 60) <= 60:\n if int(seconds / 60) == 1:\n return '1 minute' if not short else '1m'\n else:\n return '{} minutes'.format(int(seconds / 60)) if not short else '{}m'.format(int(seconds / 60))\n else:\n h = 0\n m = int(seconds / 60)\n while m > 60:\n h += 1\n m -= 60\n if not short:\n hs = 'hour' if h == 1 else 'hours'\n ms = 'minute' if m == 1 else 'minutes'\n if not one_unit_limit:\n return '{} {} and {} {}'.format(str(h), hs, str(m), ms)\n else:\n return '{} {}'.format(str(h), hs)\n else:\n return '{}h{}m'.format(h, m)\n\ndef get_attribute_from_match(iterable, match):\n for k, v in iterable.items():\n if match in k:\n return v\n\ndef get_version():\n return __version__\n\ndef get_progress_bar(progress, out_of):\n p = int((progress/out_of) * 10)\n progress = '[{}{}]'.format('■' * p, (' '*(10-p))+(' '*ceil((10-p)/2)))\n return progress\n\ndef make_list_from_string(string):\n return string.split(',') if string else []\n\ndef make_count_of_string(string):\n return string.count(',') + 1 if string else 0\n","repo_name":"TheRandomDog/ToonTracker-old","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"73796952248","text":"\n# Ini merupakan fungsi dari L2 untuk mencari\n# string yang diawali simbol 1 dan jumlah simbol 0 adalah kelipatan 3\ndef L2(state , string):\n# state adalah state awal, string adalah string yang akan diuji\n\n finishState = ['q4']\n # FINISH STATE YAITU q4\n\n if(string!=\"\"): # Jika string tidak kosong\n\n print(f'δ({ state },{ string[0] }) = ', end = '')\n # Menampilkan delta-topi dari state dan string yang akan diuji\n\n if(state == \"q0\"): # Jika state awal adalah q0\n if(string[0] == \"1\"): # Jika string yang akan diuji adalah 1\n print(state)\n return L2('q1', string[1:] ) \n # Mengembalikan fungsi dengan state awal q1 dan string yang akan diuji adalah string yang akan diuji tanpa karakter pertama\n\n else: # Jika string yang akan diuji bukan 1\n print(\"Dead State\") # Maka akan menampilkan dead state\n\n elif(state == \"q1\"): # Jika state awal adalah q1\n if(string[0]==\"1\"): # Jika string yang akan diuji adalah 1\n print(state) # Maka akan menampilkan state q1\n\n return L2(state,string[1:]) \n # Mengembalikan fungsi dengan state awal q1\n\n else: # Jika string yang akan diuji bukan 1\n print(\"q2\") # Maka akan menampilkan state q2\n\n return L2(\"q2\",string[1:]) \n # Mengembalikan fungsi dengan state awal q2\n\n elif(state == \"q2\"): # Jika state awal adalah q2\n if(string[0]==\"1\"): # Jika string yang akan diuji adalah 1\n print(state) # Maka akan menampilkan state q2\n\n return L2(state,string[1:])\n # Mengembalikan fungsi dengan state awal q2\n\n else: # Jika string yang akan diuji bukan 1\n print(\"q3\") # Maka akan menampilkan state q3\n\n return L2(\"q3\",string[1:])\n # Mengembalikan fungsi dengan state awal q3\n\n elif(state == \"q3\"): # Jika state awal adalah q3\n if(string[0] == \"1\"): # dan Jika string yang akan diuji adalah 1\n print(state) # Maka akan menampilkan state q3\n\n return L2(state,string[1:]) \n # Mengembalikan fungsi dengan state awal q3\n\n else: # Jika string yang akan diuji bukan 1\n print(finishState[0]) # Maka akan menampilkan finish state q4\n\n return L2(finishState[0],string[1:])\n # Mengembalikan fungsi dengan state awal finish state q4\n\n elif(state == finishState[0]): # Jika state awal adalah finish state q4\n if(string[0]==\"1\"): # dan Jika string yang akan diuji adalah 1\n print(state) # Maka akan menampilkan state q4\n\n return L2(state,string[1:])\n # Mengembalikan fungsi dengan state awal q4\n\n else: # Jika string yang akan diuji bukan 1\n print(\"q2\") # Maka akan menampilkan state q2\n\n return L2(\"q2\",string[1:])\n # Mengembalikan fungsi dengan state awal q2\n\n else: # Jika string sudah kosong atau kosong dari awal\n if state in finishState: \n # Jika state awal adalah finish state\n\n print('Finish State = ', state) \n # Maka akan menampilkan finish state\n\n else: # Jika state awal bukan finish state\n print('Dead State = ', state)\n # Maka akan menampilkan dead state\n","repo_name":"imkzuma/Teori-Bahasa-dan-Otomata","sub_path":"NFA/FunctionL2.py","file_name":"FunctionL2.py","file_ext":"py","file_size_in_byte":3439,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"21600209815","text":"from collections import defaultdict\nfrom sys import stdin\n\ndef main():\n input = stdin.readline\n MOD = 10**9 + 7\n n = int(input())\n songs = [int(i) for i in input().split()]\n count = 0\n ones = {}\n dic = {}\n for i in range(n):\n if songs[i] == 1:\n if count in ones:\n ones[count] += 1\n else:\n ones[count] = 1\n elif songs[i] == 2:\n count += 1\n else:\n for key in ones:\n n = count - key\n if n in dic:\n dic[n] += ones[key]\n else:\n dic[n] = ones[key]\n total = 0\n for key in dic:\n total += (2**key - 1) * dic[key]\n # for i,n in enumerate(dic):\n # total += (2**i - 1) * n\n print(total%MOD)\n\nif __name__ == \"__main__\":\n main()","repo_name":"Programmerryoki/Competitive-Programming","sub_path":"Kattis Problems/Contest/2020 NA Regionals Practice Contest 14/G.py","file_name":"G.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"75046803127","text":"from turtle import *\r\nfrom math import sqrt\r\n\r\n\r\ndef triangle(side):\r\n for i in range(3):\r\n forward(side)\r\n left(120)\r\n\r\n\r\ndef colored_factorial_triangle(colors, side):\r\n color(colors[0])\r\n fillcolor(colors[0])\r\n \r\n # draw a big triangle\r\n begin_fill()\r\n triangle(side)\r\n end_fill()\r\n forward(side/2)\r\n left(60)\r\n # start drawing inner triangles\r\n colored_factorial_triangle_insides(len(colors) - 1, side/2, colors)\r\n\r\n\r\ndef colored_factorial_triangle_insides(remaining_layers, side, colors):\r\n\r\n color(colors[len(colors) - remaining_layers])\r\n fillcolor(colors[len(colors) - remaining_layers])\r\n \r\n # main triangle\r\n begin_fill()\r\n triangle(side)\r\n end_fill()\r\n\r\n # leave if no more layers should be drawn\r\n if(remaining_layers - 1 == 0):\r\n return\r\n\r\n # draw left triangle\r\n penup()\r\n left(120)\r\n forward(side/2)\r\n right(120)\r\n pendown()\r\n colored_factorial_triangle_insides(remaining_layers - 1, side/2, colors)\r\n penup()\r\n right(60)\r\n forward(side)\r\n pendown()\r\n\r\n #draw right triangle\r\n left(60)\r\n colored_factorial_triangle_insides(remaining_layers - 1, side/2, colors)\r\n left(120)\r\n penup()\r\n forward(side/2)\r\n pendown()\r\n\r\n #draw top triangle\r\n right(90)\r\n penup()\r\n forward(side*sqrt(3)/2)\r\n pendown()\r\n right(30)\r\n colored_factorial_triangle_insides(remaining_layers - 1, side/2, colors)\r\n right(150)\r\n penup()\r\n forward(side*sqrt(3)/2)\r\n pendown()\r\n left(150)\r\n\r\n\r\n\r\ncolor_palletes = {\r\n \"black_shades\": {\"bgcolor\": \"#000000\", \"scheme\":[\"#000000\",\"#303030\", \"#5E5E5E\",\"#919191\",\"#C6C6C6\", \"#FFFFFF\"]},\r\n \"green_shades\": {\"bgcolor\": \"#005500\", \"scheme\":[\"#003400\",\"#005500\", \"#007A00\",\"#00A000\",\"#0CC82C\"]},\r\n \"red_shades\": {\"bgcolor\": \"#FF3E27\", \"scheme\":[\"#E70C0C\",\"#FF3E27\", \"#FF6041\",\"#FF7F5A\",\"#FF9D75\"]},\r\n \"blue_shades\": {\"bgcolor\": \"#6A50FF\", \"scheme\":[\"#372FE0\",\"#6A50FF\", \"#9571FF\",\"#BE94FF\",\"#E7B8FF\"]},\r\n \"brown_shades\": {\"bgcolor\": \"#AD5233\", \"scheme\":[\"#853115\",\"#AD5233\",\"#D57553\", \"#FE9975\",\"#FFBE98\"]},\r\n \"purple_shades\": {\"bgcolor\": \"#AB409B\", \"scheme\":[\"#851577\",\"#AB409B\", \"#D365C0\",\"#FB8AE6\",\"#FFB1FF\"]},\r\n}\r\n\r\n\r\nspeed(999)\r\n\r\n# start of a main triangle\r\nside = 800\r\n# offset triangle, so it gets drawn in the middle\r\npenup()\r\ngoto(-side/2, -side*sqrt(3)/4)\r\npendown()\r\n# pick color pallete\r\ncurrent_pallete = color_palletes[\"green_shades\"]\r\ncolor_scheme = current_pallete[\"scheme\"].copy()\r\nbgcolor(current_pallete[\"bgcolor\"])\r\n\r\ncolored_factorial_triangle(color_scheme,side)\r\n\r\n\r\nexitonclick()","repo_name":"TedRomato/factorial_triangle","sub_path":"factorial_triangle.py","file_name":"factorial_triangle.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"28948711469","text":"import pandas as pd\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\nimport scipy\nimport scipy.stats\nfrom scipy.stats import norm\nfrom scipy.linalg import solve\nfrom numpy.linalg import inv\nimport math\n\n\n# G2++ MODEL\n\ndef G2(T, dt, r0, x0, y0, sigma1, sigma2, a, b, rho, phi):\n n = int(round(T/dt))\n x = np.zeros(n)\n y = np.zeros(n)\n r = np.zeros(n)\n r[0] = r0\n x[0] = x0\n y[0] = y0\n for i in range(1,n):\n z = np.random.normal(0,1,2)\n w1 = z[0]\n w2 = rho*z[0] + np.sqrt(1-rho**2)*z[1]\n x[i] = x[i-1] - a*x[i-1]*dt + sigma1*np.sqrt(dt)*w1\n y[i] = y[i-1] - b*x[i-1]*dt + sigma2*np.sqrt(dt)*w2\n r[i] = x[i]+y[i]+phi\n \n R = dt*sum(r) # discount rate\n rt = r[n-1] # interest rate at T\n xt = x[n-1]\n yt = y[n-1]\n return R, rt, xt, yt\n\n \n# EUROPEAN PUT OPTION PRICE ON A PURE DISCOUNT BOND \n\ndef ep_g2_im(T_opt, K, T, dt, r0, x0, y0, sigma1, sigma2, a, b, rho, phi):\n put = []\n for i in range(0, 1000):\n R, rt, xt, yt = G2(T_opt, dt, r0, x0, y0, sigma1, sigma2, a, b, rho, phi)\n \n p = []\n for i in range(0,100):\n p.append(np.exp(-G2(T-T_opt, dt, rt, xt, yt, sigma1, sigma2, a, b, rho, phi)[0]))\n \n bond_price = np.mean(p)*1000\n payoff = max(K-bond_price, 0)\n put.append(payoff * np.exp(-R))\n \n return np.mean(put)\n","repo_name":"xinliny/Fixed-Income-Products-Pricing","sub_path":"G2++ Model.py","file_name":"G2++ Model.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"22238780794","text":"import re\nimport typing\n\nimport bs4\n\ntask_no_regex = re.compile(\n r\"document.write\\( '\\(№ (?P\\d+)\\) ' \\);\"\n)\ntask_raw_text_regex = task_raw_answer_regex = re.compile(\n r\"document.write\\( changeImageFilePath\\('(?P.+)'\\) \\);\"\n)\n\n\nclass RawTask(typing.NamedTuple):\n no: int\n raw_text: str\n raw_answer: str\n\n\ndef parse_to_raw_tasks(content: str) -> typing.List[RawTask]:\n soup = bs4.BeautifulSoup(content, \"html.parser\")\n tasks = soup.find_all(\"table\", class_=\"vartopic\")[0]\n tasks = typing.cast(bs4.Tag, tasks)\n tasks_blocks = tasks.find_all(\"tr\")\n tasks_content = [task.find_all(\"script\")[0].text for task in tasks_blocks]\n tasks_gen = iter(tasks_content)\n\n raw_tasks = []\n for task_data in tasks_gen:\n no = task_no_regex.search(task_data).group(\"task_no\")\n raw_text = task_raw_text_regex.search(task_data).group(\"raw_text\")\n answer_data = next(tasks_gen)\n raw_answer = task_raw_answer_regex.search(answer_data).group(\n \"raw_text\"\n )\n raw_task = RawTask(\n no=int(no), raw_text=raw_text, raw_answer=raw_answer\n )\n raw_tasks.append(raw_task)\n\n return raw_tasks\n","repo_name":"deknowny/polinfapi","sub_path":"polinfapi/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"} +{"seq_id":"26828526047","text":"import os\nimport shutil\nimport pyqrcode\nimport jinja2\n\nclass InventoryElement:\n\tdef __init__(self, count, code, item, company):\n\t\tself.count = int(count)\n\t\tself.code = code\n\t\tself.item = item\n\t\tself.company = company\n\ndef loadInventory():\n\twith open('inventory.txt') as input:\n\t\tlines = [line.rstrip() for line in input]\n\tdef getElement(offset):\n\t\treturn InventoryElement(*lines[offset:offset+4])\n\treturn [getElement(offset) for offset in range(0, len(lines), 5)]\n\ndef generateCodes(inventory):\n\tos.makedirs('output/codes')\n\tfor element in inventory:\n\t\tcode = pyqrcode.create(element.code)\n\t\tcode.svg('output/codes/' + element.code + '.svg')\n\ndef generateStickers(inventory):\n\tloader = jinja2.FileSystemLoader(searchpath='./')\n\tenvironment = jinja2.Environment(loader=loader)\n\ttemplate = environment.get_template('template/index.html')\n\trender = template.render(inventory = inventory)\n\twith open('output/index.html', 'w') as output:\n\t\toutput.write(render)\n\tshutil.copyfile('template/style.css', 'output/style.css')\n\ndef main():\n\tinventory = loadInventory()\n\tif os.path.exists('output'):\n\t\tshutil.rmtree('output')\n\tos.makedirs('output')\n\tgenerateCodes(inventory)\n\tgenerateStickers(inventory)\n\nif __name__ == \"__main__\":\n\tmain()","repo_name":"samuelmatn/inventory-stickers","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"74476722489","text":"from spark_streaming.utils.const import STREAM_NAME, AWS_REGION, AWS_ROLE_ARN, KINESIS_INITIAL_POSITION, B\nfrom pyspark.sql import SparkSession\n\n\nspark = SparkSession.builder.master(\n \"local[*, 4]\"\n).appName(\n \"StructureStream\"\n).enableHiveSupport(\n).getOrCreate()\n\n\ndef foreach_batch_function(df, epoch_id):\n if len(df.head(1)) != 0:\n df.write.mode(\n \"append\"\n ).parquet(\"s3a://{B}/data_test_package_table\")\n\n\ndef main():\n kinesis = spark.readStream \\\n .format(\"kinesis\") \\\n .option(\"streamName\", STREAM_NAME) \\\n .option(\"region\", AWS_REGION) \\\n .option(\"roleArn\", AWS_ROLE_ARN) \\\n .option(\"initialPosition\", KINESIS_INITIAL_POSITION) \\\n .load()\n\n df = kinesis.selectExpr(\n \"CAST(data as STRING) as json_data\"\n )\n\n df.writeStream \\\n .trigger(processingTime=\"5 seconds\") \\\n .option(\"checkpointLocation\", f\"s3a://{B}/test_package_checkpoint\") \\\n .foreachBatch(foreach_batch_function) \\\n .start()\n","repo_name":"ivandjuricic/spark_stream","sub_path":"spark_streaming/spark_streaming/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"40136187385","text":"# !/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@Author: 闫继龙\n@Version: ??\n@License: Apache Licence\n@CreateTime: 2021/1/31 17:48\n@Describe:\n 获取细粒度特征\n 通过kmeans获取簇心\n 使用余弦相似度判断动作相似度\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom pandas import DataFrame\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport torch.nn.functional as F\nfrom sklearn.decomposition import PCA\nimport math\nimport joblib\nfrom scipy.stats import mode\nfrom torchvision import models, transforms\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler,minmax_scale\nfrom sklearn.cluster import KMeans\nfrom sklearn.manifold import TSNE\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import pairwise_distances\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom torch import nn\nfrom dataToTorch import ActionDataSets\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nfrom d_Multi_NN_Net import MyMultiConvNet_2\nimport warnings\n\nwarnings.filterwarnings('ignore')\n\nstandScaler = StandardScaler(with_mean=True, with_std=True)\n\n\n# class MyMultiTempSpaceConfluenceNet(nn.Module):\n# \"\"\"\n# 时空卷积融合\n# \"\"\"\n#\n# def __init__(self, axis):\n# super(MyMultiTempSpaceConfluenceNet, self).__init__()\n#\n# self.axis = axis\n# self.temporal1_layer = nn.Sequential(\n# nn.Conv1d(in_channels=36, out_channels=256, kernel_size=1, stride=1, padding=0),\n# nn.BatchNorm1d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),\n# nn.ReLU(),\n# nn.Conv1d(256, 256, 3, 1, 2,dilation=2),\n# nn.BatchNorm1d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),\n# nn.ReLU(),\n# nn.Conv1d(256, 36, 1, 1, 0),\n# nn.BatchNorm1d(36, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),\n# nn.ReLU(),\n# # nn.AvgPool1d(2, 2)\n# ) # 输入大小(7*axis,36)\n# self.spatial2_layer = nn.Sequential(\n# nn.Conv2d(1, 128, 1, 1, 0),\n# nn.BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),\n# nn.ReLU(),\n# nn.Conv2d(128, 128, 3, 1, 2,dilation=2),\n# nn.BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),\n# nn.ReLU(),\n# nn.Conv2d(128, 1, 1, 1, 0),\n# nn.BatchNorm2d(1, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),\n# nn.ReLU(),\n# # nn.AvgPool1d(2, 2)\n# ) # 128*18\n#\n# self.confluence3_layer = nn.Sequential(\n# nn.Conv2d(1, 128, 2, 1, 1),\n# nn.Dropout2d(0.5),\n# nn.BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),\n# nn.ReLU(),\n# nn.AvgPool2d(2, 2)\n# ) # 256*9\n#\n# self.confluence4_layer = nn.Sequential(\n# nn.Conv2d(128, 256, 2, 1, 1),\n# nn.Dropout2d(0.5),\n# nn.BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),\n# nn.ReLU(),\n# nn.AvgPool2d(2, 2)\n# ) # 256*9\n#\n# self.classifier = nn.Sequential(\n# nn.Linear(256 * (math.ceil((7 * axis) / 4)) * 9, 5),\n# )\n#\n# def forward(self, x):\n# x_1d = x.permute([0,2,1])\n# temp = self.temporal1_layer(x_1d)\n# temp = temp.unsqueeze(0).permute([1, 0, 3, 2])\n#\n# x_2d = x.unsqueeze(0).permute([1, 0, 2, 3]) # 扩展一个维度\n# space = self.spatial2_layer(x_2d)\n#\n# input = temp + space # [64, 1, 42, 36]\n# # input_2d = input.unsqueeze(0).permute([1, 0, 2, 3]) # 扩展一个维度\n#\n# out = self.confluence3_layer(input)\n# out = self.confluence4_layer(out)\n# out = out.view(out.size(0), -1)\n# out = self.classifier(out)\n# return out\n\n\nclass Extract_1D_2D_features():\n def __init__(self, model, model_name, axis, data_category):\n super(Extract_1D_2D_features, self).__init__()\n\n self.model = model\n self.axis = axis\n self.data_category = data_category\n\n self.device = torch.device('cuda:1' if torch.cuda.is_available() else 'cpu')\n\n self.model.load_state_dict(torch.load(f'src/model/{model_name}_{axis}_model.pkl', map_location='cpu'))\n if torch.cuda.is_available():\n self.model.to(self.device)\n self.model.eval()\n action_data_set = ActionDataSets(data_category, axis)\n\n # 按批加载 pyTorch张量\n self.action_train_data_gen = DataLoader(action_data_set, shuffle=True,\n num_workers=2) # 分成数组(len/128)个batch,每个batch长度是128\n print(f'{data_category}data shape: ({len(action_data_set)}{(action_data_set.data_shape())})')\n\n def extract_features(self):\n print(f'============== 提取{self.data_category}-{self.axis}的卷积特征=============')\n features_action0 = []\n features_action1 = []\n features_action2 = []\n features_action3 = []\n features_action4 = []\n\n for inputs in self.action_train_data_gen:\n\n data, label = inputs\n label = int(label)\n\n output, mix_data = self.model(data)\n mix_data = mix_data.squeeze(0).detach().numpy()\n fusion_features = mix_data.flatten().tolist()\n\n if label == 0:\n features_action0.append(fusion_features)\n elif label == 1:\n features_action1.append(fusion_features)\n elif label == 2:\n features_action2.append(fusion_features)\n elif label == 3:\n features_action3.append(fusion_features)\n elif label == 4:\n features_action4.append(fusion_features)\n else:\n print(label)\n\n features_action0 = np.array(features_action0)\n features_action1 = np.array(features_action1)\n features_action2 = np.array(features_action2)\n features_action3 = np.array(features_action3)\n features_action4 = np.array(features_action4)\n\n print(f'features_action0.shape:{features_action0.shape}')\n print(f'features_action1.shape:{features_action1.shape}')\n print(f'features_action2.shape:{features_action2.shape}')\n print(f'features_action3.shape:{features_action3.shape}')\n print(f'features_action4.shape:{features_action4.shape}')\n\n np.save(f'src/fine_grained_features/conv1d_2d_features/{self.data_category}_features_{self.axis}_action0.npy',\n features_action0)\n np.save(f'src/fine_grained_features/conv1d_2d_features/{self.data_category}_features_{self.axis}_action1.npy',\n features_action1)\n np.save(f'src/fine_grained_features/conv1d_2d_features/{self.data_category}_features_{self.axis}_action2.npy',\n features_action2)\n np.save(f'src/fine_grained_features/conv1d_2d_features/{self.data_category}_features_{self.axis}_action3.npy',\n features_action3)\n np.save(f'src/fine_grained_features/conv1d_2d_features/{self.data_category}_features_{self.axis}_action4.npy',\n features_action4)\n\n\nclass Kmeans_fine_grained():\n def __init__(self, axis, action_name, data_category):\n\n self.axis = axis\n self.action_name = action_name\n self.data_category = data_category\n\n # if data_category == 'train':\n # fusion_features_path = f'src/fine_grained_features/conv1d_2d_features/{data_category}_features_{axis}_{action_name}.npy'\n # self.fusion_features = np.load(fusion_features_path)\n # else:\n # fusion_features_path = f'src/fine_grained_features/conv1d_2d_features/test_features_{axis}_{action_name}.npy'\n # self.fusion_features = np.load(fusion_features_path)\n\n fusion_features_path = f'src/fine_grained_features/conv1d_2d_features/{data_category}_features_{axis}_{action_name}.npy'\n self.fusion_features = np.load(fusion_features_path)\n\n self.Tsne = TSNE(n_components=3, init='pca', random_state=0)\n\n self.Kmeans = KMeans(n_clusters=7, random_state=0)\n\n def get_tsne_data(self):\n \"\"\"\n 获取降维后的节点数据\n :return:\n \"\"\"\n print(f'======== 获取tsne降维数据 {self.data_category}_{self.axis}_{self.action_name} =============')\n data = []\n targets = []\n for fusion_feature in self.fusion_features: # 动作数据\n fusion_feature = fusion_feature.reshape(-1, int(self.axis[0]), 36) # (7, 6, 36)\n for label, feature in enumerate(fusion_feature):\n feature = feature.flatten()\n targets.append(label)\n data.append(feature)\n\n data = np.array(data)\n targets = np.array(targets)\n print(data.shape)\n\n if self.data_category == 'train':\n tsne_fit = self.Tsne.fit(data)\n tsne_params = tsne_fit.get_params()\n np.save(f'src/fine_grained_features/tsne_model/tsne_params_{self.axis}.npy', tsne_params)\n else:\n tsne_params_value = np.load(f'src/fine_grained_features/tsne_model/tsne_params_{self.axis}.npy',\n allow_pickle=True).item()\n\n self.Tsne.set_params(**tsne_params_value)\n\n tsne_data = self.Tsne.fit_transform(data)\n\n # self.matplotlib(tsne_data)\n\n tsne_data_targets = []\n for index, tsne in enumerate(tsne_data):\n data_target = np.append(tsne, targets[index])\n tsne_data_targets.append(data_target.tolist())\n\n tsne_data_targets = np.array(tsne_data_targets)\n\n print(tsne_data_targets.shape)\n print(f'{self.data_category}_tsne_data_{self.axis}_{self.action_name} shape:{tsne_data_targets.shape}')\n np.save(\n f'src/fine_grained_features/tsne_data/{self.data_category}_tsne_data_{self.axis}_{self.action_name}.npy',\n tsne_data_targets)\n\n def train_kmeans(self):\n data_targets_path = f'src/fine_grained_features/tsne_data/train_tsne_data_{self.axis}_{self.action_name}.npy'\n data_targets = np.load(data_targets_path)\n tsne_data = data_targets[:, :3]\n tsne_targets = data_targets[:, 3]\n\n tsne_data = minmax_scale(tsne_data)\n\n kmeans_model = self.Kmeans.fit(tsne_data)\n joblib.dump(kmeans_model,\n f'src/fine_grained_features/kmeans_model/kmeans_model_{self.axis}_{self.action_name}.pkl')\n\n kmeans_cluster = kmeans_model.cluster_centers_ # 聚类的核心\n predicted = kmeans_model.predict(tsne_data)\n kmeans_cluster_label_dict = {} # 保存聚类后的簇心,和标签值\n\n # 聚类结果\n kmeans_data = np.c_[tsne_data, predicted]\n\n # 排列标签\n labels = np.zeros_like(predicted)\n for i in range(7):\n mask = (predicted == i)\n labels[mask] = mode(tsne_targets[mask])[0]\n kmeans_cluster_label = int(mode(tsne_targets[mask])[0][0])\n kmeans_cluster_label_dict[f'sensor-{kmeans_cluster_label}'] = kmeans_cluster[i]\n # print(kmeans_cluster_label_dict)\n\n np.save(\n f'src/fine_grained_features/cluster_label_dict/cluster_label_dict_{self.axis}_{self.action_name}.npy',\n kmeans_cluster_label_dict)\n np.save(\n f'src/fine_grained_features/kmeans_data/{self.data_category}_kmeans_data_{self.axis}_{self.action_name}.npy',\n kmeans_data)\n # 计算准确度\n accuracy = accuracy_score(tsne_targets, labels)\n print(f'train_{self.axis}_{self.action_name} accuracy:{accuracy}')\n\n def predict_kmeans(self):\n data_targets_path = f'src/fine_grained_features/tsne_data/test_tsne_data_{self.axis}_{self.action_name}.npy'\n data_targets = np.load(data_targets_path)\n tsne_data = data_targets[:, :3]\n tsne_targets = data_targets[:, 3]\n\n tsne_data = minmax_scale(tsne_data)\n\n kmeans_model = joblib.load(\n f'src/fine_grained_features/kmeans_model/kmeans_model_{self.axis}_{self.action_name}.pkl')\n\n predicted = kmeans_model.predict(tsne_data)\n\n # 聚类结果\n kmeans_data = np.c_[tsne_data, predicted]\n\n # 排列标签\n labels = np.zeros_like(predicted)\n for i in range(7):\n mask = (predicted == i)\n labels[mask] = mode(tsne_targets[mask])[0]\n\n # 计算准确度\n accuracy = accuracy_score(tsne_targets, labels)\n print(f'test_{self.axis}_{self.action_name} accuracy:{accuracy}')\n np.save(\n f'src/fine_grained_features/kmeans_data/{self.data_category}_kmeans_data_{self.axis}_{self.action_name}.npy',\n kmeans_data)\n\n\nclass FG__vector_Predict_with_kmeans():\n def __init__(self, axis, action_name):\n self.axis = axis\n # self.action_name = action_name\n\n self.Tsne = TSNE(n_components=3, init='pca', random_state=0)\n\n self.kmeans_model_action0 = joblib.load(\n f'src/fine_grained_features/kmeans_model/kmeans_model_{self.axis}_action0.pkl')\n self.kmeans_model_action1 = joblib.load(\n f'src/fine_grained_features/kmeans_model/kmeans_model_{self.axis}_action1.pkl')\n self.kmeans_model_action2 = joblib.load(\n f'src/fine_grained_features/kmeans_model/kmeans_model_{self.axis}_action2.pkl')\n self.kmeans_model_action3 = joblib.load(\n f'src/fine_grained_features/kmeans_model/kmeans_model_{self.axis}_action3.pkl')\n self.kmeans_model_action4 = joblib.load(\n f'src/fine_grained_features/kmeans_model/kmeans_model_{self.axis}_action4.pkl')\n\n self.modelNet = MyMultiConvNet_2(int(axis[0]))\n\n self.modelNet.load_state_dict(torch.load(f'src/model/MyMultiConvNet_2_{axis}_model.pkl', map_location='cpu'))\n self.modelNet.eval()\n\n self.toTensor = transforms.ToTensor()\n\n self.all_cluster_label_dict = np.load(\n f'src/fine_grained_features/cluster_label_dict/all_cluster_label_dict_{self.axis}.npy',\n allow_pickle=True).item()\n # print(self.all_cluster_label_dict)\n # for k,v in self.all_cluster_label_dict.items():\n # print(k,v)\n\n def calculate_fg_with_test_window_data(self):\n data_targets_path = f'D:/home/DataRec/action_windows-{self.axis}/action_window_1.csv'\n\n data_mat = pd.read_csv(data_targets_path, dtype=float, header=0).round(3)\n data_mat = np.array(data_mat)[:, 1:-1]\n\n data_mat = data_mat[:int(len(data_mat) / 36) * 36, :] # 确保是窗口长度的倍数\n data_mat = np.reshape(data_mat, (-1, 36, int(self.axis[0]) * 7))\n # print(data_mat.shape)\n data_mat = data_mat[:200, :, ] # 每个动作取200个\n\n for df in data_mat:\n data = np.array(df)[:, :].T # 转为42*36 data = np.array(df)[2:-2, :].T # 转为36*63\n data = standScaler.fit_transform(data)\n data = self.toTensor(data)\n data = data.to(torch.float32)\n # data = data.unsqueeze(0) # 扩展一个维度\n output, mix_data = self.modelNet(data)\n\n prob = F.softmax(output, dim=1)\n action_score = torch.max(prob, 1)[0].data.numpy()[0]\n action_class = torch.max(prob, 1)[1].data.numpy()[0] # 最大值下标\n\n # 计算细粒度\n mix_data = mix_data.squeeze(0).detach().numpy()\n fusion_features = mix_data.flatten()\n fusion_features = fusion_features.reshape(-1, int(self.axis[0]), 36)\n\n true_node_labels = []\n fusion_data = []\n for node_label, feature in enumerate(fusion_features):\n feature = feature.flatten()\n true_node_labels.append(node_label)\n fusion_data.append(feature)\n\n tsne_data = self.Tsne.fit_transform(np.array(fusion_data))\n tsne_data = np.array(tsne_data, dtype=np.float16)\n # print(tsne_data)\n\n cluster_label_dict = self.all_cluster_label_dict[f'action{action_class}']\n cluster_keys = cluster_label_dict.keys()\n\n vector_scores = []\n for index in range(7):\n sensor_num = f'sensor-{index}'\n if sensor_num in cluster_keys:\n # 余弦相似度\n vector_score = self.cosine_similarity_method(tsne_data[index], cluster_label_dict[sensor_num])\n # vector_score = self.distance_seuclidean(tsne_data[index], cluster_label_dict[sensor_num])\n else:\n vector_score = 0.8\n vector_scores.append(round(vector_score, 1))\n\n print(vector_scores)\n\n # if action_class == 0:\n # kmeans_predicted = self.kmeans_model_action0.predict(tsne_data)\n # elif action_class == 1:\n # kmeans_predicted = self.kmeans_model_action1.predict(tsne_data)\n # elif action_class == 2:\n # kmeans_predicted = self.kmeans_model_action2.predict(tsne_data)\n # elif action_class == 3:\n # kmeans_predicted = self.kmeans_model_action3.predict(tsne_data)\n # elif action_class == 4:\n # kmeans_predicted = self.kmeans_model_action4.predict(tsne_data)\n # else:\n # kmeans_predicted = 'error'\n #\n # vector_scores = []\n # for index,kmeans_v in enumerate(kmeans_predicted):\n # sensor_num = f'sensor-{kmeans_v}'\n # # 余弦相似度\n # vector_score = self.cosine_similarity(tsne_data[index], cluster_label_dict[sensor_num])\n # # vector_score = self.distance_seuclidean(tsne_data[index], cluster_label_dict[sensor_num])\n # vector_scores.append(round(vector_score, 1))\n #\n # print(vector_scores)\n\n def distance_seuclidean(self, x, y):\n X = np.vstack([x, y])\n distance = pairwise_distances(X, metric='seuclidean')\n # distance = pairwise_distances(X, metric='mahalanobis')\n return distance[0][1]\n\n def cosine_similarity_method(self, x, y, norm=True):\n \"\"\" 计算两个向量x和y的余弦相似度 \"\"\"\n # 计算余弦相似度\n # assert len(x) == len(y), \"len(x) != len(y)\"\n # zero_list = [0] * len(x)\n # zero_list = np.array(zero_list)\n # if x.all() == zero_list.all() or y.all() == zero_list.all():\n # return float(1) if x.all() == y.all() else float(0)\n #\n # # method 1\n # res = np.array([[x[i] * y[i], x[i] * x[i], y[i] * y[i]] for i in range(len(x))])\n # cos = sum(res[:, 0]) / (np.sqrt(sum(res[:, 1])) * np.sqrt(sum(res[:, 2])))\n x = minmax_scale(x)\n X = np.vstack([np.abs(x), np.abs(y)])\n cos = cosine_similarity(X)[0][1]\n return cos\n # return 0.5 * cos + 0.5 if norm else cos # 归一化到[0, 1]区间内\n\n\nclass Get_cluster_label_dict():\n \"\"\"\n 将不同动作、不同传感器的kmeans簇新组合成一个完整的字典\n \"\"\"\n\n def __init__(self, axis):\n super(Get_cluster_label_dict, self).__init__()\n self.axis = axis\n\n def getClusterLabelDict(self):\n actions_all = ['action0', 'action1', 'action2', 'action3', 'action4']\n all_cluster_label_dict = {}\n for action_name in actions_all:\n dict_path = f'src/fine_grained_features/cluster_label_dict/cluster_label_dict_{self.axis}_{action_name}.npy'\n cluster_label_dict = np.load(dict_path, allow_pickle=True).item()\n all_cluster_label_dict[action_name] = cluster_label_dict\n print(all_cluster_label_dict)\n np.save(f'src/fine_grained_features/cluster_label_dict/all_cluster_label_dict_{self.axis}.npy',\n all_cluster_label_dict)\n\n\nclass Matplotlib_tsne():\n def __init__(self):\n pass\n\n def matplotlib(self):\n print(f'======== 绘制三维图像 =============')\n axiss = ['6axis', '9axis']\n data_category = ['train', 'valid']\n actions_all = ['action0', 'action1', 'action2', 'action3', 'action4']\n\n for axis in axiss:\n plt.figure(figsize=(20, 14), dpi=516)\n plt.style.use('seaborn')\n for index, action_name in enumerate(actions_all):\n data_targets_path = f'src/fine_grained_features/kmeans_data/train_kmeans_data_{axis}_{action_name}.npy'\n data_targets = np.load(data_targets_path)\n\n # train_data_targets_path = f'src/fine_grained_features/tsne_data/train_tsne_data_{axis}_{action_name}.npy'\n # valid_data_targets_path = f'src/fine_grained_features/tsne_data/valid_tsne_data_{axis}_{action_name}.npy'\n # test_data_targets_path = f'src/fine_grained_features/tsne_data/test_tsne_data_{axis}_{action_name}.npy'\n # train_data_targets = np.load(train_data_targets_path)\n # valid_data_targets = np.load(valid_data_targets_path)\n # test_data_targets = np.load(test_data_targets_path)\n # data_targets = np.r_[train_data_targets,valid_data_targets,test_data_targets]\n\n # tsne_data = data_targets[:, :3]\n # tsne_label = data_targets[:, 3]\n # tsne_data_stand = MinMaxScaler().fit_transform(tsne_data)\n # data_targets = np.c_[tsne_data, tsne_label]\n\n tsne_data_node0 = np.array([x for x in data_targets if x[3] == 0])\n tsne_data_node1 = np.array([x for x in data_targets if x[3] == 1])\n tsne_data_node2 = np.array([x for x in data_targets if x[3] == 2])\n tsne_data_node3 = np.array([x for x in data_targets if x[3] == 3])\n tsne_data_node4 = np.array([x for x in data_targets if x[3] == 4])\n tsne_data_node5 = np.array([x for x in data_targets if x[3] == 5])\n tsne_data_node6 = np.array([x for x in data_targets if x[3] == 6])\n print(tsne_data_node0.shape)\n # ax = Axes3D(fig)\n # plt.title=('{self.action_name}-{self.axis} scatter plot')\n ax = plt.subplot(2, 3, index + 1, projection='3d')\n # 调整视角\n ax.view_init(elev=20, azim=30) # 仰角,方位角\n\n ax.scatter(tsne_data_node0[:, 0], tsne_data_node0[:, 1], tsne_data_node0[:, 2], c='r', label='sensor-0')\n ax.scatter(tsne_data_node1[:, 0], tsne_data_node1[:, 1], tsne_data_node1[:, 2], c='y', label='sensor-1')\n ax.scatter(tsne_data_node2[:, 0], tsne_data_node2[:, 1], tsne_data_node2[:, 2], c='m', label='sensor-2')\n ax.scatter(tsne_data_node3[:, 0], tsne_data_node3[:, 1], tsne_data_node3[:, 2], c='g', label='sensor-3')\n ax.scatter(tsne_data_node4[:, 0], tsne_data_node4[:, 1], tsne_data_node4[:, 2], c='b', label='sensor-4')\n ax.scatter(tsne_data_node5[:, 0], tsne_data_node5[:, 1], tsne_data_node5[:, 2], c='k', label='sensor-5')\n ax.scatter(tsne_data_node6[:, 0], tsne_data_node6[:, 1], tsne_data_node6[:, 2], c='orange',\n label='sensor-6')\n\n # ax.set_title(f'{self.action_name}-{self.axis} scatter plot')\n ax.set_zlabel('X', fontsize=20) # 坐标轴\n ax.set_ylabel('Y', fontsize=20)\n ax.set_xlabel('Z', fontsize=20)\n ax.legend()\n plt.subplots_adjust(hspace=0.4)\n plt.title(f'{action_name}', fontsize=30)\n plt.legend()\n plt.savefig(f'src/fine_grained_features/tsne_plt/tense_plt_scatter-{axis}.jpg',bbox_inches='tight')\n # plt.show()\n plt.close()\n\n\nif __name__ == '__main__':\n\n axis_all = ['6axis', '9axis']\n data_categorys = ['train', 'test']\n for axis in axis_all:\n myMultiConvNet_2 = MyMultiConvNet_2(int(axis[0]))\n\n models_all = {'myMultiConvNet_2': myMultiConvNet_2}\n\n for model_name, model in models_all.items():\n for data_category in data_categorys:\n # 抽取训练集、测试集多维度卷积融合特征\n extractFeatures = Extract_1D_2D_features(model,model_name, axis, data_category=data_category)\n # extractFeatures.extract_features()\n\n actions_all = ['action0', 'action1', 'action2', 'action3', 'action4']\n\n for axis in axis_all:\n for action_name in actions_all:\n # 降维后做kmeans训练\n kmeans_fine_grained = Kmeans_fine_grained(axis, action_name, data_category='train')\n # kmeans_fine_grained.get_tsne_data()\n kmeans_fine_grained.train_kmeans()\n\n for axis in axis_all:\n for action_name in actions_all:\n # 降维后做kmeans训练\n kmeans_fine_grained = Kmeans_fine_grained(axis, action_name, data_category='test')\n # kmeans_fine_grained.get_tsne_data()\n kmeans_fine_grained.predict_kmeans()\n\n # 绘制三维视图\n matplotlib_tsne = Matplotlib_tsne()\n matplotlib_tsne.matplotlib()\n\n for axis in axis_all:\n get_cluster_label_dict = Get_cluster_label_dict(axis)\n get_cluster_label_dict.getClusterLabelDict()\n\n fg_vector_Predict_with_kmeans = FG__vector_Predict_with_kmeans('9axis', 'action0')\n fg_vector_Predict_with_kmeans.calculate_fg_with_test_window_data()\n\n","repo_name":"cnyan/PytorchBasic","sub_path":"action_recog_with_function/dataRec/fg_cnn_fine_grained.py","file_name":"fg_cnn_fine_grained.py","file_ext":"py","file_size_in_byte":25730,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"20715124444","text":"#! /usr/bin/env python3 \n\n\n# import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n# import scipy\n\n\nclass DiscreteRandomVariable:\n def __init__(self, a: int = 0, b : int = 1):\n self.variableType = \"\"\n self.low = a\n self.high = b\n return\n def draw(self, numberOfSamples : int):\n samples = np.random.randint(self.low, self.high, numberOfSamples)\n return samples\n\nDieRolls = DiscreteRandomVariable(1, 6)\nplt.hist(DieRolls.draw(10000), bins = [1,2,3,4,5,6,7], align = 'mid')\nplt.xlabel('Value')\nplt.ylabel('Occurrences')\nplt.legend(['Die Rolls'])\nplt.savefig(\"dice.png\", dpi=200)","repo_name":"muhammedogz/GTU-University-Assignments","sub_path":"MATH118 - Statistics and Probability/Final_Presentation/Random Variables/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":73,"dataset":"github-code","pt":"77"} +{"seq_id":"32808702643","text":"# https://leetcode.com/contest/weekly-contest-171/problems/minimum-flips-to-make-a-or-b-equal-to-c/\n\nclass Solution:\n def minFlips(self, a: int, b: int, c: int) -> int:\n bin_a = bin(a).replace(\"0b\", \"\")\n bin_b = bin(b).replace(\"0b\", \"\")\n bin_c = bin(c).replace(\"0b\", \"\")\n max_len = max([len(bin_a), len(bin_b), len(bin_c)])\n while len(bin_a) < max_len:\n bin_a = '0' + bin_a\n while len(bin_b) < max_len:\n bin_b = '0' + bin_b\n while len(bin_c) < max_len:\n bin_c = '0' + bin_c\n ans = 0\n for i in range(max_len):\n x, y, z = int(bin_a[i]), int(bin_b[i]), int(bin_c[i])\n if (x | y) == z:\n continue\n elif (((1-x) | y) == z) or ((x | (1-y)) == z):\n ans += 1\n else:\n ans += 2\n return ans","repo_name":"rmodi6/scripts","sub_path":"practice/Leetcode/1318_minimum_flips_to_make_a_or_b_equal_to_c.py","file_name":"1318_minimum_flips_to_make_a_or_b_equal_to_c.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":"73352291769","text":"\"\"\"empty message\n\nRevision ID: 234c17fafece\nRevises: 7785468819b2\nCreate Date: 2021-04-17 05:12:14.749823\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = '234c17fafece'\ndown_revision = '7785468819b2'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('favorites', sa.Column('people_id', sa.Integer(), nullable=False))\n op.drop_column('favorites', 'peopler_id')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('favorites', sa.Column('peopler_id', mysql.INTEGER(), autoincrement=False, nullable=False))\n op.drop_column('favorites', 'people_id')\n # ### end Alembic commands ###\n","repo_name":"Gab20031995/StarWars_Blog_API-Final","sub_path":"migrations/versions/234c17fafece_.py","file_name":"234c17fafece_.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"36627251861","text":"import csv\nimport datetime\nimport logging\nimport os\nimport os.path\nimport sys\nimport typing\n\n# Third-party imports\nimport matplotlib.pyplot as plt\n\n# Local imports\nimport palmsens.instrument\nimport palmsens.mscript\nimport palmsens.serial\n\n\n###############################################################################\n# Start of configuration\n###############################################################################\n\n# COM port of the device (None = auto detect).\nDEVICE_PORT = None\n\n# Location of MethodSCRIPT file to use.\nMSCRIPT_FILE_PATH_ES4 = 'scripts/example_advanced_swv_es4.mscr'\nMSCRIPT_FILE_PATH_ESPICO = 'scripts/example_advanced_swv_espico.mscr'\n\n# Location of output files. Directory will be created if it does not exist.\nOUTPUT_PATH = 'output'\n\n# In this example, columns refer to the separate \"pck_add\" entries in each\n# MethodSCRIPT data package. For example, in the used script there are\n# four columns per data package:\n# pck_start\n# pck_add p\n# pck_add c\n# pck_add f\n# pck_add r\n# pck_end\n# Here, the indices 0/1/2/3 refer to the variables p/c/f/r/ respectively.\n# The following variables define which columns (i.e. variables) to plot, and\n# how they are named in the figure.\n\n# Column names.\nCOLUMN_NAMES = ['Potential', 'Current', 'Forward Current', 'Reverse Current']\n# Index of column to put on the x axis.\nXAXIS_COLUMN_INDEX = 0\n# Indices of columns to put on the y axis. The variables must be same type.\nYAXIS_COLUMN_INDICES = [1, 2, 3]\n\n###############################################################################\n# End of configuration\n###############################################################################\n\n\nLOG = logging.getLogger(__name__)\n\n\ndef write_curves_to_csv(file: typing.IO, curves: list[list[list[palmsens.mscript.MScriptVar]]]):\n \"\"\"Write the curves to file in CSV format.\n\n `file` must be a file-like object in text mode with newlines translation\n disabled.\n\n The header row is based on the first row of the first curve. It is assumed\n that all rows in all curves have the same data types.\n \"\"\"\n # NOTE: Although the extension is CSV, which stands for Comma Separated\n # Values, a semicolon (';') is used as delimiter. This is done to be\n # compatible with MS Excel, which may use a comma (',') as decimal\n # separator in some regions, depending on regional settings on the\n # computer. If you use anoter program to read the CSV files, you may need\n # to change this. The CSV writer can be configured differently to support\n # a different format. See\n # https://docs.python.org/3/library/csv.html#csv.writer for all options.\n # NOTE: The following line writes a Microsoft Excel specific header line to\n # the CSV file, to tell it we use a semicolon as delimiter. If you don't\n # use Excel to read the CSV file, you might want to remove this line.\n file.write('sep=;\\n')\n writer = csv.writer(file, delimiter=';')\n for curve in curves:\n # Write header row.\n writer.writerow([f'{value.type.name} [{value.type.unit}]' for value in curve[0]])\n # Write data rows.\n for package in curve:\n writer.writerow([value.value for value in package])\n\n\ndef main():\n \"\"\"Run the example.\"\"\"\n # Configure the logging.\n logging.basicConfig(level=logging.DEBUG, format='[%(module)s] %(message)s',\n stream=sys.stdout)\n # Uncomment the following line to reduce the log level of our library.\n # logging.getLogger('palmsens').setLevel(logging.INFO)\n # Disable excessive logging from matplotlib.\n logging.getLogger('matplotlib').setLevel(logging.INFO)\n logging.getLogger('PIL.PngImagePlugin').setLevel(logging.INFO)\n\n # Determine unique name for plot and files.\n base_name = datetime.datetime.now().strftime('ms_plot_swv_%Y%m%d-%H%M%S')\n # Base path contains directory and base name. Extension is appended later.\n base_path = os.path.join(OUTPUT_PATH, base_name)\n\n port = DEVICE_PORT\n if port is None:\n port = palmsens.serial.auto_detect_port()\n\n # Create and open serial connection to the device.\n with palmsens.serial.Serial(port, 1) as comm:\n device = palmsens.instrument.Instrument(comm)\n device_type = device.get_device_type()\n LOG.info('Connected to %s.', device_type)\n\n if device_type == palmsens.instrument.DeviceType.EMSTAT_PICO:\n mscript_file_path = MSCRIPT_FILE_PATH_ESPICO\n elif 'EmStat4' in device_type:\n mscript_file_path = MSCRIPT_FILE_PATH_ES4\n else:\n LOG.error('No SWV script for this device found.')\n return\n\n # Read and send the MethodSCRIPT file.\n LOG.info('Sending MethodSCRIPT.')\n device.send_script(mscript_file_path)\n\n # Read the result lines.\n LOG.info('Waiting for results.')\n result_lines = device.readlines_until_end()\n\n # Store results in file.\n os.makedirs(OUTPUT_PATH, exist_ok=True)\n with open(base_path + '.txt', 'wt', encoding='ascii') as file:\n file.writelines(result_lines)\n\n # Parse the result.\n curves = palmsens.mscript.parse_result_lines(result_lines)\n\n # Store results in CSV format.\n with open(base_path + '.csv', 'wt', newline='', encoding='ascii') as file:\n write_curves_to_csv(file, curves)\n\n # Create and configure a plot for the results.\n plt.figure()\n plt.title(base_name)\n # Put specified column of the first curve on x axis.\n xvar = curves[0][0][XAXIS_COLUMN_INDEX]\n plt.xlabel(f'{xvar.type.name} [{xvar.type.unit}]')\n # Put specified column of the first curve on y axis.\n yvar = curves[0][0][YAXIS_COLUMN_INDICES[0]]\n plt.ylabel(f'{yvar.type.name} [{yvar.type.unit}]')\n plt.grid(visible=True, which='major', linestyle='-')\n plt.grid(visible=True, which='minor', linestyle='--', alpha=0.2)\n plt.minorticks_on()\n\n # Loop through all curves and plot them.\n for icurve, curve in enumerate(curves):\n # Get xaxis column for this curve.\n xvalues = palmsens.mscript.get_values_by_column(\n curves, XAXIS_COLUMN_INDEX, icurve)\n # Loop through all y axis columns and plot one curve per column.\n for yaxis_column_index in YAXIS_COLUMN_INDICES:\n yvalues = palmsens.mscript.get_values_by_column(\n curves, yaxis_column_index, icurve)\n\n # Ignore invalid columns.\n if curve[0][yaxis_column_index].type != yvar.type:\n continue\n\n # Make plot label.\n label = f'{COLUMN_NAMES[yaxis_column_index]} vs {COLUMN_NAMES[XAXIS_COLUMN_INDEX]}'\n # If there are multiple curves, add the curve index to the label.\n if len(curves) > 1:\n label += f' {icurve}'\n\n # Plot the curve y axis against the global x axis.\n plt.plot(xvalues, yvalues, label=label)\n\n # Generate legend.\n plt.legend()\n\n plt.savefig(base_path + '.png')\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"PalmSens/MethodSCRIPT_Examples","sub_path":"MethodSCRIPTExample_Python/MethodSCRIPTExample_Python/plot_advanced_swv.py","file_name":"plot_advanced_swv.py","file_ext":"py","file_size_in_byte":7016,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"77"} +{"seq_id":"16907550500","text":"\"\"\"pytest tests for mytoyota.client.MyT\"\"\"\n\nimport asyncio\nimport datetime\nimport json\nimport os.path\nimport re\nfrom typing import Optional, Union\n\nimport arrow\nimport pytest # pylint: disable=import-error\n\nfrom mytoyota.client import MyT\nfrom mytoyota.exceptions import (\n ToyotaActionNotSupported,\n ToyotaInternalError,\n ToyotaInvalidUsername,\n ToyotaLocaleNotValid,\n ToyotaRegionNotSupported,\n)\nfrom mytoyota.models.trip import DetailedTrip, Trip, TripEvent\n\n# pylint: disable=no-self-use\n\n\nclass OfflineController:\n \"\"\"Provides a Controller class that can be used for testing.\"\"\"\n\n def __init__(\n self,\n locale: str,\n region: str,\n username: str,\n password: str,\n brand: str,\n uuid: str = None,\n ) -> None:\n self._locale = locale\n self._region = region\n self._username = username\n self._password = password\n self._brand = brand\n self._uuid = uuid\n\n @property\n def uuid(self) -> str:\n \"\"\"Returns uuid\"\"\"\n return \"_OfflineController_\"\n\n async def first_login(self) -> None:\n \"\"\"Perform first login\"\"\"\n # This is no-operation\n\n def _load_from_file(self, filename: str):\n \"\"\"Load a data structure from the specified JSON filename, and\n return it.\"\"\"\n with open(filename, encoding=\"UTF-8\") as json_file:\n return json.load(json_file)\n\n # Disables pylint warning about too many statements and branches when matching API paths\n async def request( # pylint: disable=too-many-statements, too-many-branches, too-many-locals\n self,\n method: str,\n endpoint: str,\n base_url: Optional[str] = None,\n body: Optional[dict] = None,\n params: Optional[dict] = None,\n headers: Optional[dict] = None,\n ) -> Union[dict, list, None]:\n \"\"\"Shared request method\"\"\"\n\n if method not in (\"GET\", \"POST\", \"PUT\", \"DELETE\"):\n raise ToyotaInternalError(\n \"Invalid request method provided\"\n ) # pragma: no cover\n\n _ = base_url\n\n data_files = os.path.join(os.path.curdir, \"tests\", \"data\")\n\n response = None\n\n match = re.match(r\"/api/users/.*/vehicles/.*\", endpoint)\n if match:\n # A new alias is set\n # We should return a predefined dictionary\n response = {\"id\": str(body[\"id\"]), \"alias\": body[\"alias\"]}\n\n match = re.match(r\".*/vehicles\\?.*services=uio\", endpoint)\n if match:\n response = self._load_from_file(os.path.join(data_files, \"vehicles.json\"))\n\n match = re.match(\n r\"/vehicle/user/.*/vehicle/([^?]+)\\?.*services=fud,connected\", endpoint\n )\n if match:\n vin = match.group(1)\n response = self._load_from_file(\n os.path.join(data_files, f\"vehicle_{vin}_connected_services.json\")\n )\n\n match = re.match(r\".*/vehicle/([^/]+)/addtionalInfo\", endpoint)\n if match:\n vin = match.group(1)\n response = self._load_from_file(\n os.path.join(data_files, f\"vehicle_{vin}_odometer.json\")\n )\n\n match = re.match(r\".*/vehicles/([^/]+)/vehicleStatus\", endpoint)\n if match:\n vin = match.group(1)\n response = self._load_from_file(\n os.path.join(data_files, f\"vehicle_{vin}_status.json\")\n )\n\n match = re.match(r\".*/vehicles/([^/]+)/remoteControl/status\", endpoint)\n if match:\n vin = match.group(1)\n response = self._load_from_file(\n os.path.join(data_files, f\"vehicle_{vin}_status_legacy.json\")\n )\n\n match = re.match(r\"/v2/trips/summarize\", endpoint)\n if match:\n # We should retrieve the driving statistics\n vin = headers[\"vin\"]\n interval = params[\"calendarInterval\"]\n response = self._load_from_file(\n os.path.join(data_files, f\"vehicle_{vin}_statistics_{interval}.json\")\n )\n\n match = re.match(r\"/api/user/.*/cms/trips/v2/history/vin/([^?]+)/.*\", endpoint)\n if match:\n # We should retrieve the trips\n vin = match.group(1)\n response = self._load_from_file(\n os.path.join(data_files, f\"vehicle_{vin}_trips.json\")\n )\n\n match = re.match(\n r\"/api/user/.*/cms/trips/v2/([^?]+)/events/vin/([^?]+)\", endpoint\n )\n if match:\n # We should retrieve the trips\n trip_id = match.group(1)\n vin = match.group(2)\n response = self._load_from_file(\n os.path.join(data_files, f\"vehicle_{vin}_trip_{trip_id}.json\")\n )\n\n match = re.match(r\".*/vehicles/([^?]+)/lock\", endpoint)\n if match:\n vin = match.group(1)\n try:\n response = self._load_from_file(\n os.path.join(data_files, f\"vehicle_{vin}_lock_request.json\")\n )\n except FileNotFoundError as exc:\n raise ToyotaActionNotSupported(\"Action is not supported\") from exc\n\n match = re.match(r\".*/vehicles/([^?]+)/lock/([^?]+)\", endpoint)\n if match:\n vin = match.group(1)\n request_id = match.group(2)\n response = self._load_from_file(\n os.path.join(\n data_files, f\"vehicle_{vin}_lock_request_status_{request_id}.json\"\n )\n )\n return response\n\n\nclass TestMyTHelper:\n \"\"\"Helper class for the actual TestMyT pytest classes\"\"\"\n\n def _create_offline_myt(self) -> MyT:\n \"\"\"Create a MyT instance that is using the OfflineController\"\"\"\n return MyT(\n username=\"user@domain.com\",\n password=\"xxxxx\",\n locale=\"en-gb\",\n region=\"europe\",\n controller_class=OfflineController,\n )\n\n def _lookup_vehicle(self, myt: MyT, vehicle_id: int):\n \"\"\"Retrieve all the vehicles, and find the vehicle with the specified 'id'\"\"\"\n vehicles = asyncio.get_event_loop().run_until_complete(myt.get_vehicles())\n vehicle = [veh for veh in vehicles if veh[\"id\"] == vehicle_id]\n return vehicle[0]\n\n\nclass TestMyT(TestMyTHelper):\n \"\"\"pytest functions to test MyT\"\"\"\n\n def test_myt(self):\n \"\"\"Test an error free initialisation of MyT\"\"\"\n myt = MyT(\n username=\"user@domain.com\",\n password=\"xxxxx\",\n locale=\"en-gb\",\n region=\"europe\",\n )\n assert myt is not None\n assert myt.api is not None\n\n @pytest.mark.parametrize(\n \"username\",\n [None, \"\", \"_invalid_\"],\n )\n def test_myt_invalid_username(self, username):\n \"\"\"Test an invalid username in MyT\"\"\"\n with pytest.raises(ToyotaInvalidUsername):\n _ = MyT(\n username=username, password=\"xxxxx\", locale=\"en-gb\", region=\"europe\"\n )\n\n @pytest.mark.parametrize(\n \"locale\",\n [\n None,\n \"\",\n \"invalid-locale\",\n \"da-en-dk-us\",\n ],\n )\n def test_myt_invalid_locale(self, locale):\n \"\"\"Test an invalid locale in MyT\"\"\"\n with pytest.raises(ToyotaLocaleNotValid):\n _ = MyT(\n username=\"user@domain.com\",\n password=\"xxxxx\",\n locale=locale,\n region=\"europe\",\n )\n\n @pytest.mark.parametrize(\n \"region\",\n [\n None,\n \"\",\n \"antartica\",\n \"mars\",\n ],\n )\n def test_myt_unsupported_region(self, region):\n \"\"\"Test an invalid region in MyT\"\"\"\n with pytest.raises(ToyotaRegionNotSupported):\n _ = MyT(\n username=\"user@domain.com\",\n password=\"xxxxx\",\n locale=\"en-gb\",\n region=region,\n )\n\n def test_get_supported_regions(self):\n \"\"\"Test the supported regions\"\"\"\n regions = MyT.get_supported_regions()\n assert regions is not None\n assert len(regions) > 0\n assert \"europe\" in regions\n\n def test_login(self):\n \"\"\"Test the login\"\"\"\n myt = self._create_offline_myt()\n asyncio.get_event_loop().run_until_complete(myt.login())\n\n def test_get_uuid(self):\n \"\"\"Test the retrieval of an uuid\"\"\"\n myt = self._create_offline_myt()\n uuid = myt.uuid\n assert uuid\n assert len(uuid) > 0\n\n def test_set_alias(self):\n \"\"\"Test the set_alias\"\"\"\n myt = self._create_offline_myt()\n result = asyncio.get_event_loop().run_until_complete(\n myt.set_alias(4444444, \"pytest_vehicle\")\n )\n assert isinstance(result, (dict))\n assert result == {\"id\": \"4444444\", \"alias\": \"pytest_vehicle\"}\n\n def test_get_vehicles(self):\n \"\"\"Test the retrieval of the available vehicles\"\"\"\n myt = self._create_offline_myt()\n vehicles = asyncio.get_event_loop().run_until_complete(myt.get_vehicles())\n assert vehicles\n assert len(vehicles) > 0\n for veh in vehicles:\n assert isinstance(veh, (dict))\n assert len(veh.keys()) > 0\n\n def test_get_vehicles_json(self):\n \"\"\"Test the retrieval of the available vehicles in json format\"\"\"\n myt = self._create_offline_myt()\n vehicles_json = asyncio.get_event_loop().run_until_complete(\n myt.get_vehicles_json()\n )\n assert json.loads(vehicles_json) is not None\n\n def test_get_vehicle_status(self):\n \"\"\"Test the retrieval of the status of a vehicle\"\"\"\n myt = self._create_offline_myt()\n vehicle = self._lookup_vehicle(myt, 4444444)\n assert vehicle is not None\n # Retrieve the actual status of the vehicle\n status = asyncio.get_event_loop().run_until_complete(\n myt.get_vehicle_status(vehicle)\n )\n assert status is not None\n\n def test_get_trips_json(self):\n \"\"\"Test the retrieval of the trips of a vehicle\"\"\"\n myt = self._create_offline_myt()\n vehicle = self._lookup_vehicle(myt, 4444444)\n assert vehicle is not None\n # Retrieve the actual trips of the vehicle\n trips = asyncio.get_event_loop().run_until_complete(\n myt.get_trips_json(vehicle[\"vin\"])\n )\n assert trips is not None\n\n def test_get_trip_json(self):\n \"\"\"Test the retrieval of a trip of a vehicle\"\"\"\n trip_id = \"971B8221-299E-4899-BC73-AE2EFF604D28\"\n myt = self._create_offline_myt()\n vehicle = self._lookup_vehicle(myt, 4444444)\n assert vehicle is not None\n trip_json = asyncio.get_event_loop().run_until_complete(\n myt.get_trip_json(vehicle[\"vin\"], trip_id)\n )\n assert trip_json is not None\n\n def test_get_trips(self):\n \"\"\"Test the retrieval of the trips of a vehicle\"\"\"\n myt = self._create_offline_myt()\n vehicle = self._lookup_vehicle(myt, 4444444)\n assert vehicle is not None\n trips = asyncio.get_event_loop().run_until_complete(\n myt.get_trips(vehicle[\"vin\"])\n )\n assert trips is not None\n for trip in trips:\n assert isinstance(trip, Trip)\n assert trip.raw_json.get(\"tripId\") is not None\n assert isinstance(trip.trip_id, str)\n assert trip.raw_json.get(\"startAddress\") is not None\n assert isinstance(trip.start_address, str)\n assert trip.raw_json.get(\"endAddress\") is not None\n assert isinstance(trip.end_address, str)\n assert trip.raw_json.get(\"startTimeGmt\") is not None\n assert isinstance(trip.start_time_gmt, datetime.datetime)\n assert trip.raw_json.get(\"endTimeGmt\") is not None\n assert isinstance(trip.end_time_gmt, datetime.datetime)\n assert trip.raw_json.get(\"classificationType\") is not None\n assert isinstance(trip.classification_type, int)\n\n def test_get_trip(self):\n \"\"\"Test the retrieval of a trip of a vehicle\"\"\"\n trip_id = \"971B8221-299E-4899-BC73-AE2EFF604D28\"\n myt = self._create_offline_myt()\n vehicle = self._lookup_vehicle(myt, 4444444)\n assert vehicle is not None\n # Retrieve the actual trip\n trip = asyncio.get_event_loop().run_until_complete(\n myt.get_trip(vehicle[\"vin\"], trip_id)\n )\n assert trip is not None\n assert isinstance(trip, DetailedTrip)\n assert len(trip.trip_events) == 12\n for event in trip.trip_events:\n assert isinstance(event, TripEvent)\n assert event.raw_json.get(\"lat\") is not None\n assert isinstance(event.latitude, float)\n assert event.raw_json.get(\"lon\") is not None\n assert isinstance(event.longitude, float)\n assert event.raw_json.get(\"overspeed\") is not None\n assert isinstance(event.overspeed, bool)\n assert event.raw_json.get(\"isEv\") is not None\n assert isinstance(event.is_ev, bool)\n assert event.raw_json.get(\"highway\") is not None\n assert isinstance(event.highway, bool)\n assert event.raw_json.get(\"mode\") is not None\n assert isinstance(event.mode, int)\n assert trip.raw_json.get(\"statistics\") is not None\n assert isinstance(trip.statistics, dict)\n\n\nclass TestMyTStatistics(TestMyTHelper):\n \"\"\"pytest functions to test get_vehicle_statistics of MyT\"\"\"\n\n def test_get_vehicle_statistics_invalid_interval_error(self):\n \"\"\"Test that retrieving the statistics of an unknown interval is not possible\"\"\"\n myt = self._create_offline_myt()\n vehicle = self._lookup_vehicle(myt, 4444444)\n assert vehicle is not None\n # Retrieve the actual status of the vehicle\n stat = asyncio.get_event_loop().run_until_complete(\n myt.get_driving_statistics(vehicle[\"vin\"], \"century\")\n )\n assert stat is not None\n assert \"error_mesg\" in stat[0]\n\n def test_get_vehicle_statistics_tomorrow_error(self):\n \"\"\"Test that retrieving the statistics of tomorrow is not possible\"\"\"\n myt = self._create_offline_myt()\n vehicle = self._lookup_vehicle(myt, 4444444)\n assert vehicle is not None\n tomorrow = arrow.now().shift(days=1).format(\"YYYY-MM-DD\")\n # Retrieve the actual status of the vehicle\n stat = asyncio.get_event_loop().run_until_complete(\n myt.get_driving_statistics(vehicle[\"vin\"], \"year\", from_date=tomorrow)\n )\n assert stat is not None\n assert \"error_mesg\" in stat[0]\n\n def test_get_vehicle_statistics_isoweek_error(self):\n \"\"\"Test that retrieving statistics of long ago of an isoweek is not possible\"\"\"\n myt = self._create_offline_myt()\n vehicle = self._lookup_vehicle(myt, 4444444)\n assert vehicle is not None\n # Retrieve the actual status of the vehicle\n stat = asyncio.get_event_loop().run_until_complete(\n myt.get_driving_statistics(\n vehicle[\"vin\"], \"isoweek\", from_date=\"2010-01-01\"\n )\n )\n assert stat is not None\n assert \"error_mesg\" in stat[0]\n\n def test_get_vehicle_statistics_year_error(self):\n \"\"\"Test that retrieving the previous year is not possible\"\"\"\n myt = self._create_offline_myt()\n vehicle = self._lookup_vehicle(myt, 4444444)\n assert vehicle is not None\n previous_year = arrow.now().shift(years=-1).format(\"YYYY-MM-DD\")\n # Retrieve the actual status of the vehicle\n stat = asyncio.get_event_loop().run_until_complete(\n myt.get_driving_statistics(vehicle[\"vin\"], \"year\", from_date=previous_year)\n )\n assert stat is not None\n assert \"error_mesg\" in stat[0]\n\n @pytest.mark.parametrize(\n \"interval,unit\",\n [\n (\"day\", \"metric\"),\n (\"day\", \"imperial\"),\n (\"day\", \"imperial_liters\"),\n (\"week\", \"metric\"),\n (\"week\", \"imperial\"),\n (\"week\", \"imperial_liters\"),\n (\"isoweek\", \"metric\"),\n (\"isoweek\", \"imperial\"),\n (\"isoweek\", \"imperial_liters\"),\n (\"month\", \"metric\"),\n (\"month\", \"imperial\"),\n (\"month\", \"imperial_liters\"),\n # Retrieving the year statistics of today is possible\n # as it will get the current year statistics\n ],\n )\n def test_get_vehicle_statistics_today_error(self, interval, unit):\n \"\"\"Test that retrieving the statistics of today is not possible\"\"\"\n myt = self._create_offline_myt()\n vehicle = self._lookup_vehicle(myt, 4444444)\n assert vehicle is not None\n today = arrow.now().format(\"YYYY-MM-DD\")\n # Retrieve the actual status of the vehicle\n stat = asyncio.get_event_loop().run_until_complete(\n myt.get_driving_statistics(\n vehicle[\"vin\"], interval, unit=unit, from_date=today\n )\n )\n assert stat is not None\n assert \"error_mesg\" in stat[0]\n\n @pytest.mark.parametrize(\n \"interval,unit\",\n [\n (\"day\", \"metric\"),\n (\"day\", \"imperial\"),\n (\"day\", \"imperial_liters\"),\n # (\"week\", \"metric\"),\n # (\"week\", \"imperial\"),\n # (\"week\", \"imperial_liters\"),\n # (\"isoweek\", \"metric\"),\n # (\"isoweek\", \"imperial\"),\n # (\"isoweek\", \"imperial_liters\"),\n (\"month\", \"metric\"),\n (\"month\", \"imperial\"),\n (\"month\", \"imperial_liters\"),\n (\"year\", \"metric\"),\n (\"year\", \"imperial\"),\n (\"year\", \"imperial_liters\"),\n ],\n )\n def test_get_driving_statistics(self, interval, unit):\n \"\"\"Test the retrieval of the status of a vehicle\"\"\"\n myt = self._create_offline_myt()\n vehicle = self._lookup_vehicle(myt, 4444444)\n assert vehicle is not None\n # Retrieve the actual status of the vehicle\n statistics = asyncio.get_event_loop().run_until_complete(\n myt.get_driving_statistics(vehicle[\"vin\"], interval, unit=unit)\n )\n assert statistics is not None\n for data in statistics:\n assert data[\"bucket\"] is not None\n # And the unit should be requested unit\n assert data[\"bucket\"][\"unit\"] == unit\n # And the year should be recent or (short) future\n assert 2018 <= int(data[\"bucket\"][\"year\"]) <= 2100\n assert data[\"data\"] is not None\n\n @pytest.mark.parametrize(\n \"unit\",\n [\n (\"metric\"),\n (\"imperial\"),\n (\"imperial_liters\"),\n ],\n )\n def test_get_driving_statistics_has_correct_day_of_year(self, unit):\n \"\"\"Test that the day-statistics contains the correct date for the day of the year\"\"\"\n myt = self._create_offline_myt()\n vehicle = self._lookup_vehicle(myt, 4444444)\n assert vehicle is not None\n # Retrieve the driving statistics of the vehicle\n statistics = asyncio.get_event_loop().run_until_complete(\n myt.get_driving_statistics(vehicle[\"vin\"], \"day\", unit=unit)\n )\n assert statistics is not None\n for day_data in statistics:\n bucket = day_data[\"bucket\"]\n date = datetime.date.fromisoformat(bucket[\"date\"])\n day_of_year = int(date.strftime(\"%j\"))\n assert bucket[\"dayOfYear\"] == day_of_year\n assert int(bucket[\"year\"]) == date.year\n\n @pytest.mark.parametrize(\n \"interval,unit\",\n [\n (\"day\", \"metric\"),\n (\"day\", \"imperial\"),\n (\"day\", \"imperial_liters\"),\n # (\"week\", \"metric\"),\n # (\"week\", \"imperial\"),\n # (\"week\", \"imperial_liters\"),\n # (\"isoweek\", \"metric\"),\n # (\"isoweek\", \"imperial\"),\n # (\"isoweek\", \"imperial_liters\"),\n (\"month\", \"metric\"),\n (\"month\", \"imperial\"),\n (\"month\", \"imperial_liters\"),\n (\"year\", \"metric\"),\n (\"year\", \"imperial\"),\n (\"year\", \"imperial_liters\"),\n ],\n )\n def test_get_driving_statistics_contains_year_as_int(self, interval, unit):\n \"\"\"Test that the statistics contains the year as an integer\"\"\"\n myt = self._create_offline_myt()\n vehicle = self._lookup_vehicle(myt, 4444444)\n assert vehicle is not None\n # Retrieve the driving statistics of the vehicle\n statistics = asyncio.get_event_loop().run_until_complete(\n myt.get_driving_statistics(vehicle[\"vin\"], interval, unit=unit)\n )\n assert statistics is not None\n for day_data in statistics:\n bucket = day_data[\"bucket\"]\n assert isinstance(bucket[\"year\"], int)\n\n @pytest.mark.parametrize(\n \"interval\",\n [\n (\"day\"),\n # (\"week\"),\n # (\"isoweek\"),\n (\"month\"),\n (\"year\"),\n ],\n )\n def test_get_driving_statistics_json(self, interval):\n \"\"\"Test the retrieval of the statistics (in JSON format) of a vehicle\"\"\"\n myt = self._create_offline_myt()\n vehicle = self._lookup_vehicle(myt, 4444444)\n assert vehicle is not None\n # Retrieve the actual status of the vehicle\n statistics_json = asyncio.get_event_loop().run_until_complete(\n myt.get_driving_statistics_json(vehicle[\"vin\"], interval)\n )\n assert json.loads(statistics_json) is not None\n","repo_name":"DurgNomis-drol/mytoyota","sub_path":"tests/test_myt.py","file_name":"test_myt.py","file_ext":"py","file_size_in_byte":21863,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"77"} +{"seq_id":"19303092385","text":"import requests\nimport re\nimport datetime\nfrom bs4 import BeautifulSoup\nfrom lxml import etree\n\n\nclass TweetItem():\n \"\"\"Tweet information \"\"\"\n _id = \"\" # 微博id\n weibo_url = \"\" # 微博URL\n like_num = 0 # 点赞数\n repost_num = 0 # 转发数\n comment_num = 0 # 评论数\n content = \"\" # 微博内容\n user_id = \"\" # 发表该微博用户的id\n tool = \"\" # 发布微博的工具\n image_url = \"\" # 图片\n video_url = \"\" # 视频\n origin_weibo = \"\" # 原始微博,只有转发的微博才有这个字段\n\nclass CommentItem():\n \"\"\"\n 微博评论信息\n \"\"\"\n _id = \"\"\n comment_user_id = \"\" # 评论用户的id\n content = \"\" # 评论的内容\n weibo_id = \"\" # 评论的微博的id\n created_at = \"\" # 评论发表时间\n like_num = 0 # 点赞数\n\n\n# 定义一些用于匹配微博内容的正则表达式\nkeyword_re = re.compile('||原图|||\\[组图共.张\\]')\nemoji_re = re.compile('\"|\"')\nwhite_space_re = re.compile('
')\ndiv_re = re.compile('|
')\nimage_re = re.compile('')\nurl_re = re.compile('|')\n\n\ndef extract_comment_content(comment_html):\n \"\"\"\n 工具函数 解析一个微博评论html内容,转发和原创两种类型\n :param weibo_html: 传入单条微博评论的div\n :return: 返回解析出来的微博内容\n \"\"\"\n s = comment_html\n if 'class=\"ctt\">' in s:\n s = s.split('class=\"ctt\">', maxsplit=1)[1]\n s = s.split('举报', maxsplit=1)[0]\n s = emoji_re.sub('', s)\n s = keyword_re.sub('', s)\n s = url_re.sub('', s)\n s = div_re.sub('', s)\n s = image_re.sub('', s)\n s = white_space_re.sub(' ', s)\n s = s.replace('\\xa0', '')\n s = s.strip(':')\n s = s.strip()\n return s\n\n\ndef extract_weibo_content(weibo_html):\n \"\"\"\n 工具函数 解析一个微博html内容,转发和原创两种类型\n :param weibo_html: 传入单条微博的div\n :return: 返回解析出来的微博内容\n \"\"\"\n s = weibo_html\n if 'class=\"ctt\">' in s:\n s = s.split('class=\"ctt\">', maxsplit=1)[1]\n s = emoji_re.sub('', s)\n s = url_re.sub('', s)\n s = div_re.sub('', s)\n s = image_re.sub('', s)\n if '' in s:\n s = s.split('')[0]\n splits = s.split('赞[')\n if len(splits) == 2:\n s = splits[0]\n if len(splits) == 3:\n origin_text = splits[0]\n retweet_text = splits[1].split('转发理由:')[1]\n s = origin_text + '转发理由:' + retweet_text\n s = white_space_re.sub(' ', s)\n s = keyword_re.sub('', s)\n s = s.replace('\\xa0', '')\n s = s.strip(':')\n s = s.strip()\n return s\n","repo_name":"biluochun1/PythonAndSql","sub_path":"Weibo/wb.py","file_name":"wb.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"24039668484","text":"#!/usr/bin/env python\n'''\npyinspirestat - Get time series from INSPIRE HEP database, the code is largely based on pyinspire.py , originally written by Ian Huston\nAuthor: Andrea Di Iura\n'''\nimport os\nimport re\nimport numpy as np\n\nstart_year, stop_year = 1930, 2015\nyears = map(str, range(start_year, stop_year + 1))\nquery = 'date '\noutput = []\nj = 0\nfor year in years: \n\t#print(year)\n\tj = j + 1\n\tprint(\"\\nYear = \", year, \". Completed @ {0:.1f}\".format(j*100./(stop_year - start_year + 1)), \"%\")\n\n\tcommand = 'python pyinspire.py -s \"find ' + query + year +'\"'\n\t#print(command)\n\treturn_value = os.popen(command).read().rstrip()\n\treturn_value = re.sub('((?<=,)|^)(?=,|$)', '0', return_value)\n\n\tprint(\"Number of papers: \", return_value)\n\toutput.append([int(year), int(return_value)])\n\nnpoutput = np.array(output)\nprint(\"\\n\")\nprint(npoutput)\n\n\n### export data\nfile_name = query.replace (\" \", \"_\") + 'years.dat'\nheader_str = query + str(start_year) + ' ---> ' + str(stop_year)\n#print(file_name)\nnp.savetxt(file_name, npoutput, fmt = '%.f', delimiter = '\\t', header = header_str)\n","repo_name":"agdiiura/PyInspireStat","sub_path":"pyinspirestat.py","file_name":"pyinspirestat.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"70607411130","text":"import cmath\n\ndef can_read(book, candles, dist=8):\n for c in candles:\n if cmath.polar(book - c)[0] <= dist:\n return True\n return False\n\ndef main():\n M = int(input())\n for _ in range(M):\n book = complex(*map(float, input().split()))\n N = int(input())\n candles = [complex(*map(float, input().split())) for _ in range(N)]\n print(\"light a candle\" if can_read(book, candles) else \"curse the darkness\")\n\nif __name__ == '__main__':\n main()\n","repo_name":"CianLR/judge-solutions","sub_path":"kattis/cursethedarkness.py","file_name":"cursethedarkness.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"77"} +{"seq_id":"14712825163","text":"#!/usr/bin/env python3\n\nimport os\nimport multiprocessing\nimport subprocess\n\nsrc = os.path.join(os.getcwd(), \"src\")\ndest = os.path.join(os.getcwd(), \"dest\")\n\ndef printlist(l):\n for item in l:\n print(item)\n print(\"---------------------------------------\")\n\n\ndef get_pathlist(source):\n pathlist = []\n for root, dirs, files in os.walk(source, topdown=True):\n # pathlist.append(root)\n for d in dirs:\n # pathlist.append(str(os.path.join(root,d))[len(source):])\n pathlist.append(str(os.path.join(root,d)))\n for f in files:\n # pathlist.append(str(os.path.join(root,f))[len(source):])\n pathlist.append(str(os.path.join(root,f)))\n return pathlist\n\ndef get_pathlists(source):\n dirlist = []\n filelist = []\n for root, dirs, files in os.walk(source, topdown=True):\n # pathlist.append(root)\n for d in dirs:\n dirlist.append(str(os.path.join(root,d))[len(source):])\n for f in files:\n filelist.append(str(os.path.join(root,f))[len(source):])\n return dirlist,filelist\n\ndef backup(path):\n print(\"Processing \" + path)\n # source = os.path.join(src,path)\n source = path\n # destination = os.path.join(dest,path)\n destination = dest\n subprocess.call(['rsync', '-apqz', source, destination])\n\ndef rsync(path):\n print(\"RSYNCing... \" + path)\n source = path\n destination = dest\n subprocess.call(['rsync', '-apqz', source, destination])\n\ndef back_folders(path):\n print(\"From path: \" + src)\n source = os.path.join(src,path)\n print(\"Processing DIR: \" + os.path.join(source,path))\n destination = os.path.join(dest,path)\n print(\"...to: \" + destination)\n subprocess.call(['rsync', '-q', source, destination])\n\ndef back_files(path):\n print(\"Processing FILE: \" + path)\n source = os.path.join(src,path)\n destination = os.path.join(dest,path)\n subprocess.call(['rsync', '-apqz', source, destination])\n\n\nif __name__ == \"__main__\":\n # os.mkdir(dest)\n src_pathlist = get_pathlist(src)\n dirlist,filelist = get_pathlists(src)\n printlist(src_pathlist)\n\n # subprocess.call(['rsync','-av -f\"+ */\" -f\"- *\"',src,dest ])\n with multiprocessing.Pool(len(dirlist),maxtasksperchild=1) as pool:\n # pool.map(rsync,[src,])\n pool.map(back_folders,dirlist)\n # with multiprocessing.Pool(len(filelist),maxtasksperchild=1) as pool:\n # pool.map(back_files,filelist)\n # pool.map(backup,src_pathlist)\n print(\"#######################################\")\n\n dest_pathlist = get_pathlist(dest)\n printlist = dest_pathlist\n if dest_pathlist == src_pathlist:\n print(\"!!SUCCESS!!\")\n else:\n print(\"...not yet :(\")\n","repo_name":"Xanderamon/python-IT-automation","sub_path":"files_and_folders/backupper/backupper.py","file_name":"backupper.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"43317986573","text":"import re\nimport sys\n\n\ndef walk(m, n, x, y):\n c = 0\n while n > y:\n c, m, n, x, y = c + m, n - 1, m, n - y, x\n return c + x\n\n\nwith open(sys.argv[1], 'r') as test_cases:\n for test in test_cases:\n print(walk(*map(int, re.findall(r'\\d+', test))))\n","repo_name":"daleysoftware/codeeval","sub_path":"1-moderate/robo-and-robitta/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"77"} +{"seq_id":"72314116408","text":"import json\r\nfrom sqlalchemy.ext.declarative import DeclarativeMeta\r\nimport datetime\r\n\r\nclass AlchemyEncoder(json.JSONEncoder):\r\n '''\r\n Для преобразования объекта таблицы в json формат\r\n Основа взята с https://stackoverflow.com/questions/5022066/how-to-serialize-sqlalchemy-result-to-json\r\n '''\r\n\r\n def default(self, obj):\r\n if isinstance(obj.__class__, DeclarativeMeta):\r\n fields = {}\r\n for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata']:\r\n data = obj.__getattribute__(field)\r\n try:\r\n if isinstance(data, datetime.date):\r\n json.dumps(data.strftime(r\"%d.%m.%Y\"))\r\n fields[field] = data.strftime(r\"%d.%m.%Y\")\r\n\r\n elif isinstance(data, datetime.time):\r\n json.dumps(data.strftime(r\"%H:%M\"))\r\n fields[field] = data.strftime(r\"%H:%M\")\r\n\r\n else:\r\n json.dumps(data)\r\n fields[field] = data\r\n \r\n except TypeError:\r\n fields[field] = None\r\n \r\n return fields\r\n\r\n return json.JSONEncoder.default(self, obj)","repo_name":"Domaestro/podvezi-soseda-ivr","sub_path":"PodveziSosedaSource/app/Driver/alchemyToJSON.py","file_name":"alchemyToJSON.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"27818715046","text":"import time\nfrom datetime import datetime\n\nfrom pytz import timezone\n\n'''\nIndira in India places an\norder on a Los Angeles ICO which \nstarts on Sept (Nov) 30th, 2017 at 9.00\nPDT time.\n\nThe order are stored with a UTC\ntime stamp in the ICO database.\n\nIt is be accessed by Indira\nusing her browser.\n\nA problem pops up în the case the order\nis placed in november: browsing the placed\norder displays it with a time which is 1 hour\ntoo late !\n'''\nDATE_TIME_FORMAT = \"%Y/%m/%d %H:%M:%S\"\nDATE_TIME_FORMAT_NO_YEAR = \"%m/%d %H:%M:%S\"\nDATE_TIME_FORMAT_TZ = DATE_TIME_FORMAT + ' %Z%z'\nDATE_TIME_FORMAT_TZ_NO_YEAR = DATE_TIME_FORMAT_NO_YEAR + ' %Z%z'\nLA_TIMEZONE = 'US/Pacific'\nNY_TIMEZONE = 'US/Eastern'\nZH_TIMEZONE = 'Europe/Zurich'\nIN_TIMEZONE = 'Asia/Calcutta'\nUTC_TIMEZONE = 'UTC'\nSUMMER_MONTH = '09'\nWINTER_MONTH = '11'\nTIMESTAMP_TO_DATE_CORRECTION_FACTOR = 3600\nWINTER_TIMESTAMP_TO_DATE_CORRECTION_FACTOR = 0\n\ndef printDate(location, datetimeObj):\n printDateNoDst(location, datetimeObj)\n print(' tm_isdst=' + str(datetimeObj.timetuple()[8]))\n\ndef printDateNoDst(location, datetimeObj):\n if len(location) == 3:\n print(location + ': ' + datetimeObj.strftime(DATE_TIME_FORMAT_TZ))\n else:\n print(location + ': ' + datetimeObj.strftime(DATE_TIME_FORMAT_TZ))\n\ndef printAndStoreOrderDateUtcTS(investor, datetimeObj, orderDic):\n print(investor + ': ' + datetimeObj.strftime(DATE_TIME_FORMAT_TZ))\n datetimeObjUTC = datetimeObj.astimezone(timezone(UTC_TIMEZONE))\n timeStampUTC = time.mktime(datetimeObjUTC.timetuple())\n timeStampStr = str(int(timeStampUTC))\n print(' UTC: ' + datetimeObjUTC.strftime(DATE_TIME_FORMAT_TZ))\n print(' TS: ' + timeStampStr)\n orderDic[investor] = timeStampStr\n \ndef printLag(icoDatetimeObjLA, orderDatetimeObj):\n utcLagLA = float(icoDatetimeObjLA.strftime('%z')) / 100\n utcLagOrderDate = float(orderDatetimeObj.strftime('%z')) / 100\n \n if ((utcLagLA < 0) and (utcLagOrderDate < 0)) or ((utcLagLA > 0) and (utcLagOrderDate > 0)):\n totalLag = abs(abs(utcLagLA) - abs(utcLagOrderDate))\n else:\n totalLag = abs(abs(utcLagLA) + abs(utcLagOrderDate))\n \n print(\" LAG: %.1f\" % totalLag) \n\ndef browseOrders(orderDic, viewerTimezone, tsCorr):\n print('--Orders {}--'.format(viewerTimezone))\n for key, value in orderDic.items():\n localDateStr, dst = timestamp2localdate(value, viewerTimezone, tsCorr)\n #print('dst-->{}'.format(dst))\n print(\"{} {} {} d-{}\".format(key, value, localDateStr, dst))\n print('') \n\ndef timestamp2localdate(strTimestamp, localTimeZone, tsCorr):\n # function converts a UTC timestamp into timezone Gregorian date\n intTimeStamp = int(strTimestamp)\n intTimeStamp -= tsCorr \n datetimeUTC = datetime.fromtimestamp(intTimeStamp).replace(tzinfo=timezone('UTC'))\n datetimeUnlocalized = datetime.fromtimestamp(intTimeStamp)\n datetimeUTC = timezone(UTC_TIMEZONE).localize(datetimeUnlocalized)\n datetimeLocal = datetimeUTC.astimezone(timezone(localTimeZone))\n dst = str(datetimeLocal.timetuple()[8])\n print('tsCorr: {} dst-->{}'.format(tsCorr,dst))\n return datetimeLocal.strftime(DATE_TIME_FORMAT_TZ_NO_YEAR), dst\n\n'''\nprint(\"-- Summer ICO start date/time --\")\nicoLocDateStr = '2017/' + MONTH + '/30 09:00:00'\nicoDatetimeObjUnlocalized = datetime.strptime(icoLocDateStr, DATE_TIME_FORMAT)\nicoDatetimeObjLA = timezone(LA_TIMEZONE).localize(icoDatetimeObjUnlocalized)\nprintDate('LA', icoDatetimeObjLA)\n\nicoDatetimeObjNY = icoDatetimeObjLA.astimezone(timezone(NY_TIMEZONE))\nprintDate('NY', icoDatetimeObjNY)\nicoDatetimeObjUTC = icoDatetimeObjLA.astimezone(timezone(UTC_TIMEZONE))\nprintDate('UTC', icoDatetimeObjUTC)\n\nprint(\"\\n-- Placing summer order --\")\n\nprintDateNoDst('LA', icoDatetimeObjLA)\nnormanOrderDateStr = '2017/' + MONTH + '/30 12:01:55'\norderDatetimeObjUnlocalized = datetime.strptime(normanOrderDateStr, DATE_TIME_FORMAT)\norderDatetimeObjNY = timezone(NY_TIMEZONE).localize(orderDatetimeObjUnlocalized)\nprint('NO: ' + orderDatetimeObjNY.strftime(DATE_TIME_FORMAT_TZ))\ndatetimeObjUTC = orderDatetimeObjNY.astimezone(timezone(UTC_TIMEZONE))\ntimeStampUTC = time.mktime(datetimeObjUTC.timetuple())\ntimeStampStrNO_UTC = str(int(timeStampUTC))\nprint(' UTC: ' + datetimeObjUTC.strftime(DATE_TIME_FORMAT_TZ))\nprint(' TS: ' + timeStampStrNO_UTC)\nprintLag(icoDatetimeObjLA, orderDatetimeObjNY)\n\nprint(\"\\n-- Browsing summer orders --\")\n\nprint('--Order {}--'.format(NY_TIMEZONE))\nintTimeStamp = int(timeStampStrNO_UTC)\ndstNY = orderDatetimeObjNY.timetuple()[8]\ntsCorrFactor = TIMESTAMP_TO_DATE_CORRECTION_FACTOR * dstIN\nintTimeStamp -= tsCorrFactor\ndatetimeUnlocalized = datetime.fromtimestamp(intTimeStamp)\ndatetimeUTC = timezone(UTC_TIMEZONE).localize(datetimeUnlocalized)\ndatetimeLocal = datetimeUTC.astimezone(timezone(NY_TIMEZONE))\n\ndstNYStr = str(dstNY)\nprint('tsCorr: {} dst-->{}'.format(TIMESTAMP_TO_DATE_CORRECTION_FACTOR, dstNYStr))\nlocalDateStr = datetimeLocal.strftime(DATE_TIME_FORMAT_TZ_NO_YEAR)\nprint(\"{} {} {} d-{}\".format('NO', timeStampStrNO_UTC, localDateStr, dstNYStr))\n'''\n\n\n\n\n\nprint(\"-- Summer ICO start date/time --\")\nicoLocDateStr = '2017/' + SUMMER_MONTH + '/30 09:00:00'\nicoDatetimeObjUnlocalized = datetime.strptime(icoLocDateStr, DATE_TIME_FORMAT)\nicoDatetimeObjLA = timezone(LA_TIMEZONE).localize(icoDatetimeObjUnlocalized)\nprintDate('LA', icoDatetimeObjLA)\n\nicoDatetimeObjIN = icoDatetimeObjLA.astimezone(timezone(IN_TIMEZONE))\nprintDate('IN', icoDatetimeObjIN)\nicoDatetimeObjUTC = icoDatetimeObjLA.astimezone(timezone(UTC_TIMEZONE))\nprintDate('UTC', icoDatetimeObjUTC)\n\n'''\nprint(\"\\n-- Placing summer order --\")\n\nprintDateNoDst('LA', icoDatetimeObjLA)\nindiraOrderDateStr = '2017/' + MONTH + '/30 21:31:55'\norderDatetimeObjUnlocalized = datetime.strptime(indiraOrderDateStr, DATE_TIME_FORMAT)\norderDatetimeObjIN = timezone(IN_TIMEZONE).localize(orderDatetimeObjUnlocalized)\nprint('IN: ' + orderDatetimeObjIN.strftime(DATE_TIME_FORMAT_TZ))\ndatetimeObjUTC = orderDatetimeObjIN.astimezone(timezone(UTC_TIMEZONE))\ntimeStampUTC = time.mktime(datetimeObjUTC.timetuple())\ntimeStampStrIN_UTC = str(int(timeStampUTC))\nprint(' UTC: ' + datetimeObjUTC.strftime(DATE_TIME_FORMAT_TZ))\nprint(' TS: ' + timeStampStrIN_UTC)\nprintLag(icoDatetimeObjLA, orderDatetimeObjIN)\n\nprint(\"\\n-- Browsing summer orders --\")\n\nprint('--Order {}--'.format(IN_TIMEZONE))\nintTimeStamp = int(timeStampStrIN_UTC)\ndstIN = orderDatetimeObjIN.timetuple()[8]\ntsCorrFactor = TIMESTAMP_TO_DATE_CORRECTION_FACTOR * dstIN\nintTimeStamp -= tsCorrFactor\ndatetimeUnlocalized = datetime.fromtimestamp(intTimeStamp)\ndatetimeUTC = timezone(UTC_TIMEZONE).localize(datetimeUnlocalized)\ndatetimeLocal = datetimeUTC.astimezone(timezone(IN_TIMEZONE))\n\ndstINStr = str(dstIN)\nprint('tsCorr: {} dst-->{}'.format(tsCorrFactor, dstINStr))\nlocalDateStr = datetimeLocal.strftime(DATE_TIME_FORMAT_TZ_NO_YEAR)\nutcDateStr = datetimeUTC.strftime(DATE_TIME_FORMAT_TZ_NO_YEAR)\nprint('{} {} {} '.format('UTC', timeStampStrIN_UTC, utcDateStr))\nprint(\"{} {} {} d-{}\".format('IN', str(intTimeStamp), localDateStr, dstINStr))\n\n\nprint(\"\\n-- Winter ICO start date/time --\")\nicoLocDateStr = '2017/' + WINTER_MONTH + '/30 09:00:00'\nicoDatetimeObjUnlocalized = datetime.strptime(icoLocDateStr, DATE_TIME_FORMAT)\nicoDatetimeObjLA = timezone(LA_TIMEZONE).localize(icoDatetimeObjUnlocalized)\nprintDate('LA', icoDatetimeObjLA)\n\nicoDatetimeObjIN = icoDatetimeObjLA.astimezone(timezone(IN_TIMEZONE))\nprintDate('IN', icoDatetimeObjIN)\nicoDatetimeObjUTC = icoDatetimeObjLA.astimezone(timezone(UTC_TIMEZONE))\nprintDate('UTC', icoDatetimeObjUTC)\n\nprint(\"\\n-- Placing winter order --\")\n\nprintDateNoDst('LA', icoDatetimeObjLA)\nindiraOrderDateStr = '2017/' + WINTER_MONTH + '/30 22:31:55'\norderDatetimeObjUnlocalized = datetime.strptime(indiraOrderDateStr, DATE_TIME_FORMAT)\norderDatetimeObjIN = timezone(IN_TIMEZONE).localize(orderDatetimeObjUnlocalized)\nprint('IN: ' + orderDatetimeObjIN.strftime(DATE_TIME_FORMAT_TZ))\ndatetimeObjUTC = orderDatetimeObjIN.astimezone(timezone(UTC_TIMEZONE))\ntimeStampUTC = time.mktime(datetimeObjUTC.timetuple())\ntimeStampStrIN_UTC = str(int(timeStampUTC))\nprint(' UTC: ' + datetimeObjUTC.strftime(DATE_TIME_FORMAT_TZ))\nprint(' TS: ' + timeStampStrIN_UTC)\nprintLag(icoDatetimeObjLA, orderDatetimeObjIN)\n\nprint(\"\\n-- Browsing winter orders --\")\n\nprint('--Order {}--'.format(IN_TIMEZONE))\nintTimeStamp = int(timeStampStrIN_UTC)\ndstIN = orderDatetimeObjIN.timetuple()[8]\ntsCorrFactor = TIMESTAMP_TO_DATE_CORRECTION_FACTOR * dstIN\nintTimeStamp -= tsCorrFactor\ndatetimeUnlocalized = datetime.fromtimestamp(intTimeStamp)\ndatetimeUTC = timezone(UTC_TIMEZONE).localize(datetimeUnlocalized)\ndatetimeLocal = datetimeUTC.astimezone(timezone(IN_TIMEZONE))\n\ndstINStr = str(dstIN)\nprint('tsCorr: {} dst-->{}'.format(tsCorrFactor, dstINStr))\nlocalDateStr = datetimeLocal.strftime(DATE_TIME_FORMAT_TZ_NO_YEAR)\nprint(\"{} {} {} d-{}\".format('IN', timeStampStrIN_UTC, localDateStr, dstINStr))\n'''\n\nprint(\"\\n-- Placing summer order --\")\nindiraOrderDateStr = '2017/' + SUMMER_MONTH + '/30 21:31:55'\norderDatetimeObjUnlocalized = datetime.strptime(indiraOrderDateStr, DATE_TIME_FORMAT)\norderDatetimeObjIN = timezone(IN_TIMEZONE).localize(orderDatetimeObjUnlocalized)\ndatetimeObjUTC = orderDatetimeObjIN.astimezone(timezone(UTC_TIMEZONE))\ntimeStampUTC = time.mktime(datetimeObjUTC.timetuple())\nprint('IN: ' + orderDatetimeObjIN.strftime(DATE_TIME_FORMAT_TZ))\nprint('UTC: ' + datetimeObjUTC.strftime(DATE_TIME_FORMAT_TZ))\nprint(' TS: ' + str(timeStampUTC))\n\nprint(\"\\n-- Browsing summer order --\")\ndatetimeUnlocalized = datetime.fromtimestamp(timeStampUTC)\ndatetimeUTC = timezone(UTC_TIMEZONE).localize(datetimeUnlocalized)\ndatetimeIN = datetimeUTC.astimezone(timezone(IN_TIMEZONE))\nprint('{}: {}'.format('UTC', datetimeUTC.strftime(DATE_TIME_FORMAT_TZ)))\nprint(' TS: ' + str(timeStampUTC))\nprint(\"{}: {}\".format('IN', datetimeIN.strftime(DATE_TIME_FORMAT_TZ)))\n","repo_name":"Archanciel/explore","sub_path":"tzstampindira.py","file_name":"tzstampindira.py","file_ext":"py","file_size_in_byte":9934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"17924744456","text":"texto = \"Este es el texto de Dani\"\n\nresultado = texto.upper()\nresultado2 = texto[2].upper()\nresultado3 = texto.lower()\nresultado4 = texto.split()\nresultado5 = texto.split(\"t\")\nprint(resultado)\nprint(resultado2)\nprint(resultado3)\nprint(resultado4)\nprint(resultado5)\n\na = \"Aprender\"\nb = \"Python\"\nc = \"es\"\nd = \"genial\"\ne = \" \".join([a,b,c,d])\nprint(e)\n\nresultado6 = texto.find(\"x\")\nprint(resultado6)\n\nresultado7 = texto.replace(\"Dani\", \"Todos\")\nprint(resultado7)","repo_name":"Daninja111/python_basics","sub_path":"Dia_3/metodos.py","file_name":"metodos.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"21784942878","text":"import tkinter as tk\nimport json\nfrom evaluate_excel import read_filter_json\nimport UiConfigurateFilter\nimport UiElementCreator\n\n\ndef initialize_page_edit(window, filter_file, sel_entry):\n # Clean up input line objects of the InputLineCreator class\n UiElementCreator.InputLineCreator.clean_up_objects()\n # Load selected data from filter file\n sel_data = read_filter_json(filter_file)['data_filter'][sel_entry]\n # Create a frame for the page\n page = tk.Frame(window)\n page.grid(row=0, column=0, sticky='nsew')\n\n # Frame for title\n title_frame = tk.Frame(page, bd=1, relief='raised')\n title_frame.grid(row=0, column=0, columnspan=3, sticky='nsew', padx=10,\n pady=5)\n # Label for title of creating a filter\n filter_label = tk.Label(title_frame, text='Edit entry of the filter',\n font=('Arial', 12, 'bold'))\n filter_label.grid(row=0, column=0, sticky='w', padx=10, pady=5)\n\n # Frame for selected filter json\n selected_filter_frame = tk.LabelFrame(page, text='Selected filter file',\n bd=2, relief='ridge')\n selected_filter_frame.grid(row=1, column=0, sticky='nsew', padx=10, pady=5)\n # Label for the name of the selected filter json\n selected_filter_label = tk.Label(selected_filter_frame, text=filter_file,\n font=('Arial', 8, 'bold'))\n selected_filter_label.grid(row=0, column=0, sticky='w', padx=10, pady=5)\n\n # Frame for name of the selected entry\n selected_entry_frame = tk.LabelFrame(page, text='Selected entry', bd=2,\n relief='ridge')\n selected_entry_frame.grid(row=2, column=0, sticky='nsew', padx=10, pady=5)\n # Label for name of the selected entry\n edit_name_input = tk.Label(selected_entry_frame, text=sel_entry,\n font=('Arial', 8, 'bold'))\n edit_name_input.grid(row=1, column=0, columnspan=2, sticky='w', padx=10,\n pady=(0, 5))\n\n # Frame for edit filter data\n edit_entry_frame = tk.LabelFrame(page, text='Edit filter data', bd=2,\n relief='ridge')\n edit_entry_frame.grid(row=3, column=0, sticky='nsew', padx=10, pady=5)\n # Frame for edit testcase and variable\n edit_testcase_frame = tk.Frame(edit_entry_frame, relief='ridge')\n edit_testcase_frame.grid(row=1, column=0, sticky='nsew', padx=10, pady=5)\n # Label for edit testcase\n edit_testcase_label = tk.Label(edit_testcase_frame, text='Edit testcase',\n font=('Arial', 8, 'bold'))\n edit_testcase_label.grid(row=0, column=0, sticky='w', padx=10, pady=5)\n # Label for edit variable\n edit_variable_label = tk.Label(edit_testcase_frame,\n text='Edit variable of testcase',\n font=('Arial', 8, 'bold'))\n edit_variable_label.grid(row=0, column=1, sticky='w', padx=10, pady=5)\n # Input lines for edit testcase and variable\n for key, value in sel_data[1].items():\n UiElementCreator.InputLineCreator(edit_testcase_frame, 'testcases')\n last_entry = UiElementCreator.InputLineCreator.get_all_instances('testcases')[-1]\n UiElementCreator.InputLineCreator.insert_text_entry_obj(last_entry[0], 'col1', key)\n UiElementCreator.InputLineCreator.insert_text_entry_obj(last_entry[1], 'col2', value)\n\n # Frame for edit value to calculate entry and header in template entry\n edit_calcvalue_frame = tk.Frame(edit_entry_frame, relief='ridge')\n edit_calcvalue_frame.grid(row=2, column=0, sticky='nsew', padx=10, pady=5)\n # Label for edit values to be calculated\n edit_variable_label = tk.Label(edit_calcvalue_frame,\n text='Edit value to calculate',\n font=('Arial', 8, 'bold'))\n edit_variable_label.grid(row=0, column=0, sticky='w', padx=10, pady=5)\n # Label for edit header in template\n edit_header_label = tk.Label(edit_calcvalue_frame,\n text='Edit header in the template',\n font=('Arial', 8, 'bold'))\n edit_header_label.grid(row=0, column=1, sticky='w', padx=10, pady=5)\n # Input line for edit values to be calculated and header in template\n for key, value in sel_data[2].items():\n UiElementCreator.InputLineCreator(edit_calcvalue_frame, 'calc_value')\n last_entry = UiElementCreator.InputLineCreator.get_all_instances('calc_value')[-1]\n UiElementCreator.InputLineCreator.insert_text_entry_obj(last_entry[0], 'col1', key)\n UiElementCreator.InputLineCreator.insert_text_entry_obj(last_entry[1], 'col2', value)\n\n # Frame for options\n options_frame = tk.LabelFrame(page, text='Options', bd=2,\n relief='ridge')\n options_frame.grid(row=4, column=0, sticky='nsew', padx=10, pady=5)\n # Button for deleting the complete entry\n btn_del_entry = tk.Button(options_frame, text='Delete complete entry',\n width=20, command=lambda:\n del_complete_entry(filter_file, sel_entry,\n window))\n btn_del_entry.grid(row=0, column=0, sticky='nswe', padx=5, pady=5)\n # Button for adding testcase and variable pair\n btn_add_testcase = tk.Button(options_frame, text='Add testcase', width=20,\n command=lambda:\n add_entry_line(edit_testcase_frame,\n 'testcases'))\n btn_add_testcase.grid(row=0, column=1, sticky='nswe', padx=5, pady=5)\n # Button for deleting testcase and variable\n btn_del_testcase = tk.Button(options_frame, text='Delete testcase',\n width=20, command=lambda:\n del_last_entry_line('testcases'))\n btn_del_testcase.grid(row=0, column=2, sticky='nswe', padx=5, pady=5)\n # Button for adding value to calculate and header in template\n btn_add_valcalc = tk.Button(options_frame, text='Add value to calculate',\n width=20, command=lambda:\n add_entry_line(edit_calcvalue_frame,\n 'calc_value'))\n btn_add_valcalc.grid(row=0, column=3, sticky='nswe', padx=5, pady=5)\n # Button for deleting value to calculate and header in template\n btn_del_valcalc = tk.Button(options_frame,\n text='Delete value to calculate',\n width=20, command=lambda:\n del_last_entry_line('calc_value'))\n btn_del_valcalc.grid(row=0, column=4, sticky='nswe', padx=5, pady=5)\n # Button for saving the changes\n btn_save_changes = tk.Button(options_frame, text='Save changes', width=20,\n command=lambda:\n save_changes(filter_file, sel_entry, window))\n btn_save_changes.grid(row=1, column=2, sticky='nswe', padx=5, pady=5)\n\n\ndef del_complete_entry(filter_file, entry_name_input, window):\n # Load the filter data from json file\n filter_data = read_filter_json(filter_file)\n # Delete the complete entry from the filter file\n del filter_data['data_filter'][entry_name_input]\n # Save changes to the filter file\n with open(filter_file, 'w') as f:\n json.dump(filter_data, f, indent=4)\n # Switch to configurate filter first page\n UiConfigurateFilter.initialize_page_configurate_filter(window, filter_file)\n UiConfigurateFilter.set_infos(filter_file)\n\n\ndef add_entry_line(frame, input_type):\n UiElementCreator.InputLineCreator(frame, input_type)\n\n\ndef del_last_entry_line(input_type):\n all_instances = UiElementCreator.InputLineCreator.get_all_instances(input_type)\n if len(all_instances) < 2:\n return None\n last_entry_line = UiElementCreator.InputLineCreator.get_all_instances(input_type)[-1]\n UiElementCreator.InputLineCreator.delete_entry_line(last_entry_line[0], 'col1')\n UiElementCreator.InputLineCreator.delete_obj_instances_dict(input_type, 'col1',\n last_entry_line[0])\n UiElementCreator.InputLineCreator.delete_entry_line(last_entry_line[1], 'col2')\n UiElementCreator.InputLineCreator.delete_obj_instances_dict(input_type, 'col2',\n last_entry_line[1])\n UiElementCreator.InputLineCreator.instances_dict[input_type]['row'] -= 1\n\n\ndef save_changes(filter_file, entry_name_input, window):\n # Get the texts of all testcase/variable inputs\n tc_var_dict = {}\n tc_var = UiElementCreator.InputLineCreator.get_all_instances('testcases')\n for instance in tc_var:\n testcase = UiElementCreator.InputLineCreator.get_text(instance[0], 'col1')\n variable = UiElementCreator.InputLineCreator.get_text(instance[1], 'col2')\n tc_var_dict[testcase] = variable\n # Get the texts of all value to calculate/template header inputs\n valcalc_tempheader_dict = {}\n valcalc_tempheader = UiElementCreator.InputLineCreator.get_all_instances('calc_value')\n for instance in valcalc_tempheader:\n valcalc = UiElementCreator.InputLineCreator.get_text(instance[0], 'col1')\n tempheader = UiElementCreator.InputLineCreator.get_text(instance[1], 'col2')\n valcalc_tempheader_dict[valcalc] = tempheader\n # Load the filter data from json file\n filter_data = read_filter_json(filter_file)\n # Add the new entry to the dict of the filter file\n filter_data['data_filter'][entry_name_input] = \\\n [list(valcalc_tempheader_dict),\n tc_var_dict, valcalc_tempheader_dict]\n # Save changes to the filter file\n with open(filter_file, 'w') as f:\n json.dump(filter_data, f, indent=4)\n # Switch to configurate filter first page\n UiConfigurateFilter.initialize_page_configurate_filter(window, filter_file)\n UiConfigurateFilter.set_infos(filter_file)\n","repo_name":"MiWaTec/mwtestcodes","sub_path":"ExcelReaderScript/UiConfigurateFilterEdit.py","file_name":"UiConfigurateFilterEdit.py","file_ext":"py","file_size_in_byte":10100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"16958956398","text":"import torch\n\ndef test_out(output, tile_row, tile_col, channel, pool, scale):\n if pool:\n tile_w = 10\n tile_h = 8\n else:\n tile_w = 20\n tile_h = 16\n \n exp_out = output\n for j_index in range(0, tile_row):\n for k_index in range(0, tile_col):\n tile_index = k_index + (j_index) * tile_col\n print(\"============ tile index: \", tile_index, \"================\")\n if j_index != (tile_row - 1):\n for i in range(0, channel):\n for j in range(j_index * tile_h, (j_index + 1) * tile_h):\n for k in range(k_index * tile_w, (k_index + 1) * tile_w):\n # n c h w\n # print(\"i: \", i)\n # print(\"j: \", j)\n # print(\"k: \", k)\n print('{:d}\\t'.format((exp_out[0][i][j][k].data * scale).int()), end = \"\")\n print(\"\")\n print(\"\")\n\n elif j_index == (tile_row - 1):\n #print(\"j_index == (tile_row - 1)!!!!!!\")\n for i in range(0, channel):\n for j in range(j_index * tile_h, exp_out.shape[2]):\n for k in range(k_index * tile_w, (k_index + 1) * tile_w):\n # n c h w\n #print((output[0][i][j][k] * 4).int(), \" \")\n print('{:d}\\t'.format((exp_out[0][i][j][k].data * scale).int()), end = \"\")\n print(\"\")\n print(\"\")\n\nf1 = open(\"./out/out1\", \"r\")\n\nout1 = torch.zeros([1, 16, 120, 160]) \ntile_row_num = 15\ntile_col_num = 16\n\nlines1 = f1.readlines()\ntile_count = -1\nh_count = 0\nw_count = -1\n\nw = 0\nh = 0\nc = -1\n\nfor index in range(0, len(lines1)):\n list1 = lines1[index].strip(\"\\n\").strip(\"\\t\").split(\"\\t\")\n\n for j in range(0, len(list1)):\n if len(list1) == 1:\n if list1[j] == \"\":\n pass\n else:\n #print(list1[j])\n if \"tile\" in list1[j]:\n tile_count += 1\n #print(\"tile_count: \", tile_count)\n c = 0\n if (tile_count) % tile_col_num == 0 and tile_count != 0:\n h_count += 1\n w_count = 0\n #print(\"h_count: \",h_count)\n else:\n w_count += 1\n #print(\"w_count: \",w_count)\n h = h_count * 8\n w = w_count * 10\n else:\n out1[0][c][h][w] = int(list1[j])\n if (h + 1 - h_count * 8) % 8 == 0 and (w + 1 - h_count * 10) % 10 == 0:\n c += 1\n h = h_count * 8\n w = w_count * 10\n \n else:\n if (w + 1 - w_count * 10) % 10 == 0:\n h += 1\n w = w_count * 10\n else:\n w += 1\n #print(\"h: \", h, \", w: \", w, \", c: \", c)\n\ntest_out(out1, tile_row=15, tile_col=16, channel=16, pool = 1, scale=1)\n","repo_name":"ZLkanyo009/YOLO-Deployment-in-c-language","sub_path":"check_tool/copy_map.py","file_name":"copy_map.py","file_ext":"py","file_size_in_byte":3154,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"13202831434","text":"from flask import g\nfrom common_libs.common.exception import AppException\n\nfrom common_libs.common.dbconnect.dbconnect_ws import DBConnectWs\nfrom common_libs.ansible_driver.classes.AnscConstClass import AnscConst\nfrom common_libs.ansible_driver.classes.ansibletowerlibs.RestApiCaller import RestApiCaller\nfrom common_libs.ansible_driver.classes.ansibletowerlibs.restapi_command.AnsibleTowerRestApiInstanceGroups import AnsibleTowerRestApiInstanceGroups\nfrom common_libs.ansible_driver.classes.ansibletowerlibs.restapi_command.AnsibleTowerRestApiOrganizations import AnsibleTowerRestApiOrganizations\nfrom common_libs.ansible_driver.classes.ansibletowerlibs.restapi_command.AnsibleTowerRestApiExecutionEnvironment import AnsibleTowerRestApiExecutionEnvironment\n\n\ndef DBUpdate(Contents_array, TableName, TableRows, PkeyItem, NameItem, IDItem, dbAccess, is_register_history):\n\n db_access_user_id = '20102'\n\n livingIds = []\n\n # 既存データの検索用Idカラムを作成する\n Names_inTable = [d[NameItem] for d in TableRows]\n\n # 新規追加 or 更新\n for Contents_fromTower in Contents_array:\n target_index = None\n if Contents_fromTower['name'] in Names_inTable:\n target_index = Names_inTable.index(Contents_fromTower['name'])\n\n # 見つからない場合は新規\n if target_index is None:\n newRow = {\n NameItem : Contents_fromTower['name'],\n IDItem : Contents_fromTower['id'],\n 'DISUSE_FLAG' : '0',\n 'LAST_UPDATE_USER' : db_access_user_id,\n }\n rowId = dbAccess.table_insert(TableName, newRow, PkeyItem, is_register_history)\n rowId = rowId[0][PkeyItem]\n\n # 見つかるのであれば更新の可能性 ... 差分があれば更新/復活\n else:\n updateRow = TableRows[target_index]\n rowId = updateRow[PkeyItem]\n if Contents_fromTower['id'] != updateRow[IDItem]:\n updateRow[IDItem] = Contents_fromTower['id']\n updateRow['DISUSE_FLAG'] = '0'\n updateRow['LAST_UPDATE_USER'] = db_access_user_id\n rowId = dbAccess.table_update(TableName, updateRow, PkeyItem, is_register_history)\n rowId = rowId[0][PkeyItem]\n\n if updateRow['DISUSE_FLAG'] != '0':\n updateRow['DISUSE_FLAG'] = '0'\n updateRow['LAST_UPDATE_USER'] = db_access_user_id\n rowId = dbAccess.table_update(TableName, updateRow, PkeyItem, is_register_history)\n rowId = rowId[0][PkeyItem]\n\n if rowId is False:\n raise\n\n livingIds.append(rowId)\n\n # 廃止\n for row in TableRows:\n # 既に廃止されているレコードは対象外\n if row['DISUSE_FLAG'] != \"0\":\n continue\n\n # 登録されている場合はなにもしない\n if row[PkeyItem] in livingIds:\n continue\n\n row['DISUSE_FLAG'] = '1'\n row['LAST_UPDATE_USER'] = db_access_user_id\n rset = dbAccess.table_update(TableName, row, PkeyItem, is_register_history)\n if rset is False:\n raise\n\n return True\n\ndef backyard_main(organization_id, workspace_id):\n print(\"backyard_main ita_by_ansible_towermaster_sync called\")\n\n warning_flag = 0\n error_flag = 0\n dbAccess = None\n\n try:\n g.applogger.debug(\" = Start Procedure. =\")\n\n ################################\n # DBコネクト\n ################################\n g.applogger.debug(\"db connect.\")\n dbAccess = DBConnectWs()\n\n ################################\n # インターフェース情報を取得する\n ################################\n g.applogger.debug(\"Get interface info.\")\n cols = \"\"\n cols_a = dbAccess.table_columns_get(\"T_ANSC_IF_INFO\")\n cols_b = dbAccess.table_columns_get(\"T_ANSC_TOWER_HOST\")\n for col in cols_a[0]:\n if cols:\n cols += \", \"\n\n cols += \"TAB_A.%s\" % (col)\n\n for col in cols_b[0]:\n if cols:\n cols += \", \"\n\n cols += \"TAB_B.%s\" % (col)\n\n sql = (\n \"SELECT \\n\"\n \" %s \\n\"\n \"FROM \\n\"\n \" T_ANSC_IF_INFO TAB_A \\n\"\n \"INNER JOIN \\n\"\n \" T_ANSC_TOWER_HOST TAB_B \\n\"\n \"ON \\n\"\n \" TAB_A.ANSTWR_HOST_ID = TAB_B.ANSTWR_HOST_ID \\n\"\n \"WHERE \\n\"\n \" TAB_A.DISUSE_FLAG = '0' \\n\"\n \"AND \\n\"\n \" TAB_B.DISUSE_FLAG = '0'; \\n\"\n ) % (cols)\n ifInfoRows = dbAccess.sql_execute(sql)\n num_of_rows = len(ifInfoRows)\n\n # 設定なしの場合\n if num_of_rows == 0:\n raise Exception(\"No records in if_info.\")\n\n # 重複登録の場合\n elif num_of_rows > 1:\n raise Exception(\"More than one record in if_info.\")\n\n # 実行エンジンがAnsible Towerの場合のみ処理続行\n if ifInfoRows[0]['ANSIBLE_EXEC_MODE'] != AnscConst.DF_EXEC_MODE_AAC:\n return 0\n\n if ('ANSTWR_AUTH_TOKEN' not in ifInfoRows[0] or ifInfoRows[0]['ANSTWR_AUTH_TOKEN'] is None or len(ifInfoRows[0]['ANSTWR_AUTH_TOKEN'].strip()) <= 0) \\\n or ('ANSTWR_HOST_ID' not in ifInfoRows[0] or ifInfoRows[0]['ANSTWR_HOST_ID'] is None or len(ifInfoRows[0]['ANSTWR_HOST_ID'].strip()) <= 0):\n return 0\n\n ansibleTowerIfInfo = ifInfoRows[0]\n\n proxySetting = {}\n proxySetting['address'] = ansibleTowerIfInfo[\"ANSIBLE_PROXY_ADDRESS\"]\n proxySetting['port'] = ansibleTowerIfInfo[\"ANSIBLE_PROXY_PORT\"]\n\n ################################\n # RESTの認証\n ################################\n g.applogger.debug(\"Authorize Ansible Automation Controller.\")\n\n restApiCaller = RestApiCaller(\n ansibleTowerIfInfo['ANSTWR_PROTOCOL'],\n ansibleTowerIfInfo['ANSTWR_HOSTNAME'],\n ansibleTowerIfInfo['ANSTWR_PORT'],\n ansibleTowerIfInfo['ANSTWR_AUTH_TOKEN'],\n proxySetting\n )\n\n response_array = restApiCaller.authorize()\n if not response_array['success']:\n raise Exception(\"Faild to authorize to Ansible Automation Controller. %s\" % (response_array['responseContents']['errorMessage']))\n\n ############################################################\n # インスタンスグループ情報更新\n ############################################################\n try:\n ############################################################\n # Towerのインスタンスグループ情報取得\n ############################################################\n response_array = AnsibleTowerRestApiInstanceGroups.getAll(restApiCaller)\n if not response_array['success']:\n raise Exception(\"Faild to get instance groups data from Ansible Automation Controller. %s\" % (response_array['responseContents']['errorMessage']))\n\n ############################################################\n # トランザクション開始\n ############################################################\n dbAccess.db_transaction_start()\n\n ############################################################\n # ITA側の登録済みのインスタンスグループ情報取得\n ############################################################\n TableName = \"T_ANSC_TWR_INSTANCE_GROUP\"\n cols = dbAccess.table_columns_get(TableName)\n cols = (',').join(cols[0])\n sql = (\n \"SELECT \\n\"\n \" %s \\n\"\n \"FROM \\n\"\n \" %s ; \\n\"\n ) % (cols, TableName)\n instanceGroupRows = dbAccess.sql_execute(sql)\n\n ############################################################\n # データベース更新\n ############################################################\n PkeyItem = \"INSTANCE_GROUP_ITA_MANAGED_ID\"\n NameItem = \"INSTANCE_GROUP_NAME\"\n IDItem = \"INSTANCE_GROUP_ID\"\n Contents_array = []\n for info in response_array['responseContents']:\n Contents_array.append(\n {\n 'name' : info['name'],\n 'id' : int(info['id']),\n }\n )\n\n DBUpdate(Contents_array, TableName, instanceGroupRows, PkeyItem, NameItem, IDItem, dbAccess, False)\n\n ############################################################\n # トランザクション終了(分割コミット)\n ############################################################\n dbAccess.db_commit()\n\n except Exception as e:\n g.applogger.error(\"Faild to make instance group data.\")\n raise e\n\n ############################################################\n # 組織情報更新\n ############################################################\n try:\n ############################################################\n # Towerの組織情報取得\n ############################################################\n response_array = AnsibleTowerRestApiOrganizations.getAll(restApiCaller)\n if not response_array['success']:\n raise Exception(\"Faild to get organizations data from Ansible Automation Controller. %s\" % (response_array['responseContents']['errorMessage']))\n\n ############################################################\n # トランザクション開始\n ############################################################\n dbAccess.db_transaction_start()\n\n ############################################################\n # ITA側の既に登録済みの組織名情報を取得する\n ############################################################\n TableName = \"T_ANSC_TWR_ORGANIZATION\"\n cols = dbAccess.table_columns_get(TableName)\n cols = (',').join(cols[0])\n sql = (\n \"SELECT \\n\"\n \" %s \\n\"\n \"FROM \\n\"\n \" %s ; \\n\"\n ) % (cols, TableName)\n OrganizationRows = dbAccess.sql_execute(sql)\n\n ############################################################\n # データベース更新\n ############################################################\n PkeyItem = \"ORGANIZATION_ITA_MANAGED_ID\"\n NameItem = \"ORGANIZATION_NAME\"\n IDItem = \"ORGANIZATION_ID\"\n Contents_array = []\n for info in response_array['responseContents']:\n Contents_array.append(\n {\n 'name' : info['name'],\n 'id' : int(info['id']),\n }\n )\n\n DBUpdate(Contents_array, TableName, OrganizationRows, PkeyItem, NameItem, IDItem, dbAccess, False)\n\n ############################################################\n # トランザクション終了\n ############################################################\n dbAccess.db_commit()\n\n except Exception as e:\n g.applogger.error(\"Faild to make organization data.\")\n raise e\n\n ############################################################\n # 実行環境情報更新\n ############################################################\n try:\n if ifInfoRows[0]['ANSIBLE_EXEC_MODE'] == AnscConst.DF_EXEC_MODE_AAC:\n ############################################################\n # Towerの実行環境情報取得\n ############################################################\n response_array = AnsibleTowerRestApiExecutionEnvironment.get(restApiCaller)\n if not response_array['success']:\n raise Exception(\"Faild to get Execution Environment data from Ansible Automation Controller. %s\" % (response_array['responseContents']['errorMessage']))\n\n if 'responseContents' not in response_array:\n raise Exception(\"responseContents tag is not found in Ansible Automation Controller. %s\" % (response_array))\n\n if 'results' not in response_array['responseContents']:\n raise Exception(\"responseContents->results tag not found in Ansible Automation Controller. %s\" % (response_array))\n\n ############################################################\n # トランザクション開始\n ############################################################\n dbAccess.db_transaction_start()\n\n ############################################################\n # ITA側の既に登録済みの実行環境情報取得\n ############################################################\n TableName = \"T_COMN_AAC_EXECUTION_ENVIRONMENT\"\n cols = dbAccess.table_columns_get(TableName)\n cols = (',').join(cols[0])\n sql = (\n \"SELECT \\n\"\n \" %s \\n\"\n \"FROM \\n\"\n \" %s ; \\n\"\n ) % (cols, TableName)\n VirtualEnvRows = dbAccess.sql_execute(sql)\n\n ############################################################\n # データベース更新\n ############################################################\n PkeyItem = \"EXECUTION_ENVIRONMENT_ID\"\n NameItem = \"EXECUTION_ENVIRONMENT_NAME\"\n IDItem = \"EXECUTION_ENVIRONMENT_AAC_ID\"\n Contents_array = []\n if 'responseContents' in response_array and 'results' in response_array['responseContents']:\n for no, paramList in enumerate(response_array['responseContents']['results']):\n Contents_array.append(\n {\n 'name' : paramList['name'],\n 'id' : no,\n }\n )\n\n DBUpdate(Contents_array, TableName, VirtualEnvRows, PkeyItem, NameItem, IDItem, dbAccess, False)\n\n ############################################################\n # トランザクション終了\n ############################################################\n dbAccess.db_commit()\n\n except Exception as e:\n g.applogger.error(\"Faild to make Execution Environment data.\")\n raise e\n\n except Exception as e:\n error_flag = 1\n g.applogger.error(\"Exception occurred.\")\n\n # 例外メッセージ出力\n g.applogger.error(str(e))\n\n if dbAccess and dbAccess._is_transaction:\n # ロールバック\n dbAccess.db_rollback()\n g.applogger.error(\"Rollback.\")\n\n finally:\n dbAccess = None\n restApiCaller = None\n\n if error_flag != 0:\n g.applogger.error(\" = Finished Procedure. [state: ERROR] = \")\n return 2\n\n elif warning_flag != 0:\n g.applogger.warning(\" = Finished Procedure. [state: WARNING] = \")\n return 2\n\n else:\n g.applogger.debug(\" = Finished Procedure. [state: SUCCESS] = \")\n return 0\n","repo_name":"shiota-2021/it-automation2-test","sub_path":"ita_root/ita_by_ansible_towermaster_sync/backyard_main.py","file_name":"backyard_main.py","file_ext":"py","file_size_in_byte":15847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"28808470956","text":"from . import views\nfrom .views import ProductCreateView,ProductUpdateView,ProductDeleteView\nfrom django.urls import include,path\n\nurlpatterns = [\n path('',views.index,name='index'),\n path('products/',views.products,name='product'),\n path('add-product/',ProductCreateView.as_view(),name='add_product'),\n path('administrator/',views.users,name='administrator'),\n path('products//update/',ProductUpdateView.as_view(),name='product_update'),\n path('products//delete/',ProductDeleteView.as_view(),name='product_delete'),\n]\n","repo_name":"EliAckah/Alfield-Stock-Manager","sub_path":"alfieldmanager/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"29399539329","text":"def palindromo(palabra):\n palabra_o = palabra\n palabra1 = list(palabra_o)\n palabra1.reverse()\n palabra2 = \"\".join(palabra1)\n if palabra_o == palabra2:\n return True\n else:\n return False\n\nif __name__==\"__main__\":\n print(palindromo(\"oso\"))\n print(palindromo(\"dinosaurio\"))\n","repo_name":"pabloschwarzenberg/grader","sub_path":"tema11_ej1/tema11_ej1_9eea2f1d7197b0115247f0fdb624cf9a.py","file_name":"tema11_ej1_9eea2f1d7197b0115247f0fdb624cf9a.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"38399405073","text":"\"\"\"\nbfs 처리 과정에서 비활성화 바이러스인 곳과 빈 공간 구분 필요\n\"\"\"\n\nfrom collections import deque\nfrom itertools import combinations\n\ndr = [-1, 1, 0, 0]\ndc = [0, 0, -1, 1]\n\n\ndef bfs(q):\n global ans\n cur_visited = [row[:] for row in visited] # visited 복사해서 사용해서 bfs 탐색 후 초기화 과정 생략\n cnt = 0\n max_time = 0\n while q:\n cur_r, cur_c = q.popleft()\n\n for d in range(4):\n nxt_r = cur_r + dr[d]\n nxt_c = cur_c + dc[d]\n\n if 0 <= nxt_r < N and 0 <= nxt_c < N:\n if cur_visited[nxt_r][nxt_c] == -1: # 빈 공간인 경우\n cur_visited[nxt_r][nxt_c] = cur_visited[cur_r][cur_c] + 1 # visited 갱신\n q.append((nxt_r, nxt_c))\n cnt += 1 # 채워진 빈 공간 + 1\n elif cur_visited[nxt_r][nxt_c] == -2: # 비활성 바이러스인 경우\n cur_visited[nxt_r][nxt_c] = cur_visited[cur_r][cur_c] + 1 # visited 갱신\n q.append((nxt_r, nxt_c))\n if cur_visited[nxt_r][nxt_c] > max_time: # max_time 갱신\n max_time = cur_visited[nxt_r][nxt_c]\n\n if cnt == target_cnt: # 빈 공간 모두 채워진 경우\n break\n else: # 빈 공간 모두 채우지 못한 경우\n return -1\n\n return max_time\n\n\nN, M = map(int, input().split()) # N:연구소 크기 M: 초기 활성화 바이러스 개수\n\ntotal_map = [] # 전체 연구소\nwalls = 0 # 벽의 개수\nvirus = [] # 초기 활성화/비활성화 바이러스 위치\nvirus_cnt = 0 # 초기 활성화/비활성화 바이러스 개수\nvisited = [[-1] * N for _ in range(N)] # 빈 공간:-1 비활성화:-2 벽:-3 활성화:0\n\nfor row in range(N):\n data = list(map(int, input().split()))\n for col in range(N):\n if data[col] == 2: # 초기 바이러스\n virus_cnt += 1\n virus.append((row, col))\n visited[row][col] = -2\n elif data[col] == 1: # 벽\n visited[row][col] = -3\n walls += 1\n\ntarget_cnt = N * N - walls - virus_cnt # 빈 공간의 개수\n\nif target_cnt == 0: # 빈 공간 없는 경우\n print(0)\nelse:\n combis = combinations(virus, M) # 활성화 바이러스 M개의 조합 만듦\n\n ans = -1\n for combi in combis:\n q = deque()\n for v in combi: # 활성화 바이러스 위치 큐에 담고, 해당 visited는 0으로\n q.append(v)\n visited[v[0]][v[1]] = 0\n\n max_time = bfs(q)\n\n for v in combi: # 다음 활성화 조합 탐색 위해 visited 초기화\n q.append(v)\n visited[v[0]][v[1]] = -2\n\n if ans == -1: # ans = -1인 경우 무조건 max_time으로 갱신\n ans = max_time\n else:\n if max_time != -1 and ans > max_time: # ans가 -1이 아닌 경우, max_time -1 아닌 때만 비교해서 갱신\n ans = max_time\n\n print(ans)\n","repo_name":"LeeSungRyul/TIL","sub_path":"Algorithm/SWEA/모의SW역량테스트/17142_연구소3.py","file_name":"17142_연구소3.py","file_ext":"py","file_size_in_byte":3008,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"39107257012","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom bs4 import BeautifulSoup\nimport time\nimport wget\n\nplace = 0\ns = Service('C:/1/chromedriver')\nbrowser = webdriver.Chrome(service=s)\nbrowser.get(f'https://eksmo.ru/ratings/RaitingYear/')\ntime.sleep(3)\n\nfor page in range(1):\n count = 0\n k = 0\n browser.get(f'https://eksmo.ru/ratings/RaitingYear/page{page}/')\n html_text = browser.page_source\n soup = BeautifulSoup(html_text, 'lxml')\n books = soup.find_all(\"a\", class_=\"book__link\")\n photos = soup.find_all(\"img\", class_=\"book__img book__img_shadow\")\n for k in photos:\n photos = 20\n count += 1\n url = k.find('img', class_=\"book__img book__img_shadow\")\n l = url.get('src')\n wget.download(l, f'C:/Users/kiree/PycharmProjects/s22702/task1/Kireenko/photo{count}.jpg')\n\n\n\n def main():\n place = 0\n data = []\n\n\n\n for book in books:\n place += 1\n name = book.find(\"div\", class_=\"book__name\")\n author = book.find(\"div\", class_=\"book__author\")\n format = book.find(\"div\", class_=\"book__format\")\n\n data.append(f\" {place} | {name.get_text()} | {author.get_text()} | {format.get_text()}\")\n\n return data\n\n\n if __name__ == \"__main__\":\n main()","repo_name":"KireenkoDenis702/s22702","sub_path":"task1/Kireenko/t1.py","file_name":"t1.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":"7068891570","text":"import tkinter as tk\n\n# Function to perform actions based on keyboard input\ndef on_key_press(event):\n key = event.keysym\n if key == 'Up':\n # Code to move the robot forward\n print(\"Moving robot forward\")\n elif key == 'Down':\n # Code to move the robot backward\n print(\"Moving robot backward\")\n elif key == 'Left':\n # Code to move the robot to the left\n print(\"Moving robot left\")\n elif key == 'Right':\n # Code to move the robot to the right\n print(\"Moving robot right\")\n elif key == 'a':\n # Code to turn the robot left\n print(\"Turning robot left\")\n elif key == 'd':\n # Code to turn the robot right\n print(\"Turning robot right\")\n\n# Function to control robot movement via buttons\ndef move_forward():\n # Code to move the robot forward\n print(\"Moving robot forward\")\n\ndef move_backward():\n # Code to move the robot backward\n print(\"Moving robot backward\")\n\ndef move_left():\n # Code to move the robot to the left\n print(\"Moving robot left\")\n\ndef move_right():\n # Code to move the robot to the right\n print(\"Moving robot right\")\n\ndef turn_left():\n # Code to turn the robot left\n print(\"Turning robot left\")\n\ndef turn_right():\n # Code to turn the robot right\n print(\"Turning robot right\")\n\n# Create main window\nroot = tk.Tk()\nroot.title(\"Robot Control\")\n\n# Bind keyboard events to the function\nroot.bind('', on_key_press)\n\n# Configure button styles\nbutton_style = {\n 'padx': 20,\n 'pady': 10,\n 'font': ('Arial', 12),\n 'bg': '#4CAF50', # Background color\n 'fg': 'blue', # Text color\n 'relief': 'raised'\n}\n\n# Create buttons for different movements with updated style\nforward_btn = tk.Button(root, text=\"Forward\", command=move_forward, **button_style)\nforward_btn.grid(row=0, column=1)\n\nbackward_btn = tk.Button(root, text=\"Backward\", command=move_backward, **button_style)\nbackward_btn.grid(row=2, column=1)\n\nleft_btn = tk.Button(root, text=\"Left\", command=move_left, **button_style)\nleft_btn.grid(row=1, column=0)\n\nright_btn = tk.Button(root, text=\"Right\", command=move_right, **button_style)\nright_btn.grid(row=1, column=2)\n\nturn_left_btn = tk.Button(root, text=\"Turn Left\", command=turn_left, **button_style)\nturn_left_btn.grid(row=3, column=0)\n\nturn_right_btn = tk.Button(root, text=\"Turn Right\", command=turn_right, **button_style)\nturn_right_btn.grid(row=3, column=2)\n\n# Run the main event loop\nroot.mainloop()\n","repo_name":"wzh4188/spider-sense","sub_path":"GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"35947144468","text":"import discord\n\nintents = discord.Intents.default()\nintents.message_content = True\nclient = discord.Client(intents=intents)\n\n@client.event\nasync def on_ready():\n print('We have logged in as {0.user}'.format(client))\n\n@client.event\nasync def on_message(message):\n if message.content.startswith('$hello'):\n await message.channel.send(\"\"\"Hello !\nWelcome to meal Recommender System\n$breakfast / $lunch / $dinner\n1: food / 2:snack\ncommand example : $breakfast 2\"\"\")\n elif message.content.startswith('$breakfast'):\n text = message.content.split(\"$breakfast \")\n listToStr = \"\".join(map(str, text))\n if int(listToStr) == 1:\n choice = \"sandwich\"\n elif int(listToStr) == 2:\n choice = \"salad\"\n recommendation = 'Food Recommendation : ' + choice\n await message.channel.send(recommendation)\n await message.channel.send(file=discord.File(choice + \".png\"))\n elif message.content.startswith('$lunch'):\n text = message.content.split(\"$lunch \")\n listToStr = \" \".join(map(str, text))\n if int(listToStr) == 1:\n choice = \"spaghetti\"\n await message.channel.send(file = discord.File(\"spaghetti.png\"))\n elif int(listToStr) == 2:\n choice = \"tacos\"\n await message.channel.send(file = discord.File(\"tacos.png\"))\n recommendation = 'Food Recommendation : ' + choice\n await message.channel.send(recommendation)\n\nclient.run(\"MTA0ODEzODg2NDEyNjA3ODk5Ng.GHVjaR.Ijsld4LPwju9QmbtKKG1aoAFQS2oFillCXYO-g\")","repo_name":"wendikardian/pygame_project","sub_path":"Python Recreate Again/m13_chatbotRecomendationSystem/chatbot.py","file_name":"chatbot.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":"73344836728","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the pairs function below.\ndef pairs(k, arr):\n arr.sort()\n l = 0;\n c = 0;\n\n for r in range(1, n):\n while (arr[l] + k < arr[r]):\n l += 1\n if arr[l] + k == arr[r]:\n c += 1\n return c\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n nk = input().split()\n\n n = int(nk[0])\n\n k = int(nk[1])\n\n arr = list(map(int, input().rstrip().split()))\n\n result = pairs(k, arr)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","repo_name":"Gothdn/HackerRankChallenges","sub_path":"Pairs.py","file_name":"Pairs.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"29379528419","text":"us=input(\"Ingrese su cadena: \")\noneexist=False\nl = []\nx = 0\nr = \"\"\nwhile True:\n try:\n y=int(float(input(\"Ingrese el largo: \")))\n if (y<=1):\n assert y>=2\n elif(y>len(us)):\n assert y len(us)):\n print(\"Debe ser menor que la longitud de la cadena, la cual es: \",len(us))\n except ValueError:\n print(\"Error, debe ser numerico\")\nwhile y<=len(us):\n for a in range(x,y):\n r+=us[a]\n l.append(r)\n r=\"\"\n x+=1\n y+=1\nfor b in l:\n if (l.count(b)==1):\n print(b)\n if oneexist==False:\n oneexist=True\nif not oneexist:\n print(\"Ninguna\")","repo_name":"pabloschwarzenberg/grader","sub_path":"hito2_ej3/hito2_ej3_2dee3fc3422ca52d4857121ddb05dec7.py","file_name":"hito2_ej3_2dee3fc3422ca52d4857121ddb05dec7.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"72982336249","text":"from other import select\n\n\nclass Friends:\n\n def __init__(self, api, config):\n self.__api = api\n self.__friends_list = api.friends.get(user_id='', order='hints', fields='nickname')\n self.__friends_list = self.__friends_list['items']\n self.__config = config\n self.__friends_online_list = []\n\n def list(self):\n \"\"\"Выводит список друзей\"\"\"\n n = 1\n for x in self.__friends_list:\n print(n, end='. ')\n print(x['first_name'], x['last_name'], end='. ')\n if x['online'] == 1 and self.__config.getboolean('FRIENDS', 'show_status'):\n print('Online', end='. ')\n elif self.__config.getboolean('FRIENDS', 'show_status'):\n print('Offline', end='. ')\n if self.__config.getboolean('FRIENDS', 'show_ids'):\n print('id:', x['user_id'])\n else:\n print()\n n += 1\n\n def online_list(self):\n \"\"\"Выводит список друзей онлайн\"\"\"\n self.update_data()\n n = 1\n for x in self.__friends_online_list:\n print(n, end='. ')\n print(x['first_name'], x['last_name'], end='. ')\n if self.__config.getboolean('FRIENDS', 'show_ids'):\n print('id:', x['user_id'])\n else:\n print()\n n += 1\n\n def select_friend(self, online=0):\n \"\"\"Выбор друга из списка друзей(или из списка друзей онлайн, при передаче аргумента online=1).\n Возвращает словарь с id, именем и фамилией выбранного друга.\n\n \"\"\"\n if online == 1:\n self.online_list()\n print(len(self.__friends_online_list) + 1, '. Назад', sep='')\n num = select(len(self.__friends_online_list) + 1)\n if num == len(self.__friends_online_list) + 1:\n return ''\n user = self.__friends_online_list[num - 1]\n else:\n self.list()\n print(len(self.__friends_list) + 1, '. Назад', sep='')\n num = select(len(self.__friends_list) + 1)\n if num == len(self.__friends_list) + 1:\n return ''\n user = self.__friends_list[num - 1]\n\n tmp = dict(user_id=user['id'], first_name=user['first_name'], last_name=user['last_name'])\n return tmp\n\n def update_data(self):\n \"\"\"Обновляет список друзей и список друзей онлайн\"\"\"\n self.__friends_list = self.__api.friends.get(user_id='', order='hints', fields='nickname')\n self.__friends_list = self.__friends_list['items']\n self.__friends_online_list = []\n for x in self.__friends_list:\n if x['online'] == 1:\n self.__friends_online_list.append(x)\n\n def get_user_friends(self, uid):\n \"\"\"Выводит список друзей пользователя с указаным id\"\"\"\n f_list = self.__api.friends.get(user_id=uid, order='hints', fields='nickname')\n f_list = f_list['items']\n n = 1\n for x in f_list:\n print(n, end='. ')\n print(x['first_name'], x['last_name'], end='. ')\n if x['online'] == 1 and self.__config.getboolean('FRIENDS', 'show_status'):\n print('Online', end='. ')\n elif self.__config.getboolean('FRIENDS', 'show_status'):\n print('Offline', end='. ')\n if self.__config.getboolean('FRIENDS', 'show_ids'):\n print('id:', x['user_id'])\n else:\n print()\n n += 1\n","repo_name":"fedorzaplatin/vk-python-client","sub_path":"class_friends.py","file_name":"class_friends.py","file_ext":"py","file_size_in_byte":3738,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"75024241849","text":"import paho.mqtt.client as mqtt\nimport time\n\n# Diese paar Zeilen Code reichen aus um sich bei einem Channel einzuschreiben\n\n# Diese Methode wird aufgerunfen, wenn eine Nachricht fuer einen Channel hereinkommt\ndef on_message(client, userdata, message):\n print(\"message received \" ,str(message.payload.decode(\"utf-8\")))\n print(\"message topic=\",message.topic)\n print(\"message qos=\",message.qos)\n print(\"message retain flag=\",message.retain)\n\n# Wenn Logging-Information fuer den Client vorhanden ist (gut fuer das Fehlersuchen)\ndef on_log(client, userdata, level, buf):\n print(\"log: \",buf)\n\ndef on_connect(client, userdata, flags, rc, properties=None):\n if rc == 0: #Wenn der return code 0 ist hat die Verbindung gepasst\n print(\"CONNECTION established\")\n else:\n print(\"authentication error.\")\n\n\nif __name__ == '__main__':\n client = mqtt.Client('test') # Der Parameter ist die client-ID, diese sollte möglichst eindeutig sein.\n client.username_pw_set('albert', 'XXX')\n client.on_connect = on_connect\n client.connect('127.0.0.1', port=2222) # Im Moment verwenden wir die lokale mosquitto Installation, spaeter durch die IP zu ersetzen\n\n client.subscribe(\"house/light\") # Eintragen fuer einen bestimmten Channel\n client.on_message = on_message # die on_message-Methode soll aufgerfufen werden wenn einen neue Nachricht hereinkommt\n client.on_log = on_log\n client.loop_start() # loop starten\n #client.loop_forever() # loop starten in Endlosschleife (blockiert)\n time.sleep(1000000)\n print(\"EXIT\")","repo_name":"albertgreinoecker/raspberry_examples","sub_path":"ex_03_mqtt_mosquitto_subscribe.py","file_name":"ex_03_mqtt_mosquitto_subscribe.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"de","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"14045896216","text":"# importing libraries and packages\nimport snscrape.modules.twitter as sntwitter\nimport pandas as pd\n\n# VADER Sentiment Analysis\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\n\nanalyzer = SentimentIntensityAnalyzer()\n\n# detect language and filter English sentences\nfrom langdetect import detect, DetectorFactory\n# make the result unique\nDetectorFactory.seed = 0\n\nfrom datetime import timedelta\n\n# Creating list to append tweet data to\ntweets_list = []\n\n# Using TwitterSearchScraper to scrape data and append tweets to list\n# From: iPhone 13: 09-24; Apple Watch: 10-15; MacBook Pro: 10-26\n# Till: 11-21 (code: 11-22)\nfor i,tweet in enumerate(sntwitter.TwitterSearchScraper('MacBook Pro since:2021-10-26 until:2021-11-22 lang:en').get_items()):\n try:\n if tweet.content is not None and detect(tweet.content) == 'en':\n Date = tweet.date\n\n # Combining the date for stock price\n if Date.isoweekday() in range(1,5) and Date.hour in range(15, 24):\n Stock_date = Date.date() + timedelta(days=1)\n elif Date.isoweekday() == 5 and Date.hour in range(15, 24):\n Stock_date = Date.date() + timedelta(days=3)\n elif Date.isoweekday() == 6:\n Stock_date = Date.date() + timedelta(days=2)\n elif Date.isoweekday() == 7:\n Stock_date = Date.date() + timedelta(days=1)\n else:\n Stock_date = Date.date()\n\n # Analyze sentiment parameters\n vs = analyzer.polarity_scores(tweet.content)\n\n # Append data to the tweets_list\n tweets_list.append([Date.date(), Date.strftime('%H:%M:%S'), Stock_date, tweet.id, tweet.content,\\\n tweet.username, vs['neg'], vs['neu'], vs['pos'], vs['compound']])\n except:\n print('Here is an error')\n \n# Creating a dataframe from the tweets list above\ntweets_df = pd.DataFrame(tweets_list, columns=['Date','Time', 'Combined_Stock_Date', 'Tweet_Id', 'Text',\\\n 'Username', 'neg', 'neu', 'pos', 'compound'])\n\ntweets_df.to_csv('/Users/krystalgong/Desktop/twitter2021_iPhone13_MacBookPro.csv')","repo_name":"krystalgong/Twitter_sentiment_analysis","sub_path":"twitter_sentiment_analysis.py","file_name":"twitter_sentiment_analysis.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"35853656207","text":"\"\"\"\nEste script contiene código que es útil para diferentes scripts en este proyecto\n\n\"\"\"\n\nimport datetime as dt\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nimport matplotlib.colors as colors\nfrom matplotlib.collections import PolyCollection\nfrom my_lib import pi_connect as p\nyyyy_mm_dd_hh_mm_ss = \"%d-%m-%Y %H:%M:%S\"\nfmt_dd_mm_yyyy_hh_mm = \"dd/MMM/yy HH:mm\"\nfmt_dd_mm_yyyy = \"dd/MMM/yyyy\"\nfmt_dd_mm_yy_ = \"dd_MMM_yyyy\"\npi_svr = p.PIserver()\n\nlb_tag = \"Tag\"\nlb_name = \"Nombre\"\nlb_expression = \"Expresion\"\nlb_tiempo = \"Tiempo Disponibilidad en minutos\"\nlb_per_dispo = \"Porcentaje_Disp\"\nlb_state = \"Estado\"\nlb_date = \"Fecha\"\nlb_period = \"Periodo\"\nlb_activa = \"Activa\"\nlb_protocol = \"Protocolo\"\nlb_prioridad = \"Prioridad\"\nlb_filter = \"Filter\"\n\n\ndef define_time_range_for_yesterday():\n tdy = dt.datetime.now().strftime(yyyy_mm_dd_hh_mm_ss)\n ytd = dt.datetime.now() - dt.timedelta(days=1)\n time_range = pi_svr.time_range(ytd, tdy)\n return time_range\n\ndef define_time_range_for_date(date:dt.datetime):\n ytd = date - dt.timedelta(days=1)\n time_range = pi_svr.time_range(ytd, date)\n return time_range\n\ndef define_time_range_for_last_week():\n tdy = dt.datetime.now().strftime(yyyy_mm_dd_hh_mm_ss)\n wkt = dt.datetime.now() - dt.timedelta(days=7)\n time_range = pi_svr.time_range(wkt, tdy)\n return time_range\n\n\ndef process_avalability_from_excel_file(excel_file, sheet_name, time_range_to_run,\n span=pi_svr.span(\"1d\"), time_unit=\"mi\"):\n\n # leyendo archivo Excel y filtrando aquellos que están activos:\n df = pd.read_excel(excel_file, sheet_name=sheet_name)\n df = df[df[\"Activa\"] == \"x\"]\n df[lb_tiempo] = [0 for ix in df.index] # iniciando la columna lb_tiempo con 0\n df[lb_state] = [\"\" for ix in df.index] # iniciando la columna lb_state con vacío\n\n for ix in df.index:\n # nombre de la tag\n tag_name = df[lb_tag].loc[ix]\n # expresión a tomar en cuenta:\n expression = df[lb_expression].loc[ix]\n # expression = f\"'{tag_name}' = \\\"{exp}\\\"\"\n\n # pt es un PointTag que permitirá obtener datos del servidor\n # si pt.pt es None, entonces dicha tag no existe\n pt = p.PI_point(pi_svr, tag_name)\n if pt.pt is not None:\n value = pt.time_filter(time_range_to_run, expression, span, time_unit)\n df.loc[[ix], lb_tiempo] = value[tag_name][0]\n df.loc[[ix], lb_state] = str(pt.snapshot().Value)\n df.loc[[ix], lb_date] = str(pt.snapshot().Timestamp)\n df.loc[[ix], lb_period] = str(time_range_to_run).replace(\"00:00:00\", \"\")\n df.sort_values(by=[lb_prioridad, lb_tiempo], inplace=True)\n return df\n\n\ndef get_history_from(excel_file, sheet_name, time_range, span=pi_svr.span(\"10 m\")):\n # leyendo archivo Excel y filtrando aquellos que están activos:\n df = pd.read_excel(excel_file, sheet_name=sheet_name)\n df = df[df[\"Activa\"] == \"x\"]\n df_hist = pd.DataFrame()\n tgs = list()\n for ix in df.index:\n # nombre de la tag\n tag_name = df[lb_tag].loc[ix]\n\n # pt es un PointTag que permitirá obtener datos del servidor\n # si pt.pt es None, entonces dicha tag no existe\n pt = p.PI_point(pi_svr, tag_name)\n if pt.pt is not None:\n # adjuntar el dataframe con la historia:\n tgs.append(tag_name)\n df_tag = pt.interpolated(time_range, span, numeric=False)\n df_hist = pd.concat([df_hist, df_tag], axis=1, sort=True)\n\n # filtrar solo tags existentes:\n df_hist = df_hist[tgs]\n\n return df, df_hist\n\n\ndef get_block(from_label: str, to_label: str, html_str: str):\n str_result = str()\n from_index = html_str.find(from_label)\n to_index = html_str.find(to_label)\n if from_index > 0 and to_index > 0:\n str_result = html_str[from_index + len(from_label): to_index]\n return str_result\n\n\ndef replace_block(from_label: str, to_label: str, html_str: str, to_replace: str):\n str_result = html_str\n from_index = html_str.find(from_label)\n to_index = html_str.find(to_label)\n if from_index > 0 and to_index > 0:\n str_result = html_str[:from_index] + to_replace + html_str[to_index:]\n return str_result\n\n\ndef save_html(html_str, path_html_to_save):\n # Guardar el archivo html en la carpeta reportes:\n try:\n Html_file = open(path_html_to_save, \"w\", encoding='utf-8')\n Html_file.write(html_str)\n Html_file.close()\n except Exception as e:\n print(e)\n\n\ndef get_state_colors(excel_path:str, sheet_name:str):\n columns = [\"ESTADO\", \"COLOR\"]\n try:\n df = pd.read_excel(excel_path, sheet_name)\n df = df[columns]\n color_dict = dict()\n for ste, sus in zip(list(df[\"ESTADO\"]), list(df[\"COLOR\"])):\n color_dict[ste] = sus\n return True, color_dict\n except Exception as e:\n print(e)\n return False, dict()\n\n\ndef get_state_translation(excel_path:str, sheet_name:str):\n columns = [\"ESTADO\", \"SUSTITUCION\"]\n try:\n df = pd.read_excel(excel_path, sheet_name)\n df = df[columns]\n state_dict = dict()\n for ste, clr in zip(list(df[\"ESTADO\"]), list(df[\"SUSTITUCION\"])):\n state_dict[ste] = clr\n return True, state_dict\n except Exception as e:\n print(e)\n return False, dict()\n\n\ndef get_translation(series: pd.Series, excel_path:str, sheet_name: str):\n success, dict_t = get_state_translation(excel_path, sheet_name)\n if not success:\n return series\n states = list(set(series))\n for st in states:\n if not st in dict_t.keys():\n continue\n replace = dict_t[st]\n series.replace(to_replace=st, value=replace, inplace=True)\n return series\n\n\ndef read_excel(excel_file, sheet_name):\n try:\n df = pd.read_excel(excel_file, sheet_name=sheet_name)\n return True, df, \"Leído exitosamente\"\n except Exception as e:\n print(e)\n return False, pd.DataFrame(), \"No se ha podido leer el archivo \\n\" + str(e)\n\n\ndef generate_bar_estatus(series: pd.Series, fig_size, path_to_save: str = None, color_map: dict = None):\n from matplotlib.patches import Patch\n plt.rcParams.update({'font.size': 24})\n states = list(set(series))\n # states.sort()\n ti_i = series.index[0] # tiempo inicial del estado\n st_i = series[0] # estado inicial\n data = list()\n for t, state in zip(series.index[1:], series):\n if st_i != state:\n data.append((ti_i, t, st_i)) # tiempo inicial, tiempo final, estado\n st_i = state\n ti_i = t\n data.append((ti_i, series.index[-1], st_i))\n cats = dict()\n color_mapping = dict()\n legend_elements = list()\n for ix, st in enumerate(states):\n cats[st] = 0\n if color_map is not None and st in color_map.keys():\n color_mapping[st] = color_map[st]\n else:\n color_mapping[st] = f\"C{ix}\"\n\n legend_elements.append(Patch(facecolor=color_mapping[st], label=st))\n\n verts = []\n colors = []\n for d in data:\n v = [(mdates.date2num(d[0]), cats[d[2]] - .05),\n (mdates.date2num(d[0]), cats[d[2]] + .05),\n (mdates.date2num(d[1]), cats[d[2]] + .05),\n (mdates.date2num(d[1]), cats[d[2]] - .05),\n (mdates.date2num(d[0]), cats[d[2]] - .05)]\n verts.append(v)\n colors.append(color_mapping[d[2]])\n\n bars = PolyCollection(verts, facecolors=colors)\n\n fig, ax = plt.subplots(figsize=fig_size)\n ax.add_collection(bars)\n\n days = mdates.DayLocator()\n days_fmt = mdates.DateFormatter('%d-%b')\n hours = mdates.HourLocator()\n hours_fmt = mdates.DateFormatter('%H')\n\n #ax.xaxis.set_major_locator(days)\n #ax.xaxis.set_minor_locator(hours)\n\n #ax.xaxis.set_major_formatter(days_fmt)\n #ax.xaxis.set_minor_formatter(hours_fmt)\n\n locator = mdates.AutoDateLocator(minticks=1)\n ax.xaxis.set_major_locator(locator)\n ax.xaxis.set_major_formatter(days_fmt)\n\n locator = mdates.AutoDateLocator(minticks=5, maxticks=8)\n ax.xaxis.set_minor_locator(locator)\n ax.xaxis.set_minor_formatter(hours_fmt)\n\n\n ax.set_yticks([0])\n ax.set_yticklabels([\"\"])\n\n lgd = ax.legend(handles=legend_elements, loc=\"center left\", bbox_to_anchor=(1, 0.5))\n text = ax.text(0, 0, \"\", transform=ax.transAxes)\n ax.autoscale()\n if path_to_save is not None:\n try:\n fig.savefig(path_to_save, bbox_extra_artists=(lgd, text), bbox_inches='tight',\n format=\"png\", transparent=True, dpi=30)\n return True, fig\n except Exception as e:\n print(e)\n return False, fig\n else:\n return True, fig\n\n\ndef hazard_matrix():\n import numpy as np\n plt.rcParams.update({'font.size': 16})\n critic_level = [0.0, 0.33, 0.67, 1]\n critic_name = [\"No \\ncrítico\", \"Baja\", \"Media\", \"Alta\"]\n n = 7\n availability_level = [x/n for x in range(n+1)]\n df = pd.DataFrame(columns=[str(a) for a in availability_level],\n index=[str(c) for c in critic_level])\n for c in critic_level:\n for a in availability_level:\n df.loc[[str(c)], [str(a)]] = int(c*(a)*100)\n print(df.info())\n color_lst = [(0, 'white'), (0.33, 'yellow'), (0.67, 'orange'), (1, 'red')]\n cmap = colors.LinearSegmentedColormap.from_list(\"risk_scale\", color_lst)\n\n fig, ax = plt.subplots(1, 1, figsize=(9, 7))\n pcm = ax.pcolor(df, cmap=cmap)\n ax.set_yticks(np.arange(0.5, len(df.index), 1))\n ax.set_xticks(np.arange(0.5, len(df.columns), 1))\n ax.set_yticklabels(critic_name)\n ax.set_xticklabels([str(round(x, 1)) for x in availability_level])\n ax.set_ylabel(\"Nivel de Criticidad\")\n ax.set_xlabel(\"Indisponibilidad\")\n\n cbar = fig.colorbar(pcm, ax=ax, orientation='vertical', pad=0.09)\n cbar.ax.set_title('Riesgo (%)', y=1.04)\n\n plt.tight_layout()\n plt.show()\n print(df)\n\n# hazard_matrix()\n\n","repo_name":"Borreguin/RepoSupRemoto","sub_path":"my_lib/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":9988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"34893363940","text":"#!/usr/bin/env python2\nfrom __future__ import print_function\nimport os, sys, random\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'src')))\n\nrandom.seed(0) # let's have some deterministic shuffling\n\nimport numpy as np\nimport theano\nimport itertools\nimport sklearn\nfrom imutypelib.config import Config\nfrom imutypelib.network import Network\nfrom imutypelib.stats import Stats\nfrom imutypelib.pipeline import get_samples\n\n\ndef divide_test_training_data(data, ratio):\n # data_split = [training, test]\n s = int(ratio * len(data))\n data_split = (data[:s], data[s:])\n return data_split\n\ndef build_batch(config, samples, size=None):\n indices = [random.randint(0, len(samples)-1) for i in range(size)] if size else list(range(len(samples)))\n random.shuffle(indices)\n inputs, outputs = [], []\n for i in indices:\n inputs.append(samples[i][1])\n outputs.append([(1 if key_code == samples[i][2] else 0) for key_code in [0] + config.key_codes])\n\n return (\n np.array(inputs, dtype=theano.config.floatX),\n np.array(outputs, dtype=theano.config.floatX),\n )\n\n\nif __name__ == '__main__':\n config = Config(sys.argv[1])\n if len(sys.argv) > 2:\n config.model_file = config.model_file.replace('.npz', '-{}.npz'.format(sys.argv[2]))\n\n network = Network(config)\n network.load()\n\n if os.path.exists(config.samples_file):\n with np.load(config.samples_file) as npzfile:\n samples = npzfile['samples']\n else:\n samples = get_samples(config)\n\n np.random.shuffle(samples)\n training, testing = divide_test_training_data(samples, config.training_ratio)\n\n stats = Stats(config)\n\n X_test, y_test = build_batch(config, samples)\n\n actual, predicted, _ = network.test(X_test, y_test)\n print(sklearn.metrics.confusion_matrix(actual, predicted))\n","repo_name":"imutype/bachelor","sub_path":"ros/src/imutype/tools/confusion.py","file_name":"confusion.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"42102978245","text":"import json\nimport traceback\nimport os\nfrom ecmt import settings\nfrom django.db import connection\nfrom django.core import serializers\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom pypinyin import lazy_pinyin\n# Create your views here.\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom teacher.models import Teacher, Dept, Profession\n\ndef cmp_rule(elem):\n #print(lazy_pinyin(elem['name']))\n return lazy_pinyin(elem['name'])\n\n@csrf_exempt\ndef listTeacher(request):\n res = {'code': -1, 'msg': 'error', 'data': {}}\n try:\n params = request.POST.dict()\n params['status'] = 1\n if 'name' in params.keys():\n if 'deptId' in params.keys():\n res['data']['count'] = Teacher.objects.filter(deptId=params['deptId']).filter(name__contains=params['name']).count()\n qset = Teacher.objects.filter(deptId=params['deptId']).filter(name__contains=params['name'])\n else:\n res['data']['count'] = Teacher.objects.filter(name__contains=params['name']).count()\n qset = Teacher.objects.filter(name__contains=params['name'])\n else:\n res['data']['count'] = Teacher.objects.filter(**params).count()\n qset = Teacher.objects.filter(**params)\n res['data']['teachers'] = []\n ts = json.loads(serializers.serialize(\"json\", qset))\n for t in ts:\n data_row = t['fields']\n data_row['id'] = t['pk']\n res['data']['teachers'].append(data_row)\n res['code'] = 0\n res['msg'] = 'success'\n res['data']['teachers'].sort(key=cmp_rule)\n except Exception as e:\n res['code'] = -2\n res['msg'] = e\n res['data'] = []\n return HttpResponse(json.dumps(res))\n\n@csrf_exempt\ndef listDept(request):\n res = {'code': -1, 'msg': 'error', 'data': {}}\n try:\n params = request.POST.dict()\n params['status'] = 1\n res['data']['count'] = Dept.objects.filter(**params).count()\n res['data']['depts'] = []\n qset = Dept.objects.filter(**params)\n ts = json.loads(serializers.serialize(\"json\", qset))\n for t in ts:\n data_row = t['fields']\n data_row['id'] = t['pk']\n res['data']['depts'].append(data_row)\n res['code']=0\n res['msg']='success'\n res['data']['depts'].sort(key=cmp_rule)\n except Exception as e:\n res['code'] = -2\n res['msg'] = e\n res['data'] = []\n return HttpResponse(json.dumps(res))\n\n@csrf_exempt\ndef listProfession(request):\n res = {'code': -1, 'msg': 'error', 'data': {}}\n try:\n res['data']['professions'] = []\n qset = Profession.objects.filter(status=1)\n ts = json.loads(serializers.serialize(\"json\", qset))\n for t in ts:\n data_row = t['fields']\n data_row['id'] = t['pk']\n res['data']['professions'].append(data_row)\n res['code']=0\n res['msg']='success'\n res['data']['professions'].sort(key=cmp_rule)\n except Exception as e:\n res['code'] = -2\n res['msg'] = e\n res['data'] = []\n return HttpResponse(json.dumps(res))\n\n@csrf_exempt\ndef deleteAndInsertProfession(request):\n res = {'code': -1, 'msg': 'error', 'data': {}}\n try:\n f = open(os.path.join(settings.BASE_DIR,\"ecmt\",\"profession.txt\"), \"r\", encoding=\"utf-8\") #设置文件对象\n data = f.readlines() #直接将文件中按行读到list里\n cursor=connection.cursor()\n sql = 'delete from teacher_profession'\n cursor.execute(sql)\n sql2 = 'alter table teacher_profession AUTO_INCREMENT 1' \n cursor.execute(sql2)\n for i in range(0, len(data)):\n if i == 0:\n continue\n insert = Profession(name=data[i].replace('\\n', '').replace('\\r', ''))\n insert.save()\n f.close() #关闭文件\n res = {'code': 0, 'msg': '专业添加成功', 'data': data}\n except Exception as e:\n res['code'] = -2\n res['msg'] = e\n res['data'] = []\n return HttpResponse(json.dumps(res))","repo_name":"Above-The-Cloud/ecmt","sub_path":"teacher/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"29496406183","text":"'''Basic class for word embedding'''\n\nimport struct\nimport mimetypes\nimport numpy as np\nfrom .. import LOGGER\n\nclass WordVector:\n '''\n word embedding class:\n it is created from the word2vec type word_embedding, and it contains\n - vocab\n - vectors\n '''\n # Special symbols for padding and unknown word\n PAD = \"xxPADxx\"\n UNK = \"xxUNKxx\"\n PAD_ID = 0\n UNK_ID = 1\n\n def __init__(self, inputfile):\n '''\n word_vector object\n build from a either a wordvector binary or txt file\n\n params:\n inputfile: a single filepath as string\n '''\n vocab, vectors = self.read_embeddings(inputfile)\n self.vocab = vocab\n self.vectors = vectors\n self.vocab_to_index = self.create_vocab_index_dict(self.vocab)\n\n @staticmethod\n def create_vocab_index_dict(vocab):\n return {word: index for index, word in enumerate(vocab)}\n\n @property\n def vocab_size(self):\n '''\n get the number of tokens in vocabulary\n '''\n return self.vocab.shape[0]\n\n @property\n def vector_size(self):\n '''\n get the length of the word embedding\n '''\n return self.vectors.shape[1]\n\n @property\n def unk_vector(self):\n '''\n get the default vector for the unkown word\n '''\n return self.vectors[self.UNK_ID]\n\n def get_index(self, word):\n '''\n lookup the index given the word in the embedding\n '''\n index = self.UNK_ID\n if word in self.vocab_to_index:\n index = self.vocab_to_index[word]\n return index\n\n def get_vector(self, word):\n '''\n lookup the vector given the word in the embedding\n '''\n vector_index = self.get_index(word)\n if vector_index < self.vocab_size:\n vector = self.vectors[vector_index]\n return vector\n\n def get_vectors(self, words):\n '''\n lookup the vectors given words\n '''\n indexes = [self.get_index(word) for word in words]\n return np.take(self.vectors, indexes, axis=0)\n\n def get_word(self, index):\n '''\n look up the token in vocabulary with given index\n '''\n return self.vocab[index]\n\n def __contains__(self, word):\n return word in self.vocab\n\n def cosine_nearest_neighbors(self, input_vector, nr_neighbors=10):\n '''\n compute the nearest n neighbours of any input vector\n '''\n metrics = np.dot(self.vectors, input_vector.T)\n best = np.argsort(metrics)[::-1][1:nr_neighbors + 1]\n best_metrics = metrics[best]\n return best, best_metrics\n\n def save_sublist(self, words, output_file):\n \"\"\"\n Generate a smaller binary word-embeddings model file\n with only the given list of words.\n \"\"\"\n\n known_words = [word.upper()\n for word in words\n if self.get_index(word.upper()) >= 2]\n nwords = len(known_words)\n LOGGER.info('out of %s tokens from input, save %s words with dimension %s to %s',\n len(words), nwords, self.vector_size, output_file)\n with open(output_file, 'wb') as ostream:\n # store header\n ostream.write(\"{} {}\\n\".format(nwords, self.vector_size).encode('ascii'))\n\n # store word and word_vector\n for word in known_words:\n ostream.write(\"{} \".format(word).encode('utf-8'))\n ostream.write(\n struct.pack(\"f\" * self.vector_size, *self.get_vector(word)))\n ostream.write(\" \".encode('utf-8'))\n\n @classmethod\n def read_embeddings(cls, inputfile, vacab_unicode_size=78):\n '''\n Read embeddings files and return a vocabulary and vectors array.\n\n params:\n inputfile: a single filepath as string\n vacab_unicode_size: max length of words in vocab (chars)\n\n returns:\n vocab: [vocab_size, vacab_unicode_size] unicode array\n vectors: [vocab_size, vector_size] float array containing\n embeddings\n '''\n\n # Read headers to get vocab and vector size\n mimetype = mimetypes.guess_type(inputfile)\n vocab_size, vector_size = cls.read_embeddings_header(inputfile, mimetype)\n vocab_size += 2 # +2 for pad and unknown token\n\n # Create vocab and vector arrays\n vocab = np.empty(vocab_size, dtype='= abs(mina) # bool, or indices where +ve values win\n negative = np.logical_not(positive) # bool, or indices where -ve values win\n out = np.zeros(embeddings.shape[-1], dtype=embeddings.dtype)\n out[positive] = maxa[positive]\n out[negative] = mina[negative]\n return out\n","repo_name":"tilaboy/tk-nn-classifier","sub_path":"tk_nn_classifier/data_loader/word_vector.py","file_name":"word_vector.py","file_ext":"py","file_size_in_byte":7770,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"20321725330","text":"from django.conf.urls.defaults import *\r\n# Uncomment the next two lines to enable the admin:\r\nfrom django.contrib import admin\r\nfrom os import path\r\nDOCUMENT_ROOT = path.abspath(path.dirname(__file__))\r\nadmin.autodiscover()\r\n\r\nurlpatterns = patterns('bmforum.planet.views',\r\n url(r'^$', 'blogList', name='blogList'),\r\n url(r'^planetRegister/$','planetRegister', name='planetRegister'),\r\n url(r'^planetUnregister/$','planetUnregister', name='planetUnregister'),\r\n)\r\n","repo_name":"enginmanap/archdoom","sub_path":"bmforum/bmforum/planet/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"20661275957","text":"import pandas as pd\nimport datetime as dt\nimport os\nimport re\n\nemployee_csv = os.path.join(\"..\",\"PyBoss\", \"employee_data.csv\")\nemployee_data = pd.read_csv(employee_csv)\n# new data frame with split value columns \n#using split function to look by space between strings\nnew_cols_name = employee_data[\"Name\"].str.split(\" \", n = 1, expand = True) \n# making seperate first name column from new data frame \nemployee_data[\"First Name\"]= new_cols_name[0] \n# making seperate last name column from new data frame \nemployee_data[\"Last Name\"]= new_cols_name[1] \n# Dropping old Name columns \nemployee_data.drop(columns =[\"Name\"], inplace = True) \n# df display \n#print(employee_data )\n#convert the string to datetime\nemployee_data['DOB'] = pd.to_datetime(employee_data['DOB'])\n#convert the DOB column to MM/DD/YYYY format\nemployee_data['DOB'] = employee_data['DOB'].dt.strftime('%m/%d/%Y')\n#print(employee_data['DOB'])\n#Replace the SSN to mask the first 5 characters\nemployee_data['SSN'] = employee_data['SSN'].replace(r'\\d\\d\\d-\\d\\d-', value='***-**-',regex=True) \n#Store the State abbreviations to the us_state_abbrev dictionary\nus_state_abbrev = {\n 'Alabama': 'AL',\n 'Alaska': 'AK',\n 'Arizona': 'AZ',\n 'Arkansas': 'AR',\n 'California': 'CA',\n 'Colorado': 'CO',\n 'Connecticut': 'CT',\n 'Delaware': 'DE',\n 'Florida': 'FL',\n 'Georgia': 'GA',\n 'Hawaii': 'HI',\n 'Idaho': 'ID',\n 'Illinois': 'IL',\n 'Indiana': 'IN',\n 'Iowa': 'IA',\n 'Kansas': 'KS',\n 'Kentucky': 'KY',\n 'Louisiana': 'LA',\n 'Maine': 'ME',\n 'Maryland': 'MD',\n 'Massachusetts': 'MA',\n 'Michigan': 'MI',\n 'Minnesota': 'MN',\n 'Mississippi': 'MS',\n 'Missouri': 'MO',\n 'Montana': 'MT',\n 'Nebraska': 'NE',\n 'Nevada': 'NV',\n 'New Hampshire': 'NH',\n 'New Jersey': 'NJ',\n 'New Mexico': 'NM',\n 'New York': 'NY',\n 'North Carolina': 'NC',\n 'North Dakota': 'ND',\n 'Ohio': 'OH',\n 'Oklahoma': 'OK',\n 'Oregon': 'OR',\n 'Pennsylvania': 'PA',\n 'Rhode Island': 'RI',\n 'South Carolina': 'SC',\n 'South Dakota': 'SD',\n 'Tennessee': 'TN',\n 'Texas': 'TX',\n 'Utah': 'UT',\n 'Vermont': 'VT',\n 'Virginia': 'VA',\n 'Washington': 'WA',\n 'West Virginia': 'WV',\n 'Wisconsin': 'WI',\n 'Wyoming': 'WY',\n}\n#Replace the state name to abbreviations using the dict value\nemployee_data['State'].replace(us_state_abbrev, inplace=True)\n#Organize the dataframe \norganized_data = employee_data[[\"Emp ID\",\"First Name\",\"Last Name\",\"DOB\",\"SSN\",\"State\"]]\n#Store the organized data to a xlsx\norganized_data.to_csv(\"OrganizedEmpData.csv\", index=False, header=True)","repo_name":"Priyarag/python-challenge","sub_path":"PyBoss/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"28924888716","text":"#!/usr/bin/env python\r\n# coding: utf-8\r\n\r\n# # Lab 3\r\n# \r\n# Welcome to your third lab! This notebook contains all the code and comments that you need to submit. Labs are two weeks long and the places where you need to edit are highlighted in red. Feel free to add in your own markdown for additional comments.\r\n# \r\n# __Submission details: make sure you have run all your cells from top to bottom (you can click _Kernel_ and _Restart Kernel and Run All Cells_). Submit this Jupyter Notebook and also submit the .py file that is generated.__\r\n\r\n# In[3]:\r\n\r\n\r\n## This code snippet does not need to be edited\r\nimport os\r\nos.environ[\"KMP_DUPLICATE_LIB_OK\"] = \"TRUE\"\r\nfrom python_environment_check import check_packages\r\nfrom python_environment_check import set_background\r\n\r\n## Colour schemes for setting background colour\r\nwhite_bgd = 'rgba(0,0,0,0)'\r\nred_bgd = 'rgba(255,0,0,0.2)'\r\n\r\n\r\n# In[4]:\r\n\r\n\r\n## Code snippets in red (similar to this) is where you need to edit your answer)\r\n# Set your student ID and name here:\r\n\r\nstudent_number = 12345678 # 12345678\r\nstudent_name = \"John Doe\" # \"John Doe\"\r\n\r\nset_background(red_bgd)\r\n\r\n\r\n# ## What you are going to do in this lab exercise!\r\n# \r\n# In this laboratory exercise, you will create algorithms to train non-linear models using MLPs. \r\n# \r\n# In all of the tasks below, you should use PyTorch Lightning to design, train and test MLP models. You can use any pre-written libraries like matplotlib, pandas and numpy to visualize your results. \r\n# \r\n#
\r\n# \r\n# - **Section 1** : Approximate the sine function.\r\n# - **Section 2** : Design a shallow MLP for the fashion MNIST\r\n# - **Section 3** : Comparing the performance of Shallow MLP vs Deep MLP.\r\n# \r\n#
\r\n\r\n# ## Section 1 : Approximate the sine function\r\n\r\n#
\r\n# \r\n# ## What you should do in this task!\r\n# \r\n# In this section, we will approximate the sine function with a neural network to get a sense of how architecture and hyperparameters affect neural network performance. \r\n# \r\n# #### In this task, you will work on the following points:\r\n# 1. As the first step you should have PyTorch and PyTorch-Lightning installed in your local machine. We have given you the set of necessary libraries and details on PyTorch functionalities that you need to use when implementing algorithm for Task 1. The first sub task is to create your custom dataset using PyTorch datasets and dataloaders.\r\n# \r\n# 2. Define the custom dataset class (i.e., Train and Test datasets) and visualize the train dataset you've created.\r\n# \r\n# 3. Design the Shallow Linear MLP model using PyTorch Lightning Module.\r\n# \r\n# 4. Train and evaluate the MLP model on defined train dataset and test dataset.\r\n# \r\n# 5. Visualize experimental results using Matplotlib.\r\n# \r\n# \r\n# Before approaching, we will be introducing Pytorch Lightning Neural Network structure, Pytorch datasets, dataloaders and optimizers.\r\n# \r\n# \r\n\r\n# ## PyTorch & PyTorch-Lightning Installation\r\n# \r\n# What are the differences between PyTorch and PyTorch-Lightning?\r\n# \r\n# PyTorch is based on the Torch library, adapted for Python. PyTorch is a deep learning library that allows you to have greater control of your neural network architecture, and have a lot more customisable hyper parameters / functions (such as the loss function etc.) compared to other deep learning frameworks such as TensorFlow / Keras.\r\n# \r\n# PyTorch-Lightning is a higher level of PyTorch, meaning that it is easier to use and run models on compared to the original PyTorch. There are methods that are already built into the classes for PyTorch-Lightning which you don't have to worry about as much, and takes away a lot of the additional considerations such as passing your dataset via CUDA, hence PyTorch-Lightning code will look simpler than PyTorch!\r\n# \r\n# As the first step we import all the necessary libraries needed to implement these lab tasks. \r\n# \r\n# Note: Do not modify seed values or use any other libraries.\r\n\r\n# In[5]:\r\n\r\n\r\n# If you run on Jupyter Lab uncomment bellow comment\r\n#! pip install --quiet \"matplotlib\" \"pytorch-lightning\" \"pandas\" \"torchmetrics\" \r\n#! pip install --ignore-installed \"PyYAML\"\r\n\r\n# If you run on google colab uncomment bellow comment\r\n#! pip install --quiet \"matplotlib\" \"pytorch-lightning\" \"pandas\" \"torchmetrics\"\r\nimport numpy as np\r\nimport random\r\nimport matplotlib.pyplot as plt\r\n\r\nimport pytorch_lightning as pl\r\nimport torch \r\nimport torch.nn as nn \r\nimport torchmetrics\r\nfrom torchmetrics import Accuracy\r\n\r\n# For reproducability\r\ntorch.manual_seed(1234)\r\nrandom.seed(1234)\r\nnp.random.seed(1234)\r\n\r\n# Define GPU number\r\nGPU_indx = 0\r\ndevice = torch.device(GPU_indx if torch.cuda.is_available() else 'cpu')\r\n\r\n\r\n#

Pytorch Datasets and Dataloaders

\r\n# \r\n# Pytorch has a huge number of functionalities that make training our neural networks very easy! One of those functionalities is the Pytorch dataset and dataloader (they are real life-savers!). In depth review on PyTorch Datasets and Dataloaders are covered in Lectures!\r\n\r\n# In order to load datasets, we will use torchvision module and to create a dataloader, we will use sub module of torch as follows.\r\n# \r\n# **from torch.utils.data import DataLoader**\r\n# \r\n# Under torchvision datasets you can find popular datasets that are frequently used for machine learning/deep learning tasks (eg., MNIST, SVHN, CIFAR10, CIFAR100 etc). You can create your own custom dataset using torchvision dataset in built functionalities and in this task we will show how to load custom datasets.\r\n\r\n# In[6]:\r\n\r\n\r\nfrom torch import optim\r\nfrom torch.utils.data import DataLoader\r\nfrom torch.utils.data.dataset import Dataset\r\n\r\n\r\n# ### 1.1 Creating a Pytorch dataset\r\n# \r\n# The dataset you are going to be creating will be points from a \"noisy\" sine wave. To create the custom dataset, you can use PyTorch dataset inbuilt functionalities.
\r\n# \r\n# \r\n# The Pytorch dataset class has three essential parts:
\r\n# 1. The \\__init__ function (as most Python classes do)
\r\n# 2. The \\__getitem__ function (this is called during every iteration)
\r\n# 3. The \\__len__ function (this must return the length of the dataset)\r\n# \r\n# **Remember! The \"self\" within classes will become attributes of that class that you can use within other methods that are defined for that class. If you defined an attribute without self.<\\name>, then that attribute cannot be used for other methods.**\r\n# \r\n# Make sure to follow all inline comments specified for each code fragment that you need to work on.\r\n\r\n# In[7]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Create a \"SineDataset\" class by importing the Pytorch Dataset class\r\n\r\nclass SineDataset(Dataset):\r\n \"\"\" Data noisy sinewave dataset\r\n num_datapoints - the number of datapoints you want\r\n \"\"\"\r\n def __init__(self, num_datapoints):\r\n # Lets generate the noisy sinewave points\r\n \r\n # Create \"num_datapoints\" worth of random x points using a uniform distribution (0-1) using torch.rand\r\n # Then scale and shift the points to be between -9 and 9\r\n self.x_data = (torch.rand(num_datapoints,1) - 0.5) * 18\r\n \r\n # Calculate the sin of all data points in the x vector and the scale amplitude\r\n # Scale the amplitude by diving by 2.5\r\n self.y_data = torch.sin(self.x_data) / 2.5\r\n \r\n # Add some gaussein noise to each datapoint using torch.randn_like\r\n # Note:torch.randn_like will generate a tensor of gaussein noise the same size \r\n # and type as the provided tensor\r\n # Divide the randomly generated values by 20 (so it is less noisy)\r\n self.y_data += torch.randn_like(self.y_data) / 20\r\n\r\n def __getitem__(self, index):\r\n # This function is called by the dataLOADER class whenever it wants a new mini-batch\r\n # The dataLOADER class will pass the dataSET and number of datapoint indexes (mini-batch of indexes)\r\n # It is up to the dataSET's __getitem__ function to output the corresponding input datapoints \r\n # AND the corresponding labels\r\n return self.x_data[index], self.y_data[index]\r\n # Note:Pytorch will actually pass the __getitem__ function one index at a time\r\n # If you use multiple dataLOADER \"workers\" multiple __getitem__ calls will be made in parallel\r\n # (Pytorch will spawn multiple threads)\r\n\r\n def __len__(self):\r\n # We also need to specify a \"length\" function, Python will use this fuction whenever\r\n # You use the Python len(function)\r\n # We need to define it so the dataLOADER knows how big the dataSET is!\r\n return self.x_data.shape[0]\r\n\r\n\r\n# ### 1.2 Create instances from defined custom dataset and visualize the training dataset\r\n# \r\n# Now that you've defined your dataset, lets create an instance of it for training and testing and then create dataloaders to make it easy to iterate.\r\n\r\n# In[8]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\nn_x_train = 30000 # the number of training datapoints\r\nn_x_test = 8000 # the number of testing datapoints\r\nBATCH_SIZE = 16 # the batch size for task 1\r\n\r\n# Create an instance of the SineDataset for both the training and test set \r\n# (Here we have only training and test set. Therefore consider validation set also equals to test set)\r\ndataset_train = SineDataset(n_x_train)\r\ndataset_test = SineDataset(n_x_test)\r\n# Now we need to pass the dataset to the Pytorch dataloader class along with some other arguments\r\n# batch_size - the size of our mini-batches\r\n# shuffle - whether or not we want to shuffle the dataset \r\n# For training shuffle is set to True and for Testing/Validation shuffle is set to False\r\ndata_loader_train = DataLoader(dataset_train, batch_size=BATCH_SIZE, shuffle=True)\r\ndata_loader_test = DataLoader(dataset_test, batch_size=BATCH_SIZE, shuffle=False)\r\n\r\n\r\n# In[9]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n## Why is it neccessary for us to shuffle the training, and not shuffle validation/test?\r\n# 普遍需求\r\n\r\n\r\n# Now visualise the dataset you've created!!\r\n# \r\n# Note: see here how we can just directly access the data from the dataset class. Make sure your generated sinewave matches the described sinewave within the dataset class!. \r\n\r\n# In[15]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Visualize dataset using matplotlib scatter plot\r\ntrain = torch.tensor([i for i in dataset_train])\r\ntest = torch.tensor([i for i in dataset_test])\r\nfig1, (ax11,ax12) = plt.subplots(1,2)\r\nax11.scatter(train[...,0], train[...,1], s=1)\r\nax11.set_title(\"Train_data\")\r\nax11.set_xlabel(\"x\")\r\nax11.set_ylabel(\"y\")\r\n\r\nax12.scatter(test[...,0], test[...,1], s=1)\r\nax12.set_title(\"Test_data\")\r\nax12.set_xlabel(\"x\")\r\nax12.set_ylabel(\"y\")\r\nplt.gcf().set_size_inches(20,10)\r\nplt.show()\r\n\r\n\r\n# ## Now, let's design a Neual Network and Train it!\r\n\r\n#

Neural Network Architecture

\r\n# \r\n# Up until now we have only created a single linear layer with an input layer and an output layer. In this Lab you will start to create multi-layered networks with many \"hidden\" layers separated by \"activation functions\" that give our networks \"non-linearities\". If we didn't have these activation functions and simple stacked layers together, our network would be no better than a single linear layer! Why? Because multiple sequential \"linear transformations\" can be modeled with just a single linear transformation. \r\n# \r\n# Neural networks are associated with a Directed Acyclic Graphs (DAG) describing how the functions are composed together. For example, we might have three functions $f^{(1)}, f^{(2)}$, and $f^{(3)}$, connected in a chain, to form in a chain, to form $f(x) = f^{(3)}(f^{(2)}(f^{(1)}(x))).$ In this case, $f^{(1)}$ is called the first layer of the network, $f^{(2)}$ is called the second layer, and so on. The final layer of a feedforward network is called the output layer.\r\n# \r\n# Except the output layer, the behavior of the other layers is not directly specified by the training data. The learning algorithm must decide how to use those layers to produce the desired output, but the training data do not say what each individual layer should do. Instead, the learning algorithm must decide how to use these layers to best implement an approximation of $f^*$. Because the training data does not show the desired output for each of these layers, and they\r\n# are called hidden layers. These hidden layers, receive input from many other units and computes its own activation value. This requires us to choose the activation functions that will be used to compute the hidden layer values.\r\n# \r\n# So what are these nonlinear activation functions that turn our simple linear models into a power \"nonlinear function approximator\"? Some common examples are:
\r\n# 1. relu\r\n# 2. sigmoid\r\n# 3. tanh\r\n\r\n#

Pytorch Lightning Module

\r\n# \r\n# Now we can define a Pytorch Lightning model to be trained!
\r\n# To do so, here you need to use the Pytorch LightningModule class as the base for defining your network. Just like the dataset class, this class has a number of important functions.\r\n# A LightningModule is a PyTorch nn.Module and it has a few more helpful features.\r\n\r\n# In[16]:\r\n\r\n\r\nimport os\r\nimport pandas as pd\r\n\r\nfrom IPython.core.display import display\r\nfrom pytorch_lightning import LightningModule, Trainer\r\nfrom pytorch_lightning.callbacks.progress import TQDMProgressBar\r\nfrom pytorch_lightning.loggers import CSVLogger\r\nfrom torch import nn\r\nfrom torch.nn import functional as F\r\nfrom torch.utils.data import DataLoader, random_split\r\nfrom torchmetrics import Accuracy\r\nfrom torchvision import transforms\r\nfrom IPython.display import clear_output\r\nfrom pytorch_lightning.callbacks import Callback, ModelCheckpoint\r\n\r\n\r\n# ### 1.3 Design the Shallow Linear MLP model using PyTorch Lightning Module\r\n# \r\n# Design a two layer Shallow MLP model and train it with both SGD and Adam optimizers. \r\n\r\n# In[30]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\nclass ShallowLinear(LightningModule):\r\n def __init__(self, hidden_size=[1, 64, 1], learning_rate=1e-2, optimizer=\"SGD\"):\r\n\r\n super().__init__()\r\n # Set our init args as class attributes, you can look at the PDF for the info\r\n self.learning_rate = learning_rate # Learning rate\r\n self.loss_fn = nn.MSELoss() # Use MSE loss as cost function\r\n #self.optimizer = optim.SGD(self.parameters(), lr=learning_rate) # Optimizer\r\n self.optimizer = optimizer\r\n \r\n D_in, H, D_out = hidden_size[0], hidden_size[1], hidden_size[2]\r\n \r\n self.linear1 = nn.Linear(D_in, H)\r\n self.linear2 = nn.Linear(H, D_out)\r\n self.test_accuracy = Accuracy()\r\n \r\n def forward(self, x):\r\n # This function is an important one and we must create it or pytorch will give us an error!\r\n # This function defines the \"forward pass\" of our neural network\r\n x = x.view(x.size(0),1)\r\n #Lets define the sqeuence of events for our forward pass!\r\n x = self.linear1(x) # hidden layer\r\n x = torch.tanh(x) # activation function --> use tanh\r\n\r\n #No activation function on the output!!\r\n x = self.linear2(x) # output layer\r\n \r\n #Note we re-use the variable x as we don't care about overwriting it \r\n #though in later labs we will want to use earlier hidden layers\r\n #later in our network!\r\n return x\r\n\r\n def training_step(self, batch, batch_idx):\r\n # Write training step\r\n x, y = batch\r\n logits = self(x)\r\n loss = self.loss_fn(logits,y)\r\n self.log(\"train_loss\", loss, prog_bar=True, on_step=False, on_epoch=True)\r\n return loss\r\n \r\n def validation_step(self, batch, batch_idx):\r\n # Write validation step\r\n x, y = batch\r\n logits = self(x)\r\n #print(f\"val: {x.shape, y.shape, logits.shape}\")\r\n logits = logits.squeeze(1)\r\n loss = self.loss_fn(logits,y)\r\n\r\n def test_step(self, batch, batch_idx):\r\n # Write testing step\r\n x, y = batch\r\n logits = self(x)\r\n logits = logits.squeeze(1)\r\n loss = self.loss_fn(logits, y)\r\n self.log(\"test_loss\", loss, prog_bar=True, on_step=False, on_epoch=True)\r\n\r\n def predict_step(self, batch, batch_idx):\r\n # Write predict step\r\n x, y = batch\r\n return [x, self(x)]\r\n \r\n def configure_optimizers(self):\r\n # Return Adam or SGD optimizer\r\n if self.optimizer == \"SGD\":\r\n optimizer = torch.optim.SGD(self.parameters(), lr=self.learning_rate)\r\n elif self.optimizer == \"Adam\":\r\n optimizer = torch.optim.Adam(self.parameters(), lr=self.learning_rate)\r\n return optimizer\r\n \r\n def train_dataloader(self):\r\n return data_loader_train\r\n \r\n def val_dataloader(self):\r\n return data_loader_test\r\n\r\n def test_dataloader(self):\r\n return data_loader_test\r\n\r\n\r\n# ### 1.4 Define training and testing methods for models\r\n# \r\n# By using the Trainer Constructor you can train and test the model.\r\n# Also Trainer will automatically enables: \r\n# 1. Tensorboard logging \r\n# 2. Model checkpointing \r\n# 3. Training and validation loop \r\n# 4. early-stopping\r\n# \r\n# In this task, we will test the model performance for both optimizers:\r\n# - SGD\r\n# - ADAM\r\n# \r\n\r\n# In[18]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Initialize Model with SGD optimizer\r\nmodel_sgd = model_sgd = ShallowLinear()\r\n\r\n# Train model for 20 epochs\r\ntrainer_task1_SGD = Trainer(\r\n accelerator=\"auto\",\r\n devices=1 if torch.cuda.is_available() else None, # limiting got iPython runs\r\n max_epochs=20,\r\n callbacks=[TQDMProgressBar(refresh_rate=20)],\r\n logger=CSVLogger(save_dir=\"logs_task1_SGD/\"),\r\n)\r\ntrainer_task1_SGD.fit(model_sgd)\r\n\r\n# Evaluate Model\r\ntrainer_task1_SGD.test()\r\n\r\n\r\n# If your implementation is correct, you should obtain a printed output similar to this:\r\n# \r\n# [{'test_loss': 0.009513414464890957}]\r\n\r\n# In[31]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Initialize Model with Adam optimizer\r\nmodel_adam = ShallowLinear(optimizer=\"Adam\")\r\n\r\n# Train model for 20 epochs\r\ntrainer_task1_ADAM = Trainer(\r\n accelerator=\"auto\",\r\n devices=1 if torch.cuda.is_available() else None, # limiting got iPython runs\r\n max_epochs=20,\r\n callbacks=[TQDMProgressBar(refresh_rate=20)],\r\n logger=CSVLogger(save_dir=\"logs_task1_Adam/\"),\r\n)\r\ntrainer_task1_ADAM.fit(model_adam)\r\n\r\n# Evaluate Model\r\ntrainer_task1_ADAM.test()\r\n\r\n\r\n# If your implementation is correct, you should obtain a printed output similar to this:\r\n# \r\n# [{'test_loss': 0.005056165624409914}]\r\n\r\n# ### 1.5 Generate scatter plots for above two trained models to compare noisy datapoints and denoised predictions\r\n\r\n# In[26]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Scatter plot for model trained using SGD (call predict function)\r\npredictions_sgd = trainer_task1_SGD.predict(dataloaders=data_loader_test)\r\nfig2, ax2 = plt.subplots(1,1)\r\nax2.scatter(test[...,0], test[...,1], s=1, c='g', label=\"Test_data\")\r\nfor dat_a in predictions_sgd:\r\n ax2.scatter(dat_a[0], dat_a[1], s=1, c='r')\r\nax2.set_title(\"Predicted using SGD optimizer\")\r\nax2.set_xlabel(\"x\")\r\nax2.set_ylabel(\"y\")\r\nplt.legend()\r\nplt.show()\r\n\r\n\r\n# In[27]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Scatter plot for model trained using Adam (call predict function)\r\npredictions_adam = trainer_task1_ADAM.predict(dataloaders=data_loader_test)\r\nfig3, ax3 = plt.subplots(1,1)\r\nax3.scatter(test[...,0], test[...,1], s=1, c='g', label=\"Test_data\")\r\nfor dat_a in predictions_adam:\r\n ax3.scatter(dat_a[0], dat_a[1], c=\"r\", s=1)\r\nax3.set_title(\"Predicted using Adam optimizer\")\r\nax3.set_xlabel(\"x\")\r\nax3.set_ylabel(\"y\")\r\nplt.legend()\r\nplt.show()\r\n\r\n\r\n# ### 1.6 Visualize experimental results\r\n# \r\n# Pytorch-lightning module has its own built in methods to log values. These log files can be then used to visualize experimental results. You can use python plotting libraries such as matplotlib.\r\n# \r\n# Using those logs, plot train losses for models trained on SGD and Adam.\r\n# \r\n# Note: Make sure to drop NaN entries from dataframes before you plot using matplotlib.\r\n# \r\n# You can read the logs by using the pandas library (pd.read_csv)\r\n\r\n# In[28]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# read logs for model trained with SGD\r\ntraining_loss_sgd = pd.read_csv(trainer_task1_SGD.logger.log_dir + \"/metrics.csv\")\r\ntraining_loss_sgd = training_loss_sgd[\"train_loss\"].dropna()\r\n\r\n# read logs for model trained with Adam\r\ntraining_loss_adam = pd.read_csv(trainer_task1_ADAM.logger.log_dir + \"/metrics.csv\")\r\ntraining_loss_adam = training_loss_adam[\"train_loss\"].dropna()\r\n\r\n\r\n# In[29]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Visualize train losses for model trained with SGD and Adam\r\nfig4, (ax41, ax42) = plt.subplots(1,2)\r\n\r\nax41.plot(training_loss_sgd)\r\nax41.set_title(\"SGD Train_Loss\", fontsize=18)\r\nax41.set_xticks(np.arange(len(training_loss_sgd)))\r\nax41.set_xlabel(\"Epoch\")\r\nax41.set_ylabel(\"Loss\")\r\n\r\nax42.plot(training_loss_adam)\r\nax42.set_title(\"Adam Train_Loss\", fontsize=18)\r\nax42.set_xticks(np.arange(len(training_loss_sgd)))\r\nax42.set_xlabel(\"Epoch\")\r\nax42.set_ylabel(\"Loss\")\r\n\r\nplt.gcf().set_size_inches(20,10)\r\nplt.show()\r\n\r\n\r\n# ### 1.7 Analysing above results, what optimizer you will choose? Explain why?\r\n\r\n# In[32]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Answer here\r\n# 我会选择SGD优化器。它的损失更低,收敛性较好\r\n\r\n\r\n# ### 1.8 Discuss why this simple shallow network is able to denoise noisy data and approximate sine function ?\r\n\r\n# In[33]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Answer here\r\n#因为使用了tanh激活函数,增加神经网络模型的非线性\r\n\r\n\r\n# ## Section 2 & 3 : Compare Shallow MLP and Deep MLP\r\n# \r\n# \r\n#
\r\n# \r\n# ## What you should do these sections 2 and 3!!\r\n# \r\n# In sections 2 and 3 you will be training a Shallow MLPs and Deep MLPs for classifying images on the data file \"section2_data.npz\" which is the Fashion-MNIST dataset that contains images and labels for training, validation and test purposes (The images are 28x28 grayscale images).\r\n# \r\n# You have to use Pytorch inbuilt datasets, Pytorch Lightning module class to construct a MLP in order to perform training and testing on the given datasets using stochastic gradient descent (SGD).\r\n# \r\n# #### In you will work on the following points:\r\n# 1. Create training, validation and testing dataloaders.\r\n# 2. Visualize training datasets.\r\n# 3. Design shallow neural network model.\r\n# 4. Perform training the model and evaluation for different settings. Report test accuracies.\r\n# 5. Visualize experimental results for training losses.\r\n# 6. Visualize experimental results for validation accuracies.\r\n# 7. Visualize predictions.\r\n# 8. Optimize Shallow network's performance.\r\n# \r\n# \r\n# #### In section 3 you will work on the following points:\r\n# 1. Design deep neural network model.\r\n# 2. Perform training the model and evaluation for different settings. Report test accuracies.\r\n# 3. Visualize experimental results for training loss vs Validation accuracy.\r\n# 4. Visualize predictions.\r\n# 5. Discussion on experimental results.\r\n# \r\n# \r\n# \r\n# In the above figure A is a shallow neural network and B is a deep neural network.\r\n# \r\n# Note: In all the parts below, you should only use the training images and their labels to train your model. You may use the **validation set** to pick a trained model. For example, during training, you can test the accuracy of your model using the validation set every epoch and pick the model that achieves the highest validation accuracy. You should then report your results on the test set once you choose your model.\r\n# \r\n\r\n# ### 2.1 Create custom dataloader\r\n# \r\n# The following class reads the data for section 2 & 3 tasks and creates a torch dataset object for it. With this, you can easily \r\n# use a dataloader to train your model. \r\n# \r\n# Note: Make sure that the file \"section2_data.npz\" is located properly (in this example, it should be in the same folder as this notebook).\r\n\r\n# In[34]:\r\n\r\n\r\nimport torchvision\r\n\r\n# For reproducability\r\ntorch.manual_seed(1234)\r\nrandom.seed(1234)\r\nnp.random.seed(1234)\r\n\r\nPATH_DATASETS = os.environ.get(\"PATH_DATASETS\", \".\")\r\nBATCH_SIZE = 100 \r\n\r\n\r\n# In[35]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\nclass Section3Data(Dataset):\r\n def __init__(self, trn_val_tst = 0):\r\n # Load numpy data\r\n data = np.load(\"section2_data.npz\")\r\n if trn_val_tst == 0:\r\n # Create dataset for trainloader --> images arr_0, labels arr_1\r\n self.images = data[\"arr_0\"].T\r\n self.labels = data[\"arr_1\"]\r\n elif trn_val_tst == 1:\r\n # Create dataset for valloader --> images arr_2, labels arr_3\r\n self.images = data[\"arr_2\"].T\r\n self.labels = data[\"arr_3\"]\r\n else:\r\n # Create dataset for testloader --> images arr_4, labels arr_5\r\n self.images = data[\"arr_4\"].T\r\n self.labels = data[\"arr_5\"]\r\n \r\n # Normalize images [0,1] \r\n self.images = (self.images - self.images.min())/(self.images.max() - self.images.min())\r\n\r\n # Define len function\r\n def __len__(self):\r\n return len(self.labels)\r\n\r\n # Define getitem function\r\n def __getitem__(self, idx):\r\n if torch.is_tensor(idx):\r\n idx = idx.tolist()\r\n \r\n sample = self.images[idx,:]\r\n labels = self.labels[idx]\r\n return sample, labels\r\n\r\n\r\n# Now using dataset class create a dataloader for the section 3 data.\r\n\r\n# In[36]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Call training dataset and create the trainloader\r\ntrainset = Section3Data(trn_val_tst=0)\r\ntrainloader = DataLoader(trainset,batch_size=BATCH_SIZE,shuffle=True)\r\n\r\n# Call validation dataset and create the trainloader\r\nvalset = Section3Data(trn_val_tst=1)\r\nvalloader = DataLoader(valset,batch_size=BATCH_SIZE,shuffle=False)\r\n\r\n# Call testing dataset and create the trainloader\r\ntestset = Section3Data(trn_val_tst=2) \r\ntestloader = DataLoader(testset,batch_size=BATCH_SIZE,shuffle=False)\r\n\r\n\r\n# ### 2.2 Visualize dataset\r\n# \r\n# Lets visualise that mini-batches that the training dataloader gives us.\r\n\r\n# In[38]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n\r\n# We can create an iterater using the dataloaders and take a random sample \r\ntrain_data_iter = iter(trainloader)\r\ndata, labels = train_data_iter.next()\r\ndata = data.reshape(100, 1, 28, -1)\r\nprint(f\"data:\\t{data.shape}\")\r\nprint(f\"label:\\t{labels.shape}\")\r\n\r\n# visualize dataset using torchvision grid\r\nout = torchvision.utils.make_grid(data, nrow=16)\r\n\r\nfig5, ax5 = plt.subplots(1,1)\r\nax5.imshow(out.numpy().transpose((1, 2, 0)))\r\nax5.set_title(\"Fashion_MNIST Dataset\", fontsize=20)\r\nplt.gcf().set_size_inches(20,10)\r\nplt.show()\r\n\r\n\r\n# ### 2.3 Design Shallow MLP\r\n# \r\n# Design a Shallow MLP with one hidden linear layer.\r\n\r\n# In[39]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\nclass Shallow_MLP(LightningModule):\r\n def __init__(self, n, learning_rate=1e-1):\r\n super().__init__()\r\n \r\n self.learning_rate = learning_rate\r\n self.loss_fun = nn.CrossEntropyLoss() # Use CE loss\r\n \r\n self.linear1 = nn.Linear(784, n)\r\n self.linear2 = nn.Linear(n, 10)\r\n \r\n self.train_accuracy = Accuracy()\r\n self.val_accuracy = Accuracy()\r\n self.test_accuracy = Accuracy()\r\n \r\n def forward(self, x):\r\n #Pass input through conv layers\r\n bs = x.shape[0]\r\n x = x.reshape(bs, -1).float()\r\n out1 = torch.tanh(self.linear1(x))\r\n out2 = self.linear2(out1)\r\n \r\n return out2\r\n \r\n def training_step(self, batch, batch_idx):\r\n # Write training step\r\n x, y = batch\r\n logits = self(x)\r\n loss = self.loss_fun(logits, y)\r\n\r\n preds = logits.argmax(1)\r\n self.train_accuracy.update(preds, y)\r\n\r\n self.log(\"train_loss\", loss, prog_bar=True, on_step=False, on_epoch=True)\r\n self.log(\"train_acc\", self.train_accuracy, prog_bar=True, on_step=False, on_epoch=True)\r\n return loss\r\n def validation_step(self, batch, batch_idx):\r\n # Write validation step\r\n x, y = batch\r\n logits = self(x)\r\n loss = self.loss_fun(logits, y)\r\n\r\n preds = logits.argmax(1)\r\n self.val_accuracy.update(preds, y)\r\n\r\n self.log(\"val_loss\", loss, prog_bar=True, on_step=False, on_epoch=True)\r\n self.log(\"val_acc\", self.val_accuracy, prog_bar=True, on_step=False, on_epoch=True)\r\n\r\n def test_step(self, batch, batch_idx):\r\n # Write testing step\r\n x, y = batch\r\n logits = self(x)\r\n loss = self.loss_fun(logits, y)\r\n \r\n preds = logits.argmax(1)\r\n self.test_accuracy.update(preds, y)\r\n \r\n self.log(\"test_loss\", loss, prog_bar=True, on_step=False, on_epoch=True)\r\n self.log(\"test_acc\", self.test_accuracy, prog_bar=True, on_step=False, on_epoch=True)\r\n \r\n def predict_step(self, batch, batch_idx):\r\n # Write predict step\r\n x, y = batch\r\n logits = self(x)\r\n preds = logits.argmax(1)\r\n return [preds, y]\r\n \r\n def configure_optimizers(self):\r\n optimizer = torch.optim.SGD(self.parameters(), lr=self.learning_rate)\r\n return optimizer\r\n\r\n ####################\r\n # DATA RELATED HOOKS\r\n ####################\r\n\r\n def train_dataloader(self):\r\n return trainloader\r\n \r\n def val_dataloader(self):\r\n return valloader\r\n\r\n def test_dataloader(self):\r\n return testloader\r\n\r\n\r\n# ### 2.4 Train and evaluate model's performance for following scenarios\r\n# \r\n# a. fc1 : Linear(784 $\\times$ 32) $\\rightarrow$ ReLU $\\rightarrow$ fc2 : Linear(32 x$\\times$ 10)\r\n# \r\n# b. fc1 : Linear(784 $\\times$ 128) $\\rightarrow$ ReLU $\\rightarrow$ fc2 : Linear(128 $\\times$ 10)\r\n# \r\n# c. fc1 : Linear(784 $\\times$ 512) $\\rightarrow$ ReLU $\\rightarrow$ fc2 : Linear(512 $\\times$ 10)\r\n# \r\n# In all the parts above, you should only use the training images and their labels to train your model. You may use the validation set to pick a trained model.\r\n# \r\n# For example, during training, you can test the accuracy of your model using the validation set every epoch and pick the model that achieves the highest validation accuracy. You should then report your results on the test set once you choose your model. \r\n# \r\n# Note: Make sure to have different log file directories and checkpoint folders (eg: logs_task_2a, logs_task_2b and logs_task_2c)\r\n\r\n# In[40]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Initialize Shallow MLP model with n = 32\r\nmodel = Shallow_MLP(n=32)\r\n\r\n# Define checkpoint callback function to save best model\r\ncheckpoint_callback_2a = ModelCheckpoint(monitor=\"val_acc\",dirpath=\"logs_task_2a/\",save_top_k=1,mode=\"max\",every_n_epochs=1)\r\n\r\n# Train and test the model\r\ntrainer_2a = Trainer(\r\n accelerator=\"auto\",\r\n devices=1 if torch.cuda.is_available() else None, \r\n max_epochs=100,\r\n callbacks=[TQDMProgressBar(refresh_rate=20), checkpoint_callback_2a],\r\n logger=CSVLogger(save_dir=\"logs_task_2a/\"),\r\n)\r\ntrainer_2a.fit(model)\r\ntrainer_2a.test()\r\n\r\n\r\n# If your implementation is correct, you should obtain a printed output similar to this:\r\n# \r\n# [{'test_loss': 0.4268353581428528, 'test_acc': 0.8521000146865845}]\r\n\r\n# In[41]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Initialize Shallow MLP model with n = 128\r\nmodel = Shallow_MLP(n=128)\r\n\r\n# Define checkpoint callback function to save best model\r\ncheckpoint_callback_2b = ModelCheckpoint(monitor=\"val_acc\",dirpath=\"logs_task_2b/\",save_top_k=1,mode=\"max\",every_n_epochs=1)\r\n\r\n# Train and test the model\r\ntrainer_2b = Trainer(\r\n accelerator=\"auto\",\r\n devices=1 if torch.cuda.is_available() else None, \r\n max_epochs=100,\r\n callbacks=[TQDMProgressBar(refresh_rate=20),checkpoint_callback_2b],\r\n logger=CSVLogger(save_dir=\"logs_task_2b/\"),\r\n)\r\ntrainer_2b.fit(model)\r\ntrainer_2b.test()\r\n\r\n\r\n# If your implementation is correct, you should obtain a printed output similar to this:\r\n# \r\n# [{'test_loss': 0.4281507730484009, 'test_acc': 0.8611000180244446}]\r\n\r\n# In[42]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Initialize Shallow MLP model with n = 512\r\nmodel = Shallow_MLP(n=512)\r\n\r\n# Define checkpoint callback function to save best model\r\ncheckpoint_callback_2c = ModelCheckpoint(monitor=\"val_acc\",dirpath=\"logs_task_2c/\",save_top_k=1,mode=\"max\",every_n_epochs=1)\r\n\r\n# Train and test the model\r\ntrainer_2c = Trainer(\r\n accelerator=\"auto\",\r\n devices=1 if torch.cuda.is_available() else None, \r\n max_epochs=100,\r\n callbacks=[TQDMProgressBar(refresh_rate=20), checkpoint_callback_2c],\r\n logger=CSVLogger(save_dir=\"logs_task_2c/\"),\r\n)\r\ntrainer_2c.fit(model)\r\ntrainer_2c.test()\r\n\r\n\r\n# If your implementation is correct, you should obtain a printed output similar to this:\r\n# \r\n# [{'test_loss': 0.4100257456302643, 'test_acc': 0.8678666949272156}]\r\n\r\n# ### 2.5 Plot Training losses for the different shallow networks\r\n\r\n# In[43]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# read logs for 2a\r\ntraining_data_2a = pd.read_csv(trainer_2a.logger.log_dir + \"/metrics.csv\")\r\ntraining_loss_2a = training_data_2a[\"train_loss\"].dropna()\r\n# read logs for 2b\r\ntraining_data_2b = pd.read_csv(trainer_2b.logger.log_dir + \"/metrics.csv\")\r\ntraining_loss_2b = training_data_2b[\"train_loss\"].dropna()\r\n# read logs for 2c\r\ntraining_data_2c = pd.read_csv(trainer_2c.logger.log_dir + \"/metrics.csv\")\r\ntraining_loss_2c = training_data_2c[\"train_loss\"].dropna()\r\n\r\n\r\n# In[45]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Plot using matplotlib\r\nfig6, ax6 = plt.subplots(1,1)\r\nax6.plot(training_loss_2a, label=\"n = 32\")\r\nax6.plot(training_loss_2b, label=\"n = 128\")\r\nax6.plot(training_loss_2c, label=\"n = 512\")\r\nax6.set_title(\"The train_loss of Shallow MLP \")\r\nax6.set_xlabel(\"Epochs\")\r\nax6.set_ylabel(\"Loss\")\r\nplt.legend()\r\nplt.show()\r\n# Discuss what you see\r\n\r\n\r\n# ### 2.6 Plot Validation accuracies for the different shallow networks\r\n\r\n# In[46]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Plot using matplotlib\r\nval_acc_2a = training_data_2a[\"val_acc\"].dropna()\r\nval_acc_2b = training_data_2b[\"val_acc\"].dropna()\r\nval_acc_2c = training_data_2c[\"val_acc\"].dropna()\r\nfig7, ax7 = plt.subplots(1,1)\r\nax7.plot(val_acc_2a, label=\"n = 32\")\r\nax7.plot(val_acc_2b, label=\"n = 128\")\r\nax7.plot(val_acc_2c, label=\"n = 512\")\r\nax7.set_title(\"The Val_acc of Shallow MLP\")\r\nax7.set_xlabel(\"Epochs\")\r\nax7.set_ylabel(\"Accuracy\")\r\nplt.legend()\r\nplt.show()\r\n\r\n\r\n# ### 2.7 Visualize 5 predictions of test set along with groundtruths and input images for 3rd Shallow MLP\r\n\r\n# In[49]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Generate predictions using predict function\r\npredictions_2c = trainer_2c.predict(dataloaders=testloader)\r\n\r\n# visualize predictions along with ground truths and input images using matplotlib\r\ntest_loader_iter = iter(testloader)\r\ntest_data, test_labels = test_loader_iter.next()\r\ndef vis_preds(testloader, predictions):\r\n test_data, test_labels = next(iter(testloader))\r\n im_idx = torch.randint(0, test_labels.shape[0], (5,))\r\n im_label = [predictions[0][0][i] for i in im_idx]\r\n im_pred = [predictions[0][1][i] for i in im_idx]\r\n fig, axs = plt.subplots(1, 5, figsize=(18,6), sharey=True)\r\n for i, im_num in enumerate(im_idx):\r\n axs[i].imshow(test_data[im_num].resize(28,28))\r\n axs[i].set_title(f\"Item {im_num}: label: {im_label[i]}, pred: {im_pred[i]}\")\r\n fig.suptitle(\"Test_pred Visual\", fontsize=15)\r\n plt.show()\r\n \r\nvis_preds(testloader, predictions_2c)\r\n\r\n\r\n# ### 2.8 Optimize hyper-parameters to improve accuracy of shallow network\r\n# \r\n# What do you recommend to improve shallow network's accuracy further ?\r\n# \r\n# - Make sure to test at least 2-3 hyper parameters\r\n# - For each hyper parameter, have 3 variations\r\n# - Plot out the results after you train + tested it. It is recommended to use subplot (or overlay onto 1 plot the accuracies for each model). **Important! Think about which accuracy is most relevant** \r\n\r\n# In[50]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# What do you recommend?\r\n# 对于学习速率,默认的 1e-1 在训练损失和验证准确性方面表现最佳,这更为重要。这是因为验证集是模型尚未看到的新数据,因此它是对模型的普遍性的真实测试。我们看到,降低学习速率并不能取得多大成就,如果有的话,也会损害模型的准确性,也会减慢其收敛速度。。\r\n\r\n\r\n# Train and test the Shallow MLP model using above suggested. When testing different hyper-parameters, you can use the original shallow MLP class from earlier, and just train using the different hyper-parameters. Save your MLP with the optimized parameters. \r\n\r\n# In[51]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Create New Class\r\n# class Shallow_MLP_Optimized(LightningModule):\r\nset_background(red_bgd)\r\n\r\nclass Shallow_MLP_Optimised(LightningModule):\r\n def __init__(self, learning_rate=1e-1):\r\n super().__init__()\r\n \r\n self.learning_rate = learning_rate\r\n self.loss_fun = nn.CrossEntropyLoss() # Use CE loss\r\n \r\n self.linear1 = nn.Linear(784, 128)\r\n self.linear2 = nn.Linear(128, 10)\r\n \r\n self.train_accuracy = Accuracy()\r\n self.val_accuracy = Accuracy()\r\n self.test_accuracy = Accuracy()\r\n \r\n def forward(self, x):\r\n #Pass input through conv layers\r\n bs = x.shape[0]\r\n x = x.reshape(bs, -1).float()\r\n out1 = torch.tanh(self.linear1(x))\r\n out2 = self.linear2(out1)\r\n \r\n return out2\r\n \r\n def training_step(self, batch, batch_idx):\r\n # Write training step\r\n x, y = batch\r\n logits = self(x)\r\n loss = self.loss_fun(logits, y)\r\n\r\n preds = logits.argmax(1)\r\n self.train_accuracy.update(preds, y)\r\n\r\n self.log(\"train_loss\", loss, prog_bar=True, on_step=False, on_epoch=True)\r\n self.log(\"train_acc\", self.train_accuracy, prog_bar=True, on_step=False, on_epoch=True)\r\n\r\n return loss\r\n \r\n def validation_step(self, batch, batch_idx):\r\n # Write validation step\r\n x, y = batch\r\n logits = self(x)\r\n loss = self.loss_fun(logits, y)\r\n\r\n preds = logits.argmax(1)\r\n self.val_accuracy.update(preds, y)\r\n\r\n self.log(\"val_loss\", loss, prog_bar=True, on_step=False, on_epoch=True)\r\n self.log(\"val_acc\", self.val_accuracy, prog_bar=True, on_step=False, on_epoch=True)\r\n\r\n def test_step(self, batch, batch_idx):\r\n # Write testing step\r\n x, y = batch\r\n logits = self(x)\r\n loss = self.loss_fun(logits, y)\r\n \r\n preds = logits.argmax(1)\r\n self.test_accuracy.update(preds, y)\r\n \r\n self.log(\"test_loss\", loss, prog_bar=True, on_step=False, on_epoch=True)\r\n self.log(\"test_acc\", self.test_accuracy, prog_bar=True, on_step=False, on_epoch=True)\r\n \r\n def predict_step(self, batch, batch_idx):\r\n # Write predict step\r\n x, y = batch\r\n logits = self(x)\r\n preds = logits.argmax(1)\r\n return [preds, y]\r\n\r\n def configure_optimizers(self):\r\n optimizer = torch.optim.SGD(self.parameters(), lr=self.learning_rate)\r\n return optimizer\r\n\r\n ####################\r\n # DATA RELATED HOOKS\r\n ####################\r\n\r\n def train_dataloader(self):\r\n return trainloader\r\n \r\n def val_dataloader(self):\r\n return valloader\r\n\r\n def test_dataloader(self):\r\n return testloader\r\n# Train the model\r\nmodel = Shallow_MLP_Optimised()\r\n\r\ncheckpoint_callback_opt_final = ModelCheckpoint(\r\n monitor=\"val_acc\",\r\n dirpath=\"logs_task_2_opt_final/\",\r\n save_top_k=1,\r\n mode=\"max\",\r\n every_n_epochs=1\r\n)\r\n\r\ntrainer_opt_final = Trainer(\r\n accelerator=\"auto\",\r\n devices=1 if torch.cuda.is_available() else None, \r\n max_epochs=150,\r\n callbacks=[TQDMProgressBar(refresh_rate=20), checkpoint_callback_opt_final],\r\n logger=CSVLogger(save_dir=\"logs_task_2_opt_final/\"),\r\n)\r\ntrainer_opt_final.fit(model)\r\n# Test the model\r\ntrainer_opt_final.test()\r\n# Visualize accuracy graphs and compare it with 2.3 Accuracies\r\ntraining_data_opt_final = pd.read_csv(trainer_opt_final.logger.log_dir + \"/metrics.csv\")\r\ntraining_loss_opt_final = training_data_opt_final[\"train_loss\"].dropna()\r\nval_acc_opt_final = training_data_opt_final[\"val_acc\"].dropna()\r\n\r\nfig10, (ax101, ax102) = plt.subplots(1, 2)\r\nax101.plot(training_loss_2b, label=\"origin\")\r\nax101.plot(training_loss_opt_final, label=\"optimize\")\r\nax101.set_title(\"Train_Loss\", fontsize=20)\r\nax101.set_xlabel(\"Epochs\")\r\nax101.set_ylabel(\"Loss\")\r\nax101.legend(prop={'size': 15})\r\n\r\nax102.plot(val_acc_2b, label=\"original\")\r\nax102.plot(val_acc_opt_final, label=\"optimize\")\r\nax102.set_title(\"Val_acc\", fontsize=20)\r\nax102.set_xlabel(\"Epochs\")\r\nax102.set_ylabel(\"Accuracy\")\r\nax102.legend(prop={'size': 15})\r\n\r\nplt.gcf().set_size_inches(20,10)\r\nplt.show()\r\n\r\n\r\n# # Section 3: Deep MLP\r\n\r\n# ### 3.1 Design Deep MLP\r\n# \r\n# Design a Deep MLP with four linear layers.\r\n\r\n# In[52]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n\r\nclass Deep_MLP(LightningModule):\r\n def __init__(self, n1, n2, n3, learning_rate=1e-1):\r\n super().__init__()\r\n \r\n self.learning_rate = learning_rate\r\n self.loss_fun = nn.CrossEntropyLoss() # Use CE loss\r\n \r\n self.linear1 = nn.Linear(784, n1)\r\n self.linear2 = nn.Linear(n1, n2)\r\n self.linear3 = nn.Linear(n2, n3)\r\n self.linear4 = nn.Linear(n3, 10)\r\n \r\n self.train_accuracy = Accuracy()\r\n self.val_accuracy = Accuracy()\r\n self.test_accuracy = Accuracy()\r\n \r\n def forward(self, x):\r\n #Pass input through conv layers\r\n \r\n bs = x.shape[0]\r\n x = x.reshape(bs, -1).float()\r\n out1 = torch.tanh(self.linear1(x))\r\n out2 = torch.tanh(self.linear2(out1))\r\n out3 = torch.tanh(self.linear3(out2))\r\n out4 = self.linear4(out3)\r\n \r\n return out4\r\n \r\n def training_step(self, batch, batch_idx):\r\n # Write training step\r\n x, y = batch\r\n logits = self(x)\r\n loss = self.loss_fun(logits, y)\r\n preds = logits.argmax(1)\r\n self.train_accuracy.update(preds, y)\r\n self.log(\"train_loss\", loss, prog_bar=True, on_step=False, on_epoch=True)\r\n self.log(\"train_acc\", self.train_accuracy, prog_bar=True, on_step=False, on_epoch=True) \r\n return loss\r\n def validation_step(self, batch, batch_idx):\r\n # Write validation step\r\n x, y = batch\r\n logits = self(x)\r\n loss = self.loss_fun(logits, y)\r\n preds = logits.argmax(1)\r\n self.val_accuracy.update(preds, y)\r\n self.log(\"val_loss\", loss, prog_bar=True, on_step=False, on_epoch=True)\r\n self.log(\"val_acc\", self.val_accuracy, prog_bar=True, on_step=False, on_epoch=True)\r\n def test_step(self, batch, batch_idx):\r\n # Write testing step\r\n x, y = batch\r\n logits = self(x)\r\n loss = self.loss_fun(logits, y)\r\n preds = logits.argmax(1)\r\n self.test_accuracy.update(preds, y)\r\n self.log(\"test_loss\", loss, prog_bar=True, on_step=False, on_epoch=True)\r\n self.log(\"test_acc\", self.test_accuracy, prog_bar=True, on_step=False, on_epoch=True)\r\n def predict_step(self, batch, batch_idx):\r\n # Write predict step\r\n x, y = batch\r\n logits = self(x)\r\n preds = logits.argmax(1)\r\n return [preds, y]\r\n\r\n def configure_optimizers(self):\r\n optimizer = torch.optim.SGD(self.parameters(), lr=self.learning_rate)\r\n return optimizer\r\n\r\n ####################\r\n # DATA RELATED HOOKS\r\n ####################\r\n\r\n def train_dataloader(self):\r\n return trainloader\r\n \r\n def val_dataloader(self):\r\n return valloader\r\n\r\n def test_dataloader(self):\r\n return testloader\r\n\r\n\r\n# ### 3.2 Train and evaluate model's performance for following scenarios\r\n# \r\n# a. fc1 : Linear(784 $\\times$ 128) $\\rightarrow$ ReLU $\\rightarrow$ fc2 : Linear(128 $\\times$ 64) $\\rightarrow$ ReLU $\\rightarrow$ fc3 : Linear(64 $\\times$ 32) ->$\\rightarrow$ Relu $\\rightarrow$ fc4 : Linear(32 $\\times$ 10)\r\n# \r\n# b. fc1 : Linear(784 $\\times$ 32) $\\rightarrow$ ReLU $\\rightarrow$ fc2 : Linear(32 $\\times$ 64) $\\rightarrow$ ReLU $\\rightarrow$ fc3 : Linear(64 $\\times$ 128) $\\rightarrow$ Relu $\\rightarrow$ fc4 : Linear(128 $\\times$ 10)\r\n# \r\n# c. fc1 : Linear(784 $\\times$ 64) $\\rightarrow$ ReLU $\\rightarrow$ fc2 : Linear(64 $\\times$ 64) $\\rightarrow$ ReLU $\\rightarrow$ fc3 : Linear(64 $\\times$ 64) $\\rightarrow$ Relu $\\rightarrow$ fc4 : Linear(64 $\\times$ 10)\r\n# \r\n# Note: Make sure to have different log file directories (eg: logs_task_3a, logs_task_3b and logs_task_3c)\r\n\r\n# In[53]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n\r\n# Initialize Deep MLP model for scenario 3a\r\nmodel = Deep_MLP(n1=128, n2=64, n3=32)\r\n\r\n# Define checkpoint callback function to save best model\r\ncheckpoint_callback_3a = ModelCheckpoint(monitor=\"val_acc\",dirpath=\"logs_task_3a/\",save_top_k=1,mode=\"max\",every_n_epochs=1)\r\n\r\n# Train and Test Model\r\ntrainer_3a = Trainer(\r\n accelerator=\"auto\",\r\n devices=1 if torch.cuda.is_available() else None, \r\n max_epochs=100,\r\n callbacks=[TQDMProgressBar(refresh_rate=20), checkpoint_callback_3a],\r\n logger=CSVLogger(save_dir=\"logs_task_3a/\"),\r\n)\r\ntrainer_3a.fit(model)\r\ntrainer_3a.test()\r\n\r\n\r\n# If your implementation is correct, you should obtain a printed output similar to this:\r\n# \r\n# [{'test_loss': 0.4924968481063843, 'test_acc': 0.8584499955177307}]\r\n\r\n# In[54]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Initialize Deep MLP model for scenario 3b\r\nmodel = Deep_MLP(n1=32, n2=64, n3=128)\r\n\r\n# Define checkpoint callback function to save best model\r\ncheckpoint_callback_3b = ModelCheckpoint(monitor=\"val_acc\",dirpath=\"logs_task_3b/\",save_top_k=1,mode=\"max\",every_n_epochs=1)\r\n\r\n# Train and Test Model\r\ntrainer_3b = Trainer(\r\n accelerator=\"auto\",\r\n devices=1 if torch.cuda.is_available() else None, \r\n max_epochs=100,\r\n callbacks=[TQDMProgressBar(refresh_rate=20), checkpoint_callback_3b],\r\n logger=CSVLogger(save_dir=\"logs_task_3b/\"),\r\n)\r\ntrainer_3b.fit(model)\r\ntrainer_3b.test()\r\n\r\n\r\n# If your implementation is correct, you should obtain a printed output similar to this:\r\n# \r\n# [{'test_loss': 0.4536038041114807, 'test_acc': 0.8570333123207092}]\r\n\r\n# In[55]:\r\n\r\n\r\n# Initialize Deep MLP model for scenario 3c\r\nmodel = Deep_MLP(n1=64, n2=64, n3=64)\r\n\r\n# Define checkpoint callback function to save best model\r\ncheckpoint_callback_3c = ModelCheckpoint(monitor=\"val_acc\",dirpath=\"logs_task_3c/\",save_top_k=1,mode=\"max\",every_n_epochs=1)\r\n\r\n# Train and Test Model\r\ntrainer_3c = Trainer(\r\n accelerator=\"auto\",\r\n devices=1 if torch.cuda.is_available() else None, # limiting got iPython runs\r\n max_epochs=100,\r\n callbacks=[TQDMProgressBar(refresh_rate=20), checkpoint_callback_3c],\r\n logger=CSVLogger(save_dir=\"logs_task_3c/\"),\r\n)\r\ntrainer_3c.fit(model)\r\ntrainer_3c.test()\r\n\r\n\r\n# If your implementation is correct, you should obtain a printed output similar to this:\r\n# \r\n# [{'test_loss': 0.40754958987236023, 'test_acc': 0.8532999753952026}]\r\n\r\n# ### 3.3 Plot Training loss vs Validation loss for the different deep networks\r\n\r\n# In[58]:\r\n\r\n\r\nset_background(red_bgd)\r\n# read logs for 3a\r\ntraining_data_3a = pd.read_csv(trainer_3a.logger.log_dir + \"/metrics.csv\")\r\ntraining_loss_3a = training_data_3a[\"train_loss\"].dropna()\r\nval_loss_3a = training_data_3a[\"val_loss\"].dropna()\r\n# read logs for 3b\r\ntraining_data_3b = pd.read_csv(trainer_3b.logger.log_dir + \"/metrics.csv\")\r\ntraining_loss_3b = training_data_3b[\"train_loss\"].dropna()\r\nval_loss_3b = training_data_3b[\"val_loss\"].dropna()\r\n# read logs for 3c\r\ntraining_data_3c = pd.read_csv(trainer_3c.logger.log_dir + \"/metrics.csv\")\r\ntraining_loss_3c = training_data_3c[\"train_loss\"].dropna()\r\nval_loss_3c = training_data_3c[\"val_loss\"].dropna()\r\n\r\n\r\n# In[59]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Plot using matplotlib, you can overlay the graphs.\r\nfig11, (ax111, ax112) = plt.subplots(1,2)\r\nax111.plot(training_loss_3a, label=\"n1 = 128, n2 = 64, n3 = 32\")\r\nax111.plot(training_loss_3b, label=\"n1 = 32, n2 = 64, n3 = 128\")\r\nax111.plot(training_loss_3c, label=\"n1 = 64, n2 = 64, n3 = 64\")\r\nax111.set_title(\"The Train_Loss of Deep MLP\", fontsize=20)\r\nax111.set_xlabel(\"Epochs\")\r\nax111.set_ylabel(\"Loss\")\r\nax111.legend(prop={'size': 15})\r\nax112.plot(val_loss_3a, label=\"n1=128, n2=64, n3=32\")\r\nax112.plot(val_loss_3b, label=\"n1=32, n2=64, n3=128\")\r\nax112.plot(val_loss_3c, label=\"n1=64, n2=64, n3=64\")\r\nax112.set_title(\"The Val_Loss of Deep MLP\", fontsize=20)\r\nax112.set_xlabel(\"Epochs\")\r\nax112.set_ylabel(\"Loss\")\r\nax112.legend(prop={'size': 15})\r\nplt.gcf().set_size_inches(20,10)\r\nplt.show()\r\n\r\n\r\n# ### 3.4 Visualize 5 predictions of test set along with groundtruths and input images for 3rd Deep MLP\r\n\r\n# In[60]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Generate predictions using predict function\r\npredictions_3c = trainer_3c.predict(dataloaders=testloader)\r\n\r\n# visualize predictions along with ground truths and input images using matplotlib\r\ntest_loader_iter = iter(testloader)\r\ntest_data, test_labels = test_loader_iter.next()\r\nvis_preds(testloader, predictions_3c)\r\n\r\n\r\n# ### 3.5 Discussion:\r\n\r\n# In[ ]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Question: Did you observe a strange behaviour for the deep MLPs? If yes, what is that ? Discuss what might be the source of that.\r\n\r\n# Answer here\r\n# >> Validation loss seems to increase after around 75 epochs regardless of hidden layer sizes. This may be\r\n# due to the increased complexity of the deep networks compared to shallow networks, forcing the model to \r\n# overfit to the training data. This is evident as the training loss seems to be decreasing at a comfortable\r\n# rate, but this is not the case for validation.\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\nset_background(red_bgd)\r\n\r\n# Question: How does the deep MLP compare with the shallow MLP for this case?\r\n\r\n# Answer here\r\n# >> Performance seems to be quite similar, however there is the risk that the deep MLP has overfit. \r\n# Regardless of this, both validation accuracies seem to be pretty similar, around 84%.\r\n\r\n\r\n# # Do not remove or edit the following code snippet. \r\n# \r\n# When submitting your report, please ensure that you have run the entire notebook from top to bottom. You can do this by clicking \"Kernel\" and \"Restart Kernel and Run All Cells\". Make sure the last cell (below) has also been run. \r\n\r\n# In[ ]:\r\n\r\n\r\nfile_name = str(student_number) + 'Lab_3_Student'\r\ncmd = \"jupyter nbconvert --to script Lab_3_Student.ipynb --output \" + file_name\r\nif(os.system(cmd)):\r\n print(\"Error converting to .py\")\r\n print(\"cmd\")\r\n\r\n\r\n#
\r\n# \r\n# #
That is all for this Lab!\r\n# \r\n#
\r\n","repo_name":"wlfAI/ECE4179-homework","sub_path":"lab_3/12345678Lab_3_Student.py","file_name":"12345678Lab_3_Student.py","file_ext":"py","file_size_in_byte":50931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"3740802120","text":"class OrderBook(object):\r\n\tdef __init__(self, order_book):\r\n\t\tself.bids = []\r\n\t\tself.asks = []\r\n\t\tif order_book is not None:\r\n\t\t\tfor bid in order_book['bids']:\r\n\t\t\t\tnew_bid = BidAskEntry(bid)\r\n\t\t\t\tself.bids.append(new_bid)\r\n\t\t\tfor ask in order_book['asks']:\r\n\t\t\t\tnew_ask = BidAskEntry(ask)\r\n\t\t\t\tself.asks.append(new_ask)\r\n\r\n\tdef getBids(self):\r\n\t\treturn self.bids\r\n\r\n\tdef getAsks(self):\r\n\t\treturn self.asks\r\n\r\n\tdef appendBid(self, bid):\r\n\t\tif type(bid) is BidAskEntry:\r\n\t\t\tself.bids.append(bid)\r\n\r\n\tdef appendAsk(self, ask):\r\n\t\tif type(bid) is BidAskEntry:\r\n\t\t\tself.asks.append(ask)\r\n\r\n\tdef pretty_print(self):\r\n\t\tprint ('{ ')\r\n\t\tprint ('\\tAsks: [')\r\n\t\tfor bid in self.bids:\r\n\t\t\tbid.pretty_print()\r\n\t\tprint ('\\t],')\r\n\t\tprint ('\\tBids: [')\r\n\t\tfor ask in self.asks:\r\n\t\t\task.pretty_print()\r\n\t\tprint ('\\t]')\r\n\t\tprint ('}')\r\n\r\n\r\nclass BidAskEntry(object):\r\n\tdef __init__(self, entry):\r\n\t\tif entry is not None:\r\n\t\t\tself.price = entry[0]\r\n\t\t\tself.size = entry[1]\r\n\t\t\tself.number_orders = entry[2]\r\n\t\telse:\r\n\t\t\tself.price = 0\r\n\t\t\tself.size = 0.0\r\n\t\t\tself.number_orders = 0\r\n\r\n\tdef pretty_print(self):\r\n\t\tprint ('\\t\\t[ Price: ' + str(self.price) + ', Size: ' + str(self.size) + ', Number of Orders: ' + str(self.number_orders) + ' ]')","repo_name":"matt-garner/gdaxtesting","sub_path":"order_book.py","file_name":"order_book.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"14551021729","text":"\nimport pandas as pd\nimport numpy as np\nimport urllib\nfrom io import StringIO\n\n\ndef get_cleaned_data(location):\n #link = \"https://firebasestorage.googleapis.com/v0/b/warewolves.appspot.com/o/PM_train.csv?alt=media&token=89333a8a-bef3-458d-8269-fe0bfd5572fa\"\n link=location\n f = urllib.request.urlopen(link)\n myfile = f.read()\n s=str(myfile,'utf-8')\n data = StringIO(s)\n dataset_train=pd.read_csv(data,sep=' ',header=None).drop([26,27],axis=1)\n col_names = ['id','cycle','setting1','setting2','setting3','s1','s2','s3','s4','s5','s6','s7','s8','s9','s10','s11','s12','s13','s14','s15','s16','s17','s18','s19','s20','s21']\n dataset_train.columns=col_names\n dataset_train['ttf'] = dataset_train.groupby(['id'])['cycle'].transform(max)-dataset_train['cycle']\n dataset_train.head()\n df_train=dataset_train.copy()\n period=30\n df_train['label_bc'] = df_train['ttf'].apply(lambda x: 1 if x <= period else 0)\n result=df_train\n\n return(result)\n\n\n\n#location=\"https://firebasestorage.googleapis.com/v0/b/warewolves.appspot.com/o/PM_train.csv?alt=media&token=89333a8a-bef3-458d-8269-fe0bfd5572fa\"\n#data=get_cleaned_data(location)\n#data.head()\n\n\ndef data_analysis(location,machine_name,sensor_names,cycles):\n df_train=get_cleaned_data(location)\n\n data_part=df_train[df_train[\"id\"]==machine_name]\n data_part=data_part[(data_part[\"cycle\"]>=cycles[0]) & (data_part[\"cycle\"]<=cycles[1])]\n\n data_part.set_index('cycle', inplace=True)\n columns_keep=sensor_names\n data_part=data_part[columns_keep]\n\n #print(data_part.head())\n result=data_part.to_dict()\n #print(result)\n\n new_dict={}\n for sensor,info in result.items():\n new_dict[sensor]={}\n new_dict[sensor][\"Day\"]=list(result[sensor].keys())\n new_dict[sensor][\"Value\"]=list(result[sensor].values())\n\n #print(new_dict)\n return(new_dict)\n\n\n#location=\"https://firebasestorage.googleapis.com/v0/b/warewolves.appspot.com/o/PM_train.csv?alt=media&token=89333a8a-bef3-458d-8269-fe0bfd5572fa\"\n#machine_name=1\n#cycles=[5,15]\n#sensor_names=[\"s1\",\"s2\",\"s3\",\"s4\"]\n#dict_output=data_analysis(location,machine_name,sensor_names,cycles)\n#print(dict_output)\n\n\n# In[ ]:\n\n\n#def null_rows():\n #df_train=get_cleaned_data(location)\n#df_train.columns[df_train.isnull().any()].tolist()\n\n\ndef no_failues(location):\n df_train=get_cleaned_data(location)\n data_part=df_train\n\n rul = pd.DataFrame(data_part.groupby('id')['cycle'].max()).reset_index()\n rul.columns = ['id', 'max']\n\n df=rul.groupby(\"max\")[\"id\"].apply(list)\n result=df.to_dict()\n\n\n new_dict={}\n\n for day,info in result.items():\n new_dict[day]={}\n new_dict[day][\"Machine\"]=info\n\n max_day=max(result.keys())\n for i in range(max_day):\n if i not in new_dict.keys():\n new_dict[i]={}\n new_dict[i][\"Machine\"]=[]\n\n\n #print(new_dict)\n return(new_dict)\n\n\n\n#location=\"https://firebasestorage.googleapis.com/v0/b/warewolves.appspot.com/o/PM_train.csv?alt=media&token=89333a8a-bef3-458d-8269-fe0bfd5572fa\"\n#dict_output=no_failues(location)\n#print(dict_output)\n\n\n\ndef correlated_sensors(location):\n df_train=get_cleaned_data(location)\n\n sensor_columns=df_train.columns[5:-2]\n data_part=df_train[sensor_columns]\n #print(data_part.corrcoef())\n\n correlated_columns=[]\n sensor_columns=df_train.columns[5:-2]\n for column in sensor_columns:\n corr_mat = np.corrcoef(df_train[column],df_train[\"ttf\"])\n score=abs(round(corr_mat[0,1],2))\n if(score>0.5):\n correlated_columns.append(column)\n return(correlated_columns)\n\n\n#location=\"https://firebasestorage.googleapis.com/v0/b/warewolves.appspot.com/o/PM_train.csv?alt=media&token=89333a8a-bef3-458d-8269-fe0bfd5572fa\"\n#sensors=correlated_sensors(location)\n\n\n\n# import pandas as pd\n# import numpy as np\n# import urllib\n# from io import StringIO\n\n# def get_cleaned_data():\n# \tlink = \"https://firebasestorage.googleapis.com/v0/b/warewolves.appspot.com/o/PM_train.csv?alt=media&token=89333a8a-bef3-458d-8269-fe0bfd5572fa\"\n# \tf = urllib.request.urlopen(link)\n# \tmyfile = f.read()\n# \ts=str(myfile,'utf-8')\n# \tdata = StringIO(s)\n# \tdataset_train=pd.read_csv(data,sep=' ',header=None).drop([26,27],axis=1)\n\n\n\n# \t#dataset_train=pd.read_csv(\"/Users/divalicious/Desktop/PredictiveMaintainence/PM_train.txt\",sep=' ',header=None).drop([26,27],axis=1)\n# \tcol_names = ['id','cycle','setting1','setting2','setting3','s1','s2','s3','s4','s5','s6','s7','s8','s9','s10','s11','s12','s13','s14','s15','s16','s17','s18','s19','s20','s21']\n# \tdataset_train.columns=col_names\n# \tdataset_train['ttf'] = dataset_train.groupby(['id'])['cycle'].transform(max)-dataset_train['cycle']\n# \tdataset_train.head()\n# \tdf_train=dataset_train.copy()\n# \tperiod=30\n# \tdf_train['label_bc'] = df_train['ttf'].apply(lambda x: 1 if x <= period else 0)\n# \tresult=dataset_train[\"id\"][0]\n\n\n# \treturn(result)\n\n\n\n# re=get_cleaned_data()\n# print(type(re))\n\n\n#\n\n\n\n\n","repo_name":"divapriya/WareHouse_PredictiveAnalytics","sub_path":"prototype1.py","file_name":"prototype1.py","file_ext":"py","file_size_in_byte":4951,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"29873657095","text":"from tools import *\nfrom gpt2 import *\nfrom transformers import GPT2Tokenizer\nfrom tqdm import tqdm, trange\nimport numpy as np\nimport torch\n\nsentence_prop = InjectedProperty('sentence')\n\ndef tokenized_prop_for(s_prop):\n def tokenize(d):\n result = []\n for s in tqdm(d[s_prop]):\n result.append([\n tokenizer(s)['input_ids']\n ])\n return result\n\n return Property(\n [s_prop],\n s_prop.name + '_tok',\n tokenize\n )\n\nclass LSTM_LM(torch.nn.Module):\n def __init__(self, vocab = 50257, layers = 2, hidden_size = 1024, dropout = 0.2):\n super(LSTM_LM, self).__init__()\n self.vocab = vocab\n self.layers = layers\n self.hidden_size = hidden_size\n self.dropout = dropout\n\n self.embed = torch.nn.Embedding(\n num_embeddings = vocab,\n embedding_dim = hidden_size\n )\n self.lstm = torch.nn.LSTM(\n input_size = hidden_size,\n hidden_size = hidden_size,\n num_layers = layers,\n dropout = dropout\n )\n self.out = torch.nn.Linear(\n hidden_size,\n vocab\n )\n\n def forward(self, inp, state):\n embed = torch.nn.utils.rnn.PackedSequence(\n self.embed(inp.data),\n inp.batch_sizes\n )\n output, state = self.lstm(embed, state)\n result = torch.nn.utils.rnn.PackedSequence(\n self.out(output.data),\n output.batch_sizes\n )\n return result, state\n\n def init_state(self, batch, cuda = False):\n if cuda:\n return (\n torch.zeros(self.layers, batch, self.hidden_size).cuda(),\n torch.zeros(self.layers, batch, self.hidden_size).cuda()\n )\n else:\n return (\n torch.zeros(self.layers, batch, self.hidden_size),\n torch.zeros(self.layers, batch, self.hidden_size)\n )\n\ndef packed_seq(batch):\n if any(len(s) <= 1 for s in batch):\n return None, None\n\n return (\n # Inputs\n torch.nn.utils.rnn.pack_sequence([\n torch.LongTensor(seq[:-1]) for seq in batch\n ]),\n # Targets\n torch.nn.utils.rnn.pack_sequence([\n torch.LongTensor(seq[1:]) for seq in batch\n ])\n )\n\ndef lstm_prop(s_prop,\n seed = 0,\n hidden_size = 1024,\n layers = 2,\n dropout = 0.2,\n batch_size = 32,\n epochs = 5\n ):\n\n t_prop = tokenized_prop_for(s_prop)\n\n def train_lstm(d):\n torch.manual_seed(seed)\n np.random.seed(seed)\n\n model = LSTM_LM(\n layers = layers,\n hidden_size = hidden_size,\n dropout = dropout\n ).cuda()\n\n sorted_sentences = sorted(\n [x[0] for x in d[t_prop] if 1 < len(x[0]) < 512], # Limit batch size\n key = lambda x: -len(x)\n )\n batches = [\n packed_seq(sorted_sentences[i:i + batch_size])\n for i in trange(len(sorted_sentences) // batch_size + 1)\n ]\n\n criterion = torch.nn.CrossEntropyLoss()\n optim = torch.optim.Adam(model.parameters(), lr = 3e-4)\n\n for _ in range(epochs):\n np.random.shuffle(batches)\n running_loss = 0\n i = 0\n\n for batch, target in tqdm(batches):\n if batch is None:\n continue\n batch, target = batch.cuda(), target.cuda()\n output, state = model(\n batch,\n tuple(\n x.cuda() for x in model.init_state(batch.batch_sizes[0])\n )\n )\n loss = criterion(\n output.data,\n target.data\n )\n running_loss = running_loss * 0.95 + 0.05 * (loss.detach().cpu())\n optim.zero_grad()\n loss.backward()\n optim.step()\n if i % 1000 == 0:\n print('Running loss: %f' % running_loss)\n i += 1\n '''\n for sliceable_batch, lengths in tqdm(batches):\n state = tuple(\n x.cuda()\n for x in model.init_state(sliceable_batch.shape[0])\n )\n seq_len = sliceable_batch.shape[1]\n\n optim.zero_grad()\n loss = 0\n for i in range(seq_len - 1):\n output, state = model(\n sliceable_batch[:, i].cuda(),\n state\n )\n\n loss += criterion(\n output[:lengths[i + 1]],\n sliceable_batch[:, i + 1][:lengths[i + 1]]\n )\n loss.backward()\n optim.step()\n '''\n\n return model\n\n return Property(\n [t_prop],\n s_prop.name + '_lstm_%d_%d_%d_%f_%d_%d' % (seed, hidden_size, layers, dropout, batch_size, epochs),\n train_lstm\n )\n","repo_name":"dabbler0/semantic-syntactic","sub_path":"lstms.py","file_name":"lstms.py","file_ext":"py","file_size_in_byte":5104,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"16618273207","text":"from deck import Card, Deck\nfrom player import Player, User, Dealer\n\n\nclass Round:\n\t\"\"\"start a round of blackjack\n\tArguments\n\t----------\n\tdeck : shared deck of cards between classes\n\tParameters\n\t----------\n\tuser : player class controlled by input\n\tdealer : player class controlled by hit rules\n\tmxscore : maximum score without busting\n\t\"\"\"\n\tdef __init__(self, deck):\n\t\tself.deck = deck\n\t\tself.user = User(deck)\n\t\tself.dealer = Dealer(deck)\n\t\tself.mxscore = 21\n\t\tself.deck.shuffle()\n\n\tdef play(self):\n\t\tdef deal(self):\n\t\t\tself.user.get_card()\n\t\t\tself.user.get_card()\n\t\t\tself.dealer.get_card()\n\t\t\tprint(\"\\nDealer has {0} ??? for a visible total of {1} points\".format(str(self.dealer), self.dealer.first_ace()))\n\t\t\tself.dealer.get_card() # Dealer gets 2nd card after first print to keep 2nd card hidden\n\t\t\tprint(\"You have {0} for a total of {1} points\".format(str(self.user), self.user.score()))\n\t\t\tprint(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n\t\t\tcheck_blackjack(self)\n\n\t\tdef check_blackjack(self):\n\t\t\tif self.dealer.score() == 21:\n\t\t\t\tprint(\"Dealer has {0} for a total of {1} points\".format(str(self.dealer), self.dealer.score()))\n\t\t\t\tprint(\"Dealer got a Blackjack! You Lose!\")\n\t\t\telif self.user.score() == 21:\n\t\t\t\tprint(\"You got a Blackjack! You Win!\")\n\t\t\telse:\n\t\t\t\tuser_hit(self)\n\n\t\tdef user_hit(self):\n\t\t\twhile self.user.score() <= 21 and self.user.hit():\n\t\t\t\tif self.user.score() > 21:\n\t\t\t\t\tprint(\"You have {0} for a total of {1} points. \\nYOU BUSTED!\".format(str(self.user), self.user.score()))\n\t\t\t\tif self.user.score() <= 21:\n\t\t\t\t\tprint(\"You have {0} for a total of {1} points.\".format(str(self.user), self.user.score()))\n\t\t\tif self.user.score() <= 21:\n\t\t\t\tprint(\"You stay with {0} for a total of {1} points.\".format(str(self.user), self.user.score()))\n\t\t\t\tprint(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n\t\t\t\tdealer_hit(self)\n\t\t\t\t\n\t\tdef dealer_hit(self):\n\t\t\tprint(\"Dealer has {0} for a total of {1} points.\".format(str(self.dealer), self.dealer.score()))\n\t\t\tif self.dealer.score() >= 17:\n\t\t\t\tprint(\"Dealer stays at {0}\".format(self.dealer.score()))\n\t\t\t\tprint(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n\t\t\t\tcompare_score(self)\n\t\t\twhile self.dealer.score() < 17:\n\t\t\t\tprint(\"Dealer Hits\")\n\t\t\t\tself.dealer.hit()\n\t\t\t\tprint(\"Dealer has {0} for a total of {1} points.\".format(str(self.dealer), self.dealer.score()))\n\t\t\t\tif 17 <= self.dealer.score() <= 21:\n\t\t\t\t\tprint(\"Dealer stays at {0}\".format(self.dealer.score()))\n\t\t\t\t\tprint(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n\t\t\t\t\tcompare_score(self)\n\t\t\t\telif self.dealer.score() > 21:\n\t\t\t\t\tprint(\"DEALER BUSTED!\".format(str(self.dealer), self.dealer.score()))\n\n\t\tdef compare_score(self):\n\t\t\tif self.user.score <= self.dealer.score:\n\t\t\t\tprint(\"The Dealer's {0} beats your {1}. \\nYOU LOSE!\").format(self.dealer.score(), self.user.score())\n\t\t\tif self.user.score > self.dealer.score:\n\t\t\t\tprint(\"Your {0} beats the Dealer's {1}. \\nYOU WIN!\").format(self.user.score(), self.dealer.score())\n\t\t\t\t\n\t\tdeal(self)\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\n\t\t\t\t\n\t\t\t\t\t# if self.dealer.score() <= 21:\n\t\t\t\t\t# \tprint(\"Dealer Hits\")\n\t\t\t\t\t# \tprint(\"Dealer has {0} for a total of {1} points.\".format(str(self.dealer), self.dealer.score()))\n\t\t\t\t\t# else:\n\t\t\t\t\t# \tprint(\"Dealer has {0} for a total of {1} points. DEALER BUSTED!\".format(str(self.dealer), self.dealer.score()))\nclass Blackjack:\n\t\"\"\"holds multiple rounds of blackjack\"\"\"\n\tdef __init__(self):\n\t\tpass\n\ndef test():\n\tdef round_test():\n\t\tplayer = Round(Deck())\n\t\tplayer.play()\n\tround_test()\n\n\n\nif __name__ == \"__main__\":\n\ttest()\n\n\n\n","repo_name":"moranconnorj/blackjack","sub_path":"blackjack.py","file_name":"blackjack.py","file_ext":"py","file_size_in_byte":3537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"13722727693","text":"\"\"\"Deep texture interpolation.\n\nExample:\n Synthesize a texture that interpolate two input textures :\n python3 run_synthesis.py --input_tex_1 curvy.jpg\n --input_tex_2 woven.jpg\n --weight_1 0.5\n \nSee options/base_options.py and options/train_options.py for more training options.\n\"\"\"\nimport time\nimport visdom\nfrom options.base_options import BaseOptions\nfrom models import create_model, utils\nimport torch\n\n\nif __name__ == '__main__':\n opt = BaseOptions().parse() # get training options\n \n if utils.socket_is_used(opt.display_port,'localhost'):\n vis = visdom.Visdom(port=opt.display_port, use_incoming_socket=False)\n else: \n print('Visom server is not running at localhost:'+str(opt.display_port))\n \n model = create_model(opt) # create a model given opt.model and other options\n \n model.get_net_and_loss()\n init_time = time.time() \n for epoch in range(opt.n_iter+1): \n model.optimize_parameters()\n if epoch%opt.display_freq==0:\n image = 255*model.output_tex.data.clamp_(0,1).squeeze(0)\n if utils.socket_is_used(opt.display_port,'localhost'):\n vis.image(image, win=opt.win)\n print(\"Iteration : {}\".format(epoch))\n print('Duration : {}'.format(time.time()-init_time))\n print('Tex Loss : {:4f}'.format(model.tex_score.item()))\n \n output_tex = model.output_tex.data.clamp_(0,1) \n \n utils.save_image(utils.tensor2im(output_tex), opt.output_tex,\n aspect_ratio=1.0)\n \n","repo_name":"JonathanVacher/texture-interpolation","sub_path":"texture-synthesis-algorithm/run_synthesis.py","file_name":"run_synthesis.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"77"} +{"seq_id":"41959969728","text":"# searchRule-matchPatt2.py\r\n# A new implementation of searchRule-matchPatt.py\r\n# Searches for small oscillators and spaceships in the isotropic 2-state CA\r\n# rulespace where several phases of the starting pattern match the evolution\r\n# of the pattern in the current layer.\r\n#\r\n# by Arie Paap, Jun 2019\r\n# Original random rule search scripts by Arie Paap and Rhombic\r\n#\r\n# Differences from searchRule-matchPatt.py:\r\n# - Press 'q' to stop searching (instead of aborting with 'Esc')\r\n# - Uses routines from sss.py library to analyse small patterns in isotropic\r\n# 2-state rules\r\n# - Maintains record of found spaceship speeds to avoid reporting duplicate\r\n# results (set bUniqueSpeeds to false to disable)\r\n# - Optionally allows pattern to be run for a short stabilisation time prior\r\n# to testing for periodicity\r\n# - Optionally loads previously found speeds from output file at start of\r\n# search\r\n# - Optionally also load ships from 5S project into record of known speeds\r\n# - Random rule generator uses an iterator which pseudo randomly scans the\r\n# entire rulespace\r\n#\r\n# Potential features to be added\r\n# - XXX Save the random rule iterators' current state when interrupting the\r\n# search so that it can be resumed (repeating the same search without\r\n# changing the seed will search the same rules)\r\n\r\nfrom __future__ import division\r\n\r\nimport time\r\nimport timeit\r\nimport golly as g\r\nimport sss\r\n\r\ntimer = timeit.default_timer\r\nxrange = sss.xrange\r\n\r\n# Search parameters\r\n\r\n# Exclude ships with period less than minShipP\r\nminShipP = 30\r\n# Fast ships have a lower threshold for interesting period\r\nminSpeed = 0.5\r\nfastShipP = 9\r\n# Exclude oscillators with period less than minOscP\r\nminOscP = 3\r\n# Maximum period to test the pattern for\r\nmaxGen = 20000 # 20000\r\n# Maximum population in any phase\r\nmaxPop = 1000 # 1000\r\n# Maximum bounding box dimension (0 to disable)\r\n# - Early abort testRule() when stabilisation not detected e.g. when\r\n# spaceships emitted in multiple directions\r\nmaxDim = 500 # 500\r\n# Allow search for oscillators\r\nbOsc = False\r\n# Output file\r\nresultsFile = 'matchPatt2-test.txt'\r\n# Only record ships with unique speed? (or smaller than previously found)\r\nbUniqueSpeeds = True # True\r\n# Import 5S project into known speeds?\r\nbImport5S = True # True\r\n# Special case speeds to ignore (useful when bUniqueSpeeds = False)\r\nignoreResults = [] # A list of the form: [(dx, dy, P)]\r\n\r\n# Number of generations to match pattern behaviour\r\ns = g.getstring('How many generations to remain unchanged:', '', 'Rules calculator')\r\nif not s.isdigit():\r\n g.exit('Bad number: %s' % s)\r\nnumgen = int(s)\r\nif numgen < 1:\r\n g.exit('Generations to match must be at least 1.')\r\n# Seed for random rule generator\r\nseed = 1\r\n\r\n# Initial stabilisation time\r\n# Test pattern is run in each random rule for stabGen generations before \r\n# periodicity detection begins\r\n# Set to 0 to only match the test pattern\r\nstabCycles = 5 # 5\r\nstabGen = stabCycles * numgen\r\n# Stability check periodicity\r\n# - Used to detect if pattern becomes periodic after initial stabilisation time\r\n# Pattern won't be detected as an oscillator or spaceship, just avoids\r\n# simulting until maxGen generations have passed.\r\nstabCheckP = 24 # 24\r\n\r\n# Minimum population criteria\r\n# - Probably redundant now that stability checking has been added\r\nif bOsc: minPop = 2 # Patterns with 0, or 1 cells can not be oscillators\r\nelse: minPop = 3 # Patterns with 0, 1, or 2 cells can not be ships\r\n\r\n# Test pattern in given rule\r\n# Original pattern is evolved in the given randomly generated rule.\r\n# Pattern is evolved for a short stabilisation period and then tested to\r\n# determine if it has become an oscillator or a spaceship. \r\ndef testRule(rulestr):\r\n r = g.getrect()\r\n if r:\r\n g.select(r)\r\n g.clear(0)\r\n g.putcells(origPatt)\r\n g.setrule(rulestr)\r\n g.run(stabGen)\r\n if g.empty():\r\n return ()\r\n pop = int(g.getpop())\r\n if (pop < minPop or pop > maxPop):\r\n return ()\r\n r = g.getrect()\r\n testPatt = g.transform(g.getcells(r),-r[0],-r[1])\r\n testPop = int(g.getpop())\r\n testRect = g.getrect()\r\n stabPatt = list(testPatt)\r\n stabPop = testPop\r\n for ii in xrange(maxGen):\r\n g.run(1)\r\n pop = int(g.getpop())\r\n if (pop < minPop or pop > maxPop):\r\n break\r\n if (pop == testPop):\r\n # Test for periodicity\r\n r = g.getrect()\r\n if testPatt == g.transform(g.getcells(r),-r[0],-r[1]):\r\n period = ii+1\r\n dy, dx = sss.minmaxofabs((r[0] - testRect[0], r[1] - testRect[1]))\r\n if (dx == 0):\r\n # Oscillator (reject if low period or bOsc is False)\r\n if bOsc and period >= minOscP:\r\n return (0, 0, period)\r\n elif ( period >= minShipP ):\r\n # Spaceship\r\n return (dx, dy, period)\r\n elif ( (dx + dy/1.9) / (period * 1.0) > minSpeed and period >= fastShipP ):\r\n # Fast spaceship\r\n return (dx, dy, period)\r\n break # Pattern is a low period oscillator or spaceship\r\n # Stability check\r\n if (ii % stabCheckP == 0):\r\n r = g.getrect()\r\n # First check for BBox expansion\r\n if maxDim > 0 and max(r[2:4]) > maxDim:\r\n # Pattern is expanding\r\n # XXX Attempt to separate components expanding in different directions\r\n break\r\n currPatt = g.transform(g.getcells(r),-r[0],-r[1])\r\n if (pop == stabPop and currPatt == stabPatt):\r\n # Pattern has stabilised to low period oscillator / spaceship\r\n break\r\n stabPop = pop\r\n stabPatt = list(currPatt)\r\n return ()\r\n\r\n# Preload foundSpeeds from existing results file\r\nfoundSpeeds = {}\r\ndef loadKnownSpeeds(resultsFile):\r\n global foundSpeeds\r\n g.show('Loading known speeds from file %s' % resultsFile)\r\n try:\r\n with open(resultsFile, 'r') as rF:\r\n for line in rF:\r\n # Trust the data in the sss file, no need to test ships\r\n ship = sss.parseshipstr(line)\r\n if not ship:\r\n continue\r\n minpop, _, dx, dy, period, _ = ship\r\n try:\r\n if foundSpeeds[(dx, dy, period)] <= minpop:\r\n # Skip this speed unless the current ship is smaller\r\n continue\r\n except KeyError:\r\n pass\r\n foundSpeeds[(dx, dy, period)] = minpop\r\n except IOError:\r\n return 1\r\n return 0\r\n\r\nif bImport5S:\r\n bUniqueSpeeds = True\r\n shipFiles = ['Orthogonal ships.sss.txt', 'Diagonal ships.sss.txt', 'Oblique ships.sss.txt']\r\nelse:\r\n shipFiles = []\r\n \r\nstatus = 'Results file: %s.' % resultsFile\r\nif bUniqueSpeeds:\r\n with open(resultsFile, 'a+') as rF:\r\n pass\r\n shipFiles.append(resultsFile)\r\n for F in shipFiles:\r\n if loadKnownSpeeds(F):\r\n g.exit('Failed to load known speeds from file: %s' % F)\r\n status += ' %d known speeds loaded.' % len(foundSpeeds)\r\n\r\n# Set up the search with the current pattern\r\nr = g.getrect()\r\norigPop = int(g.getpop())\r\norigPatt = g.transform(g.getcells(r),-r[0],-r[1])\r\norigRule = g.getrule()\r\n\r\nNfound = 0\r\nupdateP = 1000\r\nlastRule = ''\r\n\r\ntry:\r\n # Begin the search\r\n g.new('MatchPatt')\r\n g.putcells(origPatt)\r\n \r\n # Determine the rulespace to search\r\n B_need, S_need, B_OK, S_OK = sss.getRuleRangeElems(numgen)\r\n rulerange = sss.rulestringopt('B' + ''.join(sorted(B_need)) + '/S' + ''.join(sorted(S_need)) + \\\r\n ' - B' + ''.join(sorted(B_OK)) + '/S' + ''.join(sorted(S_OK)))\r\n B_OK = [t for t in B_OK if t not in B_need]\r\n S_OK = [t for t in S_OK if t not in S_need]\r\n rulespace = len(B_OK) + len(S_OK)\r\n status += ' Matching pattern works in 2^%d rules: %s' % (rulespace, rulerange)\r\n g.show(status)\r\n g.update()\r\n time.sleep(2)\r\n \r\n # Results header\r\n with open(resultsFile, 'a') as rF:\r\n msg = '\\n# Search results matching pattern %s for %d gen' % (sss.giveRLE(origPatt), numgen)\r\n msg += ' in rule %s with searchRule-matchPatt2.py using seed=%d\\n' % (origRule, seed)\r\n rF.write(msg)\r\n \r\n start_time = timer()\r\n \r\n # Random rule iterator. Change seed to repeat search with different rules from given rulespace\r\n for (ii, rule) in enumerate(sss.iterRuleStr(B_OK, S_OK, B_need, S_need, seed=seed), start=1):\r\n result = testRule(rule)\r\n if result and (not result in ignoreResults):\r\n minpop = int(g.getpop())\r\n mingen = 0\r\n if bUniqueSpeeds:\r\n # Find minimum population\r\n for gen in xrange(1, result[2]):\r\n g.run(1)\r\n pop = int(g.getpop())\r\n if pop < minpop:\r\n minpop = pop\r\n mingen = gen\r\n g.run(1)\r\n try:\r\n if foundSpeeds[result] <= minpop:\r\n # Skip this speed unless the current ship is smaller\r\n continue\r\n except KeyError:\r\n pass\r\n foundSpeeds[result] = minpop\r\n # Interesting pattern found\r\n Nfound += 1\r\n dx, dy, period = result\r\n lastRule = rule\r\n if dy == 0:\r\n if dx == 0:\r\n description = 'Found oscillator with period = %d' % period\r\n else:\r\n description = 'Found orthogonal spaceship with speed = %dc/%d' % (dx, period)\r\n elif dy == dx:\r\n description = 'Found diagonal spaceship with speed = %dc/%d' % (dx, period)\r\n else:\r\n description = 'Found knightship with speed = (%d, %d)c/%d' % (dx, dy, period)\r\n g.show(description)\r\n g.run(mingen)\r\n shipRLE = sss.giveRLE(g.getcells(g.getrect()))\r\n sss.setminisorule(period)\r\n newship = (minpop, g.getrule(), dx, dy, period, shipRLE)\r\n with open(resultsFile, 'a') as rF:\r\n rF.write(', '.join(map(str, newship))+'\\n')\r\n if (ii % updateP == 0):\r\n curr_time = timer()\r\n g.select([])\r\n msg = '%d ships found after testing %d candidate rules out of 2^%d rule space' % (Nfound, ii, rulespace)\r\n msg += ', %d rules/second' % (updateP/(curr_time - start_time))\r\n start_time = curr_time\r\n g.show(msg)\r\n g.fit()\r\n g.setmag(3)\r\n g.update()\r\n event = g.getevent()\r\n if event == \"key q none\":\r\n # Interrupt the search\r\n # XXX Save the current state of the Rule generator's seed so that the search can be continued\r\n break\r\n g.new('')\r\n \r\nexcept IOError:\r\n g.note('Failed to open results file %s for writing!' % resultsFile)\r\n raise\r\nexcept Exception as e:\r\n raise\r\nfinally:\r\n g.new('Search result')\r\n g.putcells(origPatt)\r\n if lastRule:\r\n g.setrule(lastRule)\r\n g.show('%d ships found after testing %d candidate rules.' % (Nfound, ii))\r\n else:\r\n g.setrule(origRule)\r\n g.show('No results found after testing %d candidate rules.' % ii)\r\n","repo_name":"apaap/sssss","sub_path":"scripts/searchRule-matchPatt2.py","file_name":"searchRule-matchPatt2.py","file_ext":"py","file_size_in_byte":11542,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"77"} +{"seq_id":"9125076573","text":"\ninput = list(map(lambda x: int(x), open(\"6/input.txt\").read()[:-1].split(',')))\n\n#input = [3,4,3,1,2]\n\nfor day in range(80):\n to_add = 0\n for index, el in enumerate(input):\n if el == 0:\n to_add += 1\n input[index] = 6\n else:\n input[index] = el-1\n input += [8] * to_add\n\n\nprint(len(input))\n\n#1 = 353079","repo_name":"walkon23/aoc2021","sub_path":"6/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"40252936078","text":"'''\nhttps://leetcode-cn.com/problems/longest-continuous-increasing-subsequence\n\n给定一个未经排序的整数数组,找到最长且连续的的递增序列。\n示例 1:\n输入: [1,3,5,4,7]\n输出: 3\n解释: 最长连续递增序列是 [1,3,5], 长度为3。\n尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为5和7在原数组里被4隔开。 \n\n示例 2:\n输入: [2,2,2,2,2]\n输出: 1\n解释: 最长连续递增序列是 [2], 长度为1。\n\n注意:数组长度不会超过10000。\n'''\n\nclass Solution:\n def findLengthOfLCIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n \n\n\nif __name__ == '__main__':\n s = Solution()\n # ret = s.\n print(s)\n","repo_name":"chanfengsr/AllPrivateProject","sub_path":"Python/LeetCodeTraining/题库/0674 最长连续递增序列(Longest Continuous Increasing Subsequence).py","file_name":"0674 最长连续递增序列(Longest Continuous Increasing Subsequence).py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"zh","doc_type":"code","stars":5,"dataset":"github-code","pt":"77"} +{"seq_id":"8533830716","text":"import os\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\n\n\nHOME_DIR = os.environ['HOME_DIR']\nDATA_DIR = f'{HOME_DIR}data/zen/'\n\n\ndef dcg_at_k(r, k=20, method=0):\n \"\"\"\n Args:\n r: Relevance scores (list or numpy) in rank order\n (first element is the first item)\n k: Number of results to consider\n method: If 0 then weights are [1.0, 1.0, 0.6309, 0.5, 0.4307, ...]\n If 1 then weights are [1.0, 0.6309, 0.5, 0.4307, ...]\n Returns:\n Discounted cumulative gain\n \"\"\"\n r = np.asfarray(r)[:k]\n if r.size:\n if method == 0:\n return r[0] + np.sum(r[1:] / np.log2(np.arange(2, r.size + 1)))\n elif method == 1:\n return np.sum(r / np.log2(np.arange(2, r.size + 2)))\n else:\n raise ValueError('method must be 0 or 1.')\n return 0.\n\n\ndef ndcg_at_k(r, k=20, method=0):\n \"\"\"\n Args:\n r: Relevance scores (list or numpy) in rank order\n (first element is the first item)\n k: Number of results to consider\n method: If 0 then weights are [1.0, 1.0, 0.6309, 0.5, 0.4307, ...]\n If 1 then weights are [1.0, 0.6309, 0.5, 0.4307, ...]\n Returns:\n Normalized discounted cumulative gain\n \"\"\"\n dcg_max = dcg_at_k(sorted(r, reverse=True), k, method)\n if not dcg_max:\n return 0.\n return dcg_at_k(r, k, method) / dcg_max\n\n\nclass test:\n solution = pd.read_csv(f'{DATA_DIR}/solution.csv')\n ratings = {}\n user_items = {}\n user_ids = set(solution['userId'])\n for uid in tqdm(user_ids):\n uid_items = solution[solution['userId'] == uid]\n user_items[uid] = uid_items['itemId'].tolist()\n ratings[uid] = dict(zip(uid_items['itemId'], uid_items['rating']))\n\n @staticmethod\n def user_ndcg(user_id, ordered_items, k=20, method=1):\n true_ratings = test.ratings[user_id]\n return ndcg_at_k(list(map(lambda x: true_ratings[x], ordered_items)), k, method)\n\n @staticmethod\n def ndcg(predict, k=20, method=1):\n ndcg = 0\n for uid, items in tqdm(test.user_items.items()):\n ndcg += test.user_ndcg(\n uid,\n np.array(sorted(\n zip(predict(uid, items), items),\n key=lambda x: x[0],\n reverse=True))[:, 1],\n k, method\n )\n return ndcg / len(test.user_items)\n\n\nif __name__ == \"__main__\":\n click_rate_submission = pd.read_csv(f'{DATA_DIR}/click_rate_submission.csv')\n \n \n def predict(uid, items):\n predicted_order = click_rate_submission[click_rate_submission['userId'] == uid]['itemId'].values\n predicted_order = dict(zip(predicted_order, np.arange(predicted_order.shape[0], 0, -1)))\n return list(map(lambda x: predicted_order[x], items))\n \n \n test.ndcg(predict)\n","repo_name":"Xetd71/Content-based-Neural-Recommender-Systems","sub_path":"utils/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"38220805167","text":"from mayavi import mlab\nimport numpy as np\nfrom traits.api import HasTraits, Range, Instance, Enum, observe\nfrom traitsui.api import View, Item, Group, HSplit\nfrom mayavi.core.ui.api import MayaviScene, SceneEditor, \\\n MlabSceneModel\nfrom traitsui.api import CancelButton, OKButton\nfrom fft import fft2d\n\n\nclass plot(HasTraits):\n\n perc_coeffs = Range(1, 100, 100, desc='percent of coeff',\n enter_set=True, auto_set=False)\n display = Enum('Sinc', 'Cone', 'Rect', 'InvertedCone', desc='function')\n fft_pts = Enum('32', '64', '128', '256', '512', '1024')\n xrange = Range(1, 100, 20, desc='x Range',\n enter_set=True, auto_set=False)\n yrange = Range(1, 100, 20, desc='y Range',\n enter_set=True, auto_set=False)\n\n pts = 256\n\n scene = Instance(MlabSceneModel, args=())\n\n func = np.empty((1, 1))\n x = np.empty((1, 1))\n y = np.empty((1, 1))\n\n f_coeffs = np.empty((1, 1))\n f2 = np.empty((1, 1))\n\n view = View(HSplit(\n Group(Item('scene', editor=SceneEditor(scene_class=MayaviScene),\n height=550, width=600, show_label=False)),\n Group(\n Item('perc_coeffs'),\n Item('display'),\n Item('fft_pts'),\n Item('xrange'),\n Item('yrange')\n ),\n\n ), buttons=[OKButton, CancelButton]\n )\n\n def axis_mod(self):\n self.pts = int(self.fft_pts)\n\n self.x, self.y = np.mgrid[\n -1 * self.xrange:self.xrange:int(self.pts) * 1j,\n -1*self.yrange:self.yrange:int(self.pts) * 1j\n ]\n\n def disp(self):\n mlab.clf()\n x, y = self.x, self.y\n\n if self.display == 'Sinc':\n self.function = np.sinc(x/5)*np.sinc(y/5)*50\n elif self.display == 'Cone':\n self.function = 5 * np.sqrt(x ** 2 + y ** 2)\n elif self.display == 'InvertedCone':\n self.function = np.zeros_like(x)\n self.function = 50 - 5 * np.sqrt(x ** 2 + y ** 2)\n self.function[self.function < 0] = 0\n else:\n self.function = np.zeros_like(x)\n self.function[self.pts//4:3*self.pts //\n 4, self.pts//4:3*self.pts//4] = 25\n\n self.f_coeffs = fft2d(self.function)\n\n self.update()\n return\n\n def update(self):\n mlab.clf()\n x = self.x\n y = self.y\n x_idx = int(round(self.perc_coeffs * len(x) / 100))\n y_idx = int(round(self.perc_coeffs * len(y) / 100))\n f_coeffs = self.f_coeffs.copy()\n f_coeffs[:, y_idx:] = 0\n f_coeffs[x_idx:, :] = 0\n f2 = np.real(np.fft.ifft2(f_coeffs))\n mlab.surf(x, y, f2)\n mlab.axes()\n mlab.outline()\n return\n\n @observe('fft_pts, xrange, yrange, scene.activated')\n def change_axis(self, event=None):\n self.scene.mlab.clf()\n self.axis_mod()\n self.disp()\n\n @observe('display')\n def show_plot(self, event=None):\n self.scene.mlab.clf()\n self.disp()\n\n @observe('perc_coeffs')\n def update_plot(self, event=None):\n self.scene.mlab.clf()\n self.update()\n\n\ndef main():\n p = plot()\n p.configure_traits()\n return\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ShaunZac/AE6102-Fourier-Visualization","sub_path":"fourier_viz.py","file_name":"fourier_viz.py","file_ext":"py","file_size_in_byte":3241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"33000402864","text":"a=[]\nb=int(input(\"Enter the size of the Queue: \"))\n#Queue Means First in First Out\n#Using List we can create Queue by pushing Element at last and popping element at last\n#Here we will take length of the Queue as an input from the user \n#Queue is full Error: When we try to insert an element after the Queue is full\n#Queue is Empty Error: When we try to delete an element if the Queue is empty\n\nc=int(input(\"If you want to continue Enter 1 or else Enter 0 : \"))\n\nwhile c!=0:\n d=int(input(\"For Pushing Enter 1, For Popping Enter 0 : \"))\n if d==1:\n if len(a)0:\n print(a.pop(0))\n print(\"Current Queue is: \",a)\n else:\n print(\"Queue is empty\")\n c=int(input(\"If you want to continue Enter 1 or else Enter 0: \"))","repo_name":"manikanta-puppala/sandeep_8052","sub_path":"queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"32459075339","text":"# coding: UTF-8\nimport asyncio\nimport tornado.auth\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.options\nimport tornado.web\nimport tornado.autoreload\nfrom tornado.options import define, options\nfrom handlers import *\nimport session\nfrom settings import settings\nfrom cache import RedisCacheBackend\nimport redis\n\ndefine(\"port\", default=8888, help=\"run on the given port\", type=int)\ndefine(\"debug\", default=True, help=\"debug mode\", type=bool)\ndefine(\"mongo_host\", default=\"127.0.0.1:27017\", help=\"database host\")\n\nclass Application(tornado.web.Application):\n def __init__(self):\n handlers = [\n (r\"/\", HomeHandler),\n (r\"/logout\", LogoutHandler),\n (r\"/webhook\", WebhookHandler),\n (r\"/callback\", CallbackHandler),\n (r\"/stars\", UserStarHandler),\n (r\"/follows\", UserFollowingHandler),\n (r\"/cities\", UserCityhandler),\n (r\"/f\", FollowHandler),\n (r\"/uf\", UnfollowHandler),\n (r\"/add\", AddWebhookHandler),\n (r\"/show\", ShowHandler),\n (r\"/login\", LoginHandler),\n (r\"/howitworks\", HowHandler),\n (r\"/stat\", StatHandler),\n (r\"/users\", StatUserHandler),\n (r\"/repos\", StatRepoHandler),\n (r\"/export\", ExportHandler),\n\n ]\n self.session_manager = session.TornadoSessionManager(settings[\"session_secret\"], settings[\"session_dir\"])\n self.redis = redis.Redis()\n self.cache = RedisCacheBackend(self.redis)\n debug = False\n tornado.web.Application.__init__(self, handlers, **settings)\n\n\n# async def main():\n# tornado.options.parse_command_line()\n# application = tornado.web.Application([(r\"/\", MainHandler)])\n# http_server = tornado.httpserver.HTTPServer(application)\n# http_server.listen(options.port)\n# await asyncio.Event().wait()\n\n\nasync def main():\n tornado.options.parse_command_line()\n http_server = tornado.httpserver.HTTPServer(Application())\n http_server.listen(options.port)\n await asyncio.Event().wait()\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n","repo_name":"no13bus/ohmyrepo","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","stars":123,"dataset":"github-code","pt":"77"} +{"seq_id":"4256076999","text":"import sys\r\n# import bisect\r\ninput = sys.stdin.readline\r\n\r\nn = int(input())\r\narr = list(map(int, input().split()))\r\nm = int(input())\r\nbrr = list(map(int, input().split()))\r\narr.sort()\r\nfor x in brr:\r\n # x 이상의 첫번째 원소의 위치를 반환할 것이다.\r\n l0 = -1\r\n hi = n - 1\r\n while(l0 + 1 < hi):\r\n mid = (l0 + hi) // 2\r\n if arr[mid] < x:\r\n l0 = mid\r\n else:\r\n hi = mid\r\n if arr[hi] == x:\r\n print(1)\r\n else:\r\n print(0)\r\n","repo_name":"chwoong/algorithm","sub_path":"1000/1920.py","file_name":"1920.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"1234841210","text":"\"\"\" Test out different slang on the Naive Bayes Classifier! What happens when you use the word “lit” to mean “wonderful” or “fun”?\n\nIs the sentiment prediction accurate? Test out different slang. \"\"\"\n\n\n\n\nfrom reviews import counter, training_counts\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\n\n# Add your review:\nreview = \"It was fun!\"\nreview_counts = counter.transform([review])\n\nclassifier = MultinomialNB()\ntraining_labels = [0] * 1000 + [1] * 1000\n\nclassifier.fit(training_counts, training_labels)\n\nneg = (classifier.predict_proba(review_counts)[0][0] * 100).round()\npos = (classifier.predict_proba(review_counts)[0][1] * 100).round()\n\nif pos > 50:\n print(\"Naive Bayes classifies this as positive.\")\nelif neg > 50:\n print(\"Naive Bayes classifies this as negative.\")\nelse:\n print(\"Naive Bayes cannot determine if this is negative or positive.\")\n \n\nprint(\"\\nAccording to our trained Naive Bayes classifier, the probability that your review was negative was {0}% and the probability it was positive was {1}%.\".format(neg, pos))","repo_name":"akhilnair111/100DaysOfCode","sub_path":"Week3/NLP_Challenges_and_Considerations.py","file_name":"NLP_Challenges_and_Considerations.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"8660559304","text":"import csv\nimport sys\nfrom datetime import datetime\nfrom numpy import array,linspace,zeros,eye,concatenate,sum as SUM,linalg\n\n# folder for F\nindir1 = sys.argv[1]\n# folder for b \nindir2 = sys.argv[2]\n# output folder\noutdir = sys.argv[3]\n\ndef list_files(path):\n # returns a list of names (with extension, without full path) of all files \n # in folder path\n files = []\n for name in os.listdir(path):\n if os.path.isfile(os.path.join(path, name)):\n files.append(str(os.path.join(path, name)))\n return files \n\ndef sort_count(kmer, freq, count):\n for i in range(0, len(count)-1):\n for j in range(i+1, len(count)):\n if (count[i] < count[j]):\n temp = count[i]\n count[i] = count[j]\n count[j] = temp\n\n temp = freq[i]\n freq[i] = freq[j]\n freq[j] = temp\n\n temp = kmer[i]\n kmer[i] = kmer[j]\n kmer[j] = temp\n\n\nfiles = list_files(indir1)\n\nnamex = []\nx = []\np = 1\nfor f in files:\n fi = open(f, \"r\")\n filename = str(f).split(\"/\")\n b = indir2 + filename[1]\n fc = open(b, \"r\")\n\n print(p, filename[1])\n F = []\n nameF = []\n for line in fi:\n line = line.strip()\n part = line.split(\",\")\n nameF.append(part[0])\n F.append(int(part[1]))\n\n b = []\n nameb = []\n for lineb in fc:\n lineb = lineb.strip()\n partb = lineb.split(\",\")\n if (partb[0] != \"kmer\"):\n nameb.append(partb[0])\n b.append(int(partb[1]))\n\n p = p + 1\n fi.close()\n fc.close()\n\n outfile = outdir + filename[1]\n out = open(outfile,\"w\")\n for i in range(0, len(F)):\n if (nameF[i] == nameb[i]):\n out.write(\"%s, %d, %d\\n\" %(nameF[i], F[i], b[i]))\n else:\n out.write(\"#,%s,%s\\n\" %(nameF[i], nameb[i]))\n out.close()\n","repo_name":"pdtrang/GSM","sub_path":"solvers/merge_Fc.py","file_name":"merge_Fc.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"36134223207","text":"from pyzbar.pyzbar import decode\nimport numpy as np\nimport cv2\n\nsave_path = '../static/imgs/qrcode_result/'\ncamera_path = '/dev/cameraTop'\n\ncap = cv2.VideoCapture(camera_path)\ncap.set(3, 640)\ncap.set(4, 480)\ncap.set(6, cv2.VideoWriter.fourcc(*'MJPG'))\n\ntry:\n while True:\n # 读取摄像头传回的图片\n ret, frame = cap.read()\n img_gray = None\n if ret:\n img_gray = frame.copy()\n img_gray = cv2.cvtColor(img_gray, cv2.COLOR_BGR2GRAY)\n else:\n print(\"cannot read image\")\n break\n\n cv2.imshow(\"img\", frame)\n cv2.waitKey(1)\n\n result = decode(img_gray)\n result_string_list = []\n if len(result) == 0:\n print(\"qrcode not found\")\n continue\n else:\n # print(len(result))\n # print(result)\n for item in result:\n result_string_list.append(item.data.decode(\"utf-8\"))\n print(\"success read qrcode\")\n string = result_string_list[0]\n print(\"qrcode result: \"+string)\n break \nexcept:\n print(\"error\")\n","repo_name":"WangEden/GongXun","sub_path":"legacy/script/detect_qrcode.py","file_name":"detect_qrcode.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"71026305529","text":"\"\"\"\n Определить, существует ли треугольник.\n\n Программа принимает на ввод 3 стороны треугольника.\n Выводит стороны и текст, существует треугольник или нет.\n\n * у треугольника каждая сторона меньше суммы двух других сторон\n\"\"\"\n\nside_a = int(input('Enter side A: '))\nside_b = int(input('Enter side B: '))\nside_c = int(input('Enter side C: '))\n\nif side_a + side_b > side_c and side_b + side_c > side_a and side_c + side_a > side_b:\n print('Triangle is exists')\nelse:\n print('Triangle is not exists')\n\n\n","repo_name":"FesenkoE/Python-Basic","sub_path":"lesson_2/home_work/triangle.py","file_name":"triangle.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"73627685367","text":"import umap\nimport numpy as np\nfrom sklearn.datasets import load_iris, load_digits\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LinearSegmentedColormap\nimport seaborn as sns\nimport pandas as pd\n\nsns.set(context=\"paper\", style=\"white\")\n\niris = load_iris()\nirisDF = pd.DataFrame(data= np.c_[iris['data'], iris['target']], columns= iris['feature_names'] + ['target'])\nirisDF['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)\n\n# Set random state\nnp.random.seed(2105)\n\nreducer = umap.UMAP(random_state = 2105, transform_seed = 2105)\nembedding = reducer.fit_transform(iris.data)\nembedding.shape\n# embDF = pd.DataFrame(embedding, index=irisDF['species'].values.tolist(), columns=['UM1','UM2'])\nembDF = pd.DataFrame(embedding, columns=['UM1','UM2'])\n\n# Define a nice colour map for gene expression\ncolors2 = plt.cm.Reds(np.linspace(0, 1, 128))\ncolors3 = plt.cm.Greys_r(np.linspace(0.7,0.8,20))\ncolorsComb = np.vstack([colors3, colors2])\nexpColorMap = LinearSegmentedColormap.from_list('ExpressionColorMap', colorsComb)\n\n\n# plt.scatter(embedding[:, 0], embedding[:, 1], c=[sns.color_palette()[x] for x in iris.target])\nplt.scatter(embedding[:, 0], embedding[:, 1], c=expColorMap)\nplt.gca().set_aspect('equal', 'datalim')\nplt.title('UMAP projection of the Iris dataset', fontsize=24);\n\nplt.show()\n\n# Using plotly.go\nimport plotly.graph_objs as go\nfig = go.Figure()\nfvals = irisDF['sepal length (cm)']\n\nmarkerDict = dict(color=fvals,\n colorscale='Viridis', opacity=0.9,\n showscale=True,\n colorbar=dict(thickness=20,\n title=\"Test\",\n titleside='right'))\n\nfig.add_trace(go.Scatter(x=embedding[:, 0], y=embedding[:, 1], mode='markers',\n hoverinfo='text', text='sepal length (cm)', marker = markerDict))\n\nfig.show()\n","repo_name":"gauravj49/dashApps","sub_path":"testApp/apps/test_small_umap.py","file_name":"test_small_umap.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"43997986293","text":"from __future__ import unicode_literals\nimport os\nimport sys\nimport json\nimport struct\n\nclass MyLogger(object):\n def debug(self, msg):\n pass\n\n def warning(self, msg):\n with open(\"err.txt\", \"a\", encoding='utf8') as myfile:\n myfile.write(msg+ \"\\n\")\n\n def error(self, msg):\n global errorvar\n errorvar = 1\n with open(\"err.txt\", \"a\", encoding='utf8') as myfile:\n myfile.write(msg+ \"\\n\")\n err = {'action': 'error', 'error': msg}\n send_message(encode_message(err))\n\nclass DummyLogger(object):\n def debug(self, msg):\n pass\n\n def warning(self, msg):\n pass\n\n def error(self, msg):\n pass\n\n# Send an encoded message to stdout.\ndef send_message(encoded_message):\n sys.stdout.buffer.write(encoded_message['length'])\n sys.stdout.buffer.write(encoded_message['content'])\n sys.stdout.buffer.flush()\n\n# Read a message from stdin and decode it.\ndef get_message():\n raw_length = sys.stdin.buffer.read(4)\n if not raw_length:\n sys.exit(0)\n message_length = struct.unpack('=I', raw_length)[0]\n message = sys.stdin.buffer.read(message_length).decode(\"utf-8\")\n return json.loads(message)\n\n# Encode a message for transmission, given its content.\ndef encode_message(message_content):\n encoded_content = json.dumps(message_content).encode(\"utf-8\")\n encoded_length = struct.pack('=I', len(encoded_content))\n # use struct.pack(\"10s\", bytes), to pack a string of the length of 10 characters\n return {'length': encoded_length, 'content': struct.pack(str(len(encoded_content))+\"s\",encoded_content)}\n \n# Generates youtube-dl options to pass to the downloader\ndef make_command(msg):\n ydl_opts ={\n \"noplaylist\": True,\n \"outtmpl\" : msg[\"outpath\"] + \"/\" + \"%(title)s.%(ext)s\",\n \"postprocessor\": \"FFmpegPostProcessor\",\n \"progress_hooks\": [showProgress],\n \"ignoreerrors\": True,\n 'logger': MyLogger(),\n \"quiet\": True\n }\n if (msg[\"onlysound\"]):\n ydl_opts['format'] = \"bestaudio[ext=m4a]/bestaudio\"\n elif (msg['withoutsound']):\n if (msg['quality'] != \"bestpossible\"):\n ydl_opts['format'] = \"bestvideo[height<=\"+ msg['quality'][:-1] +\"]\"\n else:\n ydl_opts['format'] = \"bestvideo[vcodec=vp9.2]/bestvideo[vcodec=vp9][height>=1400]\\\n /bestvideo[vcodec=vp9][height>=1000][fps>30]/bestvideo[height>720]/bestvideo[fps>30]/best\"\n elif (msg['quality'] != \"bestpossible\"):\n ydl_opts['format'] = \"bestvideo[height<=\"+ msg['quality'][:-1] +\"]+bestaudio/best[height<=\"+ msg['quality'][:-1] + \"]\"\n else:\n ydl_opts['format'] = \"bestvideo[vcodec=vp9.2]+(bestaudio[acodec=opus]/bestaudio)\\\n /bestvideo[vcodec=vp9][height>=1400]+(bestaudio[acodec=opus]/bestaudio)\\\n /bestvideo[vcodec=vp9][height>=1000][fps>30]+(bestaudio[acodec=opus]/bestaudio)\\\n /bestvideo[height>720]+(bestaudio[ext=m4a]/bestaudio)\\\n /bestvideo[fps>30]+(bestaudio[ext=m4a]/bestaudio)\\\n /best\"\n if (msg['subtitles']):\n ydl_opts['writesubtitles'] = True\n ydl_opts['allsubtitles'] = True\n ydl_opts['subtitleformat'] = \"best\"\n if (msg['playlist']):\n ydl_opts['noplaylist'] = False\n return ydl_opts\n\ndef downloadSingle(msg):\n global urlsToSave\n global errorvar\n urlsToDownload = []\n savePlaylist = False \n res = splitUrl(msg['url'])\n if (res != False and msg['playlist'] == True):\n savePlaylist = True\n ydl_opts1 ={\n \"quiet\" : True,\n \"no-warnings\" : True,\n \"ignoreerrors\": True,\n 'logger': DummyLogger()\n }\n # For some dumbass reason ydl.extract still writes errors into out despite quiet, no-warnings and ignoreerrors\n # which is why the dummy logger exists to not mess up communication lane with the extension\n with youtube_dl.YoutubeDL(ydl_opts1) as ydl:\n result = ydl.extract_info(msg['url'], download=False)\n\n for entry in result['entries']:\n if (entry != None):\n urlsToDownload.append('https://www.youtube.com/watch?v='+entry['id'])\n else:\n urlsToDownload.append(msg['url'])\n ydl_opts = make_command(msg)\n urlsToSave = urlsToDownload[:]\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n ydl.download(urlsToDownload)\n ydl.cache.remove()\n if(not errorvar):\n for urlinlist in urlsToSave:\n saveUrl(urlinlist, msg, False)\n if (savePlaylist and not errorvar):\n saveUrl(msg['url'], msg, True)\n\ndef downloadList():\n global errorvar\n db = TinyDB('downloadlist.json')\n if (len(db)):\n for item in db:\n downloadSingle(item)\n if(errorvar):\n db.truncate()\n return\n db.truncate()\n resp = {'action': 'emptylist'}\n send_message(encode_message(resp))\n\ndef addToList(msg):\n db = TinyDB('downloadlist.json')\n dbQuery = Query()\n oldentry = db.get(dbQuery.url == msg['url'])\n\n if(oldentry == None):\n db.insert({'url': msg['url'], 'outpath': msg['outpath'], 'onlysound': msg['onlysound'], 'subtitles': msg['subtitles'], 'quality': msg['quality'], 'withoutsound': msg['withoutsound'], 'playlist': msg['playlist']})\n\n# Will send progress report to the Extension so it can show a progress bar\ndef showProgress(status):\n global progress_seq\n global urlsToSave\n global msg\n if (status[\"status\"] == \"downloading\"):\n progress = int(float(status[\"_percent_str\"][:-1]))\n if (progress not in progress_seq):\n progress_seq.add(progress)\n resp = {'action':'progress', 'status':progress}\n send_message(encode_message(resp))\n elif (status[\"status\"] == \"finished\"):\n progress_seq.clear()\n elif (status[\"status\"] == \"error\"):\n send_message(encode_message(\"error\"))\n\ndef updateChecker(msg):\n currentDateValue = datetime.datetime.now().strftime(\"%Y\"+\"%m\"+\"%d\")\n with open(\"lastupdate.txt\", \"r+\",encoding='utf8') as myfile:\n oldDateValue = int(myfile.readline())\n if (int(currentDateValue) - oldDateValue >0):\n myfile.seek(0)\n myfile.write(currentDateValue)\n myfile.truncate()\n directory = os.getcwd()\n os.system(directory +\"\\\\Scripts\\\\pip.exe install -U -q youtube-dl\")\n checkUrl(msg['url'])\n\ndef splitUrl(url):\n startindex = url.find(\"&list=\")\n if (startindex>0):\n baseUrl= url[:startindex]\n playlistUrl= url[startindex+6:]\n extraParameterIndex = playlistUrl.find(\"&\")\n if (extraParameterIndex>=0):\n finalPlaylistUrl = playlistUrl[:extraParameterIndex]\n return [baseUrl, finalPlaylistUrl]\n else:\n return [baseUrl, playlistUrl]\n else:\n return False\n\ndef checkUrl(url):\n # check in db and list if that url is saved already\n res = splitUrl(url)\n downloadlistdb = TinyDB('downloadlist.json')\n downloadlistdbQuery = Query()\n if (len(downloadlistdb)):\n downloadlistoldentry = downloadlistdb.get(downloadlistdbQuery.url == url)\n if (downloadlistoldentry != None):\n resp = {'action': 'addedtolist'}\n send_message(encode_message(resp))\n return\n if (res):\n\n db = TinyDB('alreadydownloaded.json')\n dbQuery = Query()\n entry = db.get((dbQuery.url == res[1]) & (dbQuery.playlist == True)) \n if (entry):\n resp = {'action': 'alreadydownloadedpl', 'onlysound': entry['onlysound'], 'subtitles': entry['subtitles'], 'quality': entry['quality'], 'withoutsound': entry['withoutsound'], 'date': entry['date'], 'playlist': entry['playlist']}\n send_message(encode_message(resp))\n return\n else:\n db = TinyDB('alreadydownloaded.json')\n dbQuery = Query()\n entry = db.get(dbQuery.url == url)\n if (entry):\n resp = {'action': 'alreadydownloaded', 'onlysound': entry['onlysound'], 'subtitles': entry['subtitles'], 'quality': entry['quality'], 'withoutsound': entry['withoutsound'], 'date': entry['date'], 'playlist': entry['playlist']}\n send_message(encode_message(resp))\n return\n resp = {'action': 'default'}\n send_message(encode_message(resp))\n\ndef saveUrl(url, msg, playlistFlag):\n # check if url is saved already\n res = splitUrl(url)\n realUrl = \"\"\n if (playlistFlag == True):\n realUrl = res[1]\n else:\n realUrl = url\n db = TinyDB('alreadydownloaded.json')\n dbQuery = Query()\n oldentry = db.get(dbQuery.url == realUrl)\n currentDate = datetime.datetime.now().strftime('%y'+'%m'+'%d')\n if (oldentry == None):\n db.insert({'url': realUrl, 'onlysound': msg['onlysound'], 'subtitles': msg['subtitles'], 'quality': msg['quality'], 'withoutsound': msg['withoutsound'], 'date': currentDate, 'playlist': playlistFlag})\n else:\n db.update({'onlysound': msg['onlysound'], 'subtitles': msg['subtitles'], 'quality': msg['quality'], 'withoutsound': msg['withoutsound'], 'date': currentDate}, dbQuery.url == realUrl)\n\n# START \nsys.path.insert(0, os.getcwd() + \"/Lib/site-packages\")\nimport youtube_dl\nfrom tinydb import TinyDB, Query\nimport datetime\nprogress_seq = set(())\nurlsToSave = []\ncurrentDate = datetime.datetime.now().strftime('%y'+'%m'+'%d')\nmsg = \"\"\nerrorvar = 0\nwith open(\"err.txt\", \"w\",encoding='utf8') as myfile:\n myfile.write(\"\")\nwhile True:\n msg = get_message()\n if (msg['action'] == \"checkurl\"):\n updateChecker(msg)\n elif (msg['action'] == \"downloadsingle\"):\n downloadSingle(msg)\n if(errorvar == 0):\n resp = {'action': 'alreadydownloaded', 'onlysound': msg['onlysound'], 'subtitles': msg['subtitles'], 'quality': msg['quality'], 'withoutsound': msg['withoutsound'], 'date': currentDate, 'playlist': msg['playlist']}\n \n if(msg['playlist'] == True):\n resp['action'] = 'alreadydownloadedpl'\n send_message(encode_message(resp))\n elif (msg['action'] == 'downloadlist'):\n downloadList()\n elif (msg['action'] == 'addtolist'):\n addToList(msg)\n resp = {'action': 'addedtolist', 'onlysound': msg['onlysound'], 'subtitles': msg['subtitles'], 'quality': msg['quality'], 'withoutsound': msg['withoutsound'], 'date': currentDate, 'playlist': msg['playlist']}\n send_message(encode_message(resp))","repo_name":"IUCPROD/TokkiDownload","sub_path":"Windows/Firefox/Application/tkdl.py","file_name":"tkdl.py","file_ext":"py","file_size_in_byte":10427,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"22175632986","text":"from typing import Iterator, Optional, cast, Iterable, TYPE_CHECKING\n\nfrom cirq import ops\nfrom cirq.interop.quirk.cells.cell import CellMaker, ExplicitOperationsCell\n\nif TYPE_CHECKING:\n import cirq\n\n\ndef generate_all_measurement_cell_makers() -> Iterator[CellMaker]:\n yield _measurement(\"Measure\")\n yield _measurement(\"ZDetector\")\n yield _measurement(\"YDetector\", basis_change=ops.X**-0.5)\n yield _measurement(\"XDetector\", basis_change=ops.Y**0.5)\n\n\ndef _measurement(identifier: str, basis_change: Optional['cirq.Gate'] = None) -> CellMaker:\n return CellMaker(\n identifier=identifier,\n size=1,\n maker=lambda args: ExplicitOperationsCell(\n [ops.measure(*args.qubits, key=f'row={args.row},col={args.col}')],\n basis_change=cast(\n Iterable['cirq.Operation'], [basis_change.on(*args.qubits)] if basis_change else ()\n ),\n ),\n )\n","repo_name":"quantumlib/Cirq","sub_path":"cirq-core/cirq/interop/quirk/cells/measurement_cells.py","file_name":"measurement_cells.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","stars":3974,"dataset":"github-code","pt":"77"} +{"seq_id":"5557762620","text":"import time\nfrom collections import OrderedDict\n\nimport config as cfg\nimport database as db\nimport numpy as np\nfrom scipy.spatial import distance as dist\nfrom operator import itemgetter\n\nVERTICAL_TOLERANCE = cfg.VERTICAL_TOLERANCE\nDISTANCE_TOLERANCE = cfg.DISTANCE_TOLERANCE\nMAX_DISAPPEARED = cfg.MAX_DISAPPEARED\n\n\nclass centroidtracker():\n def __init__(self, MAX_DISAPPEARED=MAX_DISAPPEARED):\n # initialize the next unique object ID along with two ordered\n # dictionaries used to keep track of mapping a given object\n # ID to its centroid and number of consecutive frames it has\n # been marked as \"disappeared\", respectively\n self.previousPos = OrderedDict()\n self.nextObjectID = 0\n self.objects = OrderedDict()\n self.disappeared = OrderedDict()\n self.continued_movement = OrderedDict()\n self.lastValidMovement = OrderedDict()\n self.length = OrderedDict()\n self.height = OrderedDict()\n self.conf = OrderedDict()\n self.class_id = OrderedDict()\n self.DBList = []\n\n # store the number of maximum consecutive frames a given\n # object is allowed to be marked as \"disappeared\" until we\n # need to deregister the object from tracking\n self.MAX_DISAPPEARED = MAX_DISAPPEARED\n self.previous_timestamp = None\n self.time_between_frames = 1\n\n def register(self, centroid, bbox, conf, class_id):\n # when registering an object we use the next available object\n # ID to store the centroid\n self.objects[self.nextObjectID] = centroid\n self.previousPos[self.nextObjectID] = centroid\n self.disappeared[self.nextObjectID] = 0\n self.continued_movement[self.nextObjectID] = False\n self.lastValidMovement[self.nextObjectID] = None\n self.length[self.nextObjectID] = bbox[0]\n self.height[self.nextObjectID] = bbox[1]\n self.conf[self.nextObjectID] = conf\n self.class_id[self.nextObjectID] = class_id\n self.nextObjectID += 1\n\n def deregister(self, objectID):\n # to deregister an object ID we delete the object ID from\n # both of our respective dictionaries\n del self.objects[objectID]\n del self.previousPos[objectID]\n del self.disappeared[objectID]\n del self.continued_movement[objectID]\n del self.lastValidMovement[objectID]\n del self.length[objectID]\n del self.height[objectID]\n del self.conf[objectID]\n del self.class_id[objectID]\n\n def update(self, rects, confidences, class_ids):\n # create current timestamp in ms\n frame_timestamp = int(round(time.time() * 1000))\n frame_date = time.strftime('%Y%m%d')\n frame_time = time.strftime('%H%M')\n\n if self.previous_timestamp is not None and not cfg.IS_VIDEO_INPUT:\n self.time_between_frames = frame_timestamp - self.previous_timestamp\n\n # create db connection\n conn = db.create_connection(cfg.DATABASE_PATH)\n\n # check to see if the list of input bounding box rectangles\n # is empty\n if len(rects) == 0:\n # loop over any existing tracked objects and mark them\n # as disappeared\n for objectID in list(self.disappeared.keys()):\n self.continued_movement[objectID] = False\n self.disappeared[objectID] += 1\n self.continueMovement(objectID, VERTICAL_TOLERANCE)\n self.previousPos[objectID] = None\n # if we have reached a maximum of consecutive\n # frames where a given object has been marked as\n # missing, deregister it\n # first two ifs check if vehicle is on edge of lane and deregister object immediately if so\n if (self.objects[objectID][1] < cfg.LANE_SEPARATOR and self.objects[objectID][0] < cfg.DEREGISTRATION_ZONE) \\\n or (self.objects[objectID][1] > cfg.LANE_SEPARATOR \\\n and self.objects[objectID][0] > (cfg.FRAME_WIDTH-cfg.LANE_SEPARATOR)) \\\n or (self.disappeared[objectID] > self.MAX_DISAPPEARED):\n self.deregister(objectID)\n\n # add each object to database\n for objectID in self.objects.keys():\n self.addToDatabase(frame_timestamp, frame_date, frame_time, objectID)\n # return early as there are no centroids or tracking info\n # to update\n self.pushToDatabase(conn)\n self.previous_timestamp = frame_timestamp\n return self.objects\n\n # initialize an array of input centroids for the current frame\n inputCentroids = np.zeros((len(rects), 2), dtype=\"int\")\n inputBBoxes = np.zeros((len(rects), 2), dtype=\"int\")\n # loop over the bounding box rectangles\n for (i, (startX, startY, endX, endY)) in enumerate(rects):\n # use the bounding box coordinates to derive the centroid\n cX = int((startX + endX) / 2.0)\n cY = int((startY + endY) / 2.0)\n inputCentroids[i] = (cX, cY)\n inputBBoxes[i] = (endX - startX, endY - startY)\n # if we are currently not tracking any objects take the input\n # centroids and register each of them\n if len(self.objects) == 0:\n for i in range(0, len(inputCentroids)):\n # check if vehicle is not on edge of lane\n if (inputCentroids[i][1] < cfg.LANE_SEPARATOR and inputCentroids[i][0] >= cfg.DEREGISTRATION_ZONE) \\\n or (inputCentroids[i][1] > cfg.LANE_SEPARATOR \\\n and inputCentroids[i][0] <= (cfg.FRAME_WIDTH-cfg.DEREGISTRATION_ZONE)) \\\n or cfg.IGNORE_REGISTRATION_ZONES:\n self.register(inputCentroids[i], inputBBoxes[i], confidences[i], class_ids[i])\n\n # otherwise, are are currently tracking objects so we need to\n # try to match the input centroids to existing object centroids\n else:\n # grab the set of object IDs and corresponding centroids\n objectIDs = list(self.objects.keys())\n objectCentroids = list(self.objects.values())\n # compute the distance between each pair of object centroids and input centroids\n D = dist.cdist(np.array(objectCentroids), inputCentroids)\n # create sorted list of tuples of indexes and value in ascending order\n D_sorted = sorted(np.ndenumerate(D), key=itemgetter(1))\n usedRows = set()\n usedCols = set()\n # loop through pairs of object, inputCentroid, and distance\n for x in D_sorted:\n row = x[0][0]\n col = x[0][1]\n distance = x[1]\n if row in usedRows or col in usedCols:\n continue\n else:\n if (distance < DISTANCE_TOLERANCE) and \\\n (abs(self.objects[objectIDs[row]][1] - inputCentroids[col][1]) < VERTICAL_TOLERANCE):\n objectID = objectIDs[row]\n self.objects[objectID] = inputCentroids[col]\n self.length[objectID] = inputBBoxes[col][0]\n self.height[objectID] = inputBBoxes[col][1]\n self.conf[objectID] = confidences[col]\n self.class_id[objectID] = class_ids[col]\n self.disappeared[objectID] = 0\n self.continued_movement[objectID] = False\n # save the movement between the last two frames (only, if it is \"forward\")\n if self.previousPos[objectID] is not None:\n if (self.objects[objectID][1] < 302 \\\n and (self.objects[objectID][0] - self.previousPos[objectID][0]) < 0) \\\n or (self.objects[objectID][1] > 302 \\\n and (self.objects[objectID][0] - self.previousPos[objectID][0]) > 0):\n self.lastValidMovement[objectID] = (self.objects[objectID] - self.previousPos[\n objectID]) / self.time_between_frames\n self.previousPos[objectID] = self.objects[objectID]\n # indicate that we have examined each of the row and column indexes, respectively\n usedRows.add(row)\n usedCols.add(col)\n # compute both the row and column index we have NOT yet examined\n unusedRows = set(range(0, D.shape[0])).difference(usedRows) # object ids that could not be assigned\n unusedCols = set(range(0, D.shape[1])).difference(usedCols) # input centroids that could not be assigned\n\n # loop over the unused row indexes\n for row in unusedRows:\n # grab the object ID for the corresponding row\n # index and increment the disappeared counter\n objectID = objectIDs[row]\n self.continued_movement[objectID] = False\n self.disappeared[objectID] += 1\n self.continueMovement(objectID, VERTICAL_TOLERANCE)\n self.previousPos[objectID] = None\n # check to see if the number of consecutive\n # frames the object has been marked \"disappeared\"\n # for warrants deregistering the object\n # check if vehicle was on edges of the lanes or has exceeded max_disappeared\n if (objectCentroids[row][1] < cfg.LANE_SEPARATOR and objectCentroids[row][0] < cfg.DEREGISTRATION_ZONE) \\\n or (objectCentroids[row][1] > cfg.LANE_SEPARATOR \\\n and objectCentroids[row][0] > (cfg.FRAME_WIDTH-cfg.DEREGISTRATION_ZONE)) \\\n or (self.disappeared[objectID] > self.MAX_DISAPPEARED):\n self.deregister(objectID)\n\n # usedRows.add(row)\n\n # register each unused inputCentroid as a new object:\n for col in unusedCols:\n if (inputCentroids[col][1] < cfg.LANE_SEPARATOR and inputCentroids[col][0] >= cfg.DEREGISTRATION_ZONE) \\\n or (inputCentroids[col][1] > cfg.LANE_SEPARATOR \\\n and inputCentroids[col][0] <= (cfg.FRAME_WIDTH-cfg.DEREGISTRATION_ZONE)) \\\n or cfg.IGNORE_REGISTRATION_ZONES: \n self.register(inputCentroids[col], inputBBoxes[col], confidences[col], class_ids[col])\n\n # add each object to database\n for objectID in self.objects.keys():\n self.addToDatabase(frame_timestamp, frame_date, frame_time, objectID)\n # return the set of trackable objects \n self.pushToDatabase(conn)\n self.previous_timestamp = frame_timestamp\n return self.objects\n\n def continueMovement(self, objectID, verticalTolerance):\n # check if values for the last valid movement is existing (i.e. the object must have been detected at least once in two consecutive frames)\n if self.lastValidMovement[objectID] is not None:\n self.objects[objectID][0] = self.objects[objectID][0] + \\\n (self.lastValidMovement[objectID][0] * self.time_between_frames)\n self.continued_movement[objectID] = True\n\n def addToDatabase(self, frame_timestamp, frame_date, frame_time, objectID):\n if cfg.SKIP_DB:\n return\n object_for_db = (frame_timestamp,\n frame_date,\n frame_time,\n objectID,\n int(self.objects[objectID][0]),\n int(self.objects[objectID][1]),\n int(self.length[objectID]),\n int(self.height[objectID]),\n int(self.class_id[objectID]),\n self.conf[objectID],\n self.continued_movement[objectID],\n int(round(time.time() * 1000)))\n self.DBList.append(object_for_db)\n \n\n def pushToDatabase(self, conn):\n if len(self.DBList) == 0 or cfg.SKIP_DB:\n return\n\n db.insert_detections(conn, self.DBList)\n self.DBList = []\n\n","repo_name":"martinmeyer489/Vehicle_detection_tracking_YOLO","sub_path":"centroidtracker.py","file_name":"centroidtracker.py","file_ext":"py","file_size_in_byte":12417,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"23117875425","text":"from sklearn import mixture\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.gridspec as gridspec\r\nimport glob\r\nimport numpy as np\r\nimport os\r\nfrom collections import Counter\r\n\r\n\r\n\r\n#Open file to a list\r\ndef open_files(files):\r\n points = 0\r\n for fl in files:\r\n \r\n with open(fl) as f:\r\n \r\n for line in f: \r\n test = line.rstrip(\"\\n\").split(\",\")\r\n data.append(test) \r\n points+=1\r\n \r\n return points\r\n \r\n#Check if string is a number \r\ndef isNumber(s):\r\n try:\r\n int(s)\r\n return True\r\n except ValueError:\r\n return False\r\n\r\n#Remove lines from the data of points \r\ndef remove_lines(): \r\n rawLines = []\r\n for point in data:\r\n for x in point:\r\n if not isNumber(x):\r\n rawLines.append(point)\r\n break\r\n for point in rawLines:\r\n data.remove(point)\r\n \r\n return rawLines \r\n\r\n\r\n\r\n#transform raw list to the list of 4 points\r\n# (the last 2 are beginning and ending of line)\r\ndef rawToLines(raw):\r\n for point in raw:\r\n temp = point[2].split(\"-\")\r\n point.remove(point[2])\r\n for num in temp:\r\n if isNumber(num):\r\n point.append(num)\r\n return raw\r\n\r\ndef reject_outliers(lines):\r\n temp = lines\r\n ind = 0\r\n for index, line in enumerate(lines, start=0):\r\n if line[2]>200 or line[3]>200:\r\n temp = np.delete(temp, index-ind, axis = 0)\r\n \r\n ind+=1\r\n \r\n return temp\r\n\r\n \r\n#plot points after opening to list in 3d\r\ndef plot_initial(lines):\r\n fig = plt.figure(1)\r\n ax = fig.add_subplot(111, projection='3d')\r\n ax.plot(data[:,0], data[:,1], data[:,2], 'o', markerfacecolor='r',\r\n markeredgecolor='k', markersize=1)\r\n for line in lines: \r\n ax.plot([line[0],line[0]], [line[1],line[1]], [line[2],line[3]], c=\"b\")\r\n \r\n ax.set_xlabel('X Label')\r\n ax.set_ylabel('Y Label')\r\n ax.set_zlabel('Z Label')\r\n \r\n plt.title(\"Initial represantation after loading dataset\")\r\n \r\n return\r\n\r\n\r\n#predict clusters using Bayesian Gausian Mixture\r\ndef predictBayesian(data2D): \r\n bgmm = mixture.BayesianGaussianMixture(n_components=7, covariance_type='diag',\r\n weight_concentration_prior = 1e-5, \r\n max_iter=10000, random_state=1).fit(data2D)\r\n\r\n labels=bgmm.predict(data2D)\r\n return bgmm, labels\r\n\r\n\r\n\r\n#plot correct prediction\r\ndef plot_correct (unique_labels):\r\n\r\n colors = [plt.cm.nipy_spectral(each)\r\n for each in np.linspace(0, 1, len(unique_labels))]\r\n \r\n fig = plt.figure(2)\r\n ax = fig.add_subplot(111, projection='3d')\r\n \r\n \r\n for k, col in zip(unique_labels, colors):\r\n \r\n class_member_mask = (labels == k)\r\n \r\n xyz = data[class_member_mask] #& core_samples_mask\r\n plt.plot(xyz[:, 0], xyz[:, 1], xyz[:, 2], 'o', markerfacecolor=tuple(col),\r\n markeredgecolor='k', markersize=4)\r\n\r\n ax.set_xlabel('X Label')\r\n ax.set_ylabel('Y Label')\r\n ax.set_zlabel('Z Label')\r\n plt.title(\"Estimated number of clusters: 6\")\r\n \r\n\r\n\r\n#Subfunction for ploting weights\r\ndef plot_results(ax2, estimator, title):\r\n\r\n ax2.set_title(title)\r\n ax2.get_xaxis().set_tick_params(direction='out')\r\n ax2.yaxis.grid(True, alpha=0.7)\r\n for k, w in enumerate(estimator.weights_):\r\n ax2.bar(k, w, width=0.9, color='#56B4E9', zorder=3,\r\n align='center', edgecolor='black')\r\n ax2.text(k, w + 0.007, \"%.1f%%\" % (w * 100.),\r\n horizontalalignment='center')\r\n \r\n ax2.set_ylim(0., 1.1)\r\n ax2.tick_params(axis='y', which='both', left='off',\r\n right='off', labelleft='off')\r\n ax2.tick_params(axis='x', which='both', top='off')\r\n\r\n \r\n ax2.set_ylabel('Weight of each component')\r\n\r\n#Plot weights to see why the clustering selects 6 clusters\r\ndef plot_weights(weights):\r\n plt.figure(3, figsize=(4.7 * 3, 8)) \r\n \r\n plt.subplots_adjust(bottom=.04, top=0.90, hspace=.05, wspace=.05,\r\n left=.03, right=.99)\r\n \r\n \r\n gs = gridspec.GridSpec(3, len(weights)) \r\n \r\n for k, concentration in enumerate(weights):\r\n bgmm.weight_concentration_prior = concentration\r\n bgmm.fit(data2D)\r\n plot_results(plt.subplot(gs[2,k]), bgmm, \"gamma = \"+str(concentration)) \r\n \r\n \r\n\r\n#transform lines to points with interval 0.01 and get prediction for each point\r\ndef estimate_lines():\r\n pointsLines = [] \r\n lines2D = np.vstack((lines[:,1], lines[:,2], lines[:,3])).T\r\n for line in lines2D:\r\n i = 0.01\r\n \r\n if line[1]<=line[2]:\r\n while i <= line[2]:\r\n pointsLines.append([line[0], line[1]+i])\r\n i+=0.01\r\n if line[1] > line[2]:\r\n while i > line[2]:\r\n pointsLines.append([line[0], line[1]-i])\r\n i+=0.01\r\n pointsLines = np.asarray(pointsLines)\r\n linesLabels = bgmm.predict(pointsLines)\r\n \r\n return pointsLines, linesLabels\r\n\r\n\r\n \r\nos.chdir(\".\\\\Demo\")\r\nfiles = glob.glob(\"*\")\r\n\r\ndata = [] \r\n\r\n#Let's load our data into list\r\npoints = open_files(files)\r\nprint(\"Total number of points is: \"+str(points))\r\nrawLines = remove_lines()\r\n\r\ndata = np.asarray(data)\r\ndata = np.asarray(data, dtype=\"int\") \r\nprint(\"Number of precise points is \"+str(data.shape[0]))\r\nprint(\"Number of unprecise points (lines) is \"+str(len(rawLines)))\r\n\r\n\r\nlines = rawToLines(rawLines)\r\nlines = np.asarray(lines, dtype=\"int\")\r\n\r\n#Let's visualize our data of precise points\r\n#First we need to reject outliers\r\ndraw_lines = reject_outliers(lines)\r\nplot_initial(draw_lines)\r\n#We can visually see 6 clusters as planes in parallel to xy plane\r\n#However we still need to prove there are really 6 clusters\r\n#Let's project dataset to yz plane\r\ndata2D = np.vstack((data[:,1],data[:,2])).T\r\n\r\n#Since we need dynamic number of clusters, \r\n#the distance between clusters isn't very large,\r\n#and clusters aren't uniformly shaped, Bayesian Gausian Mixture is a reasonable choice\r\nbgmm, labels = predictBayesian(data2D)\r\nunique_labels = set(labels)\r\nprint(\"These are unique labels: \"+str(unique_labels))\r\nprint(\"These are possible clusters for precise points: - \"+str(Counter(labels)))\r\n\r\n#Let's see the plotting\r\nplot_correct (unique_labels)\r\n\r\n#Plotting look good, but let's check the weights that are dynamicaly adapted\r\nweights = [1e-8, 1e-6, 1]\r\nplot_weights(weights)\r\n#We see that although we have chosen 7 clusters(components), \r\n#it's dyanamically eliminated by weights being zero or close to zero\r\n\r\n#Let's deal with unprecise points. Now we can predict most probable cluster\r\n# for each point in line (unprecise points)\r\n\r\n#Let's divide lines into points and predict possible clusters for them\r\npointsLines, linesLabels = estimate_lines()\r\nprint(\"These are possible clusters for lines(unprecise points) is\" +str(Counter(linesLabels)))\r\n#It's clear that 2 clusters correspond to initial visual representation of lines\r\n# that intersected or was near two planes\r\n\r\n\r\nplt.show() \r\n","repo_name":"DmytroSytro/Clusterization-of-3D-points-and-lines","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":7299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"42609368008","text":"import re\nimport requests\nimport random\n\n\ndef search_by_keyword(word):\n main_url = \"https://yandex.ru/images/search?text=\"\n category_images = word\n data = requests.get(main_url + category_images)\n pattern = r\"http:[\\w, \\., \\_, \\-, \\/, \\:]*jpg\"\n all_images = re.findall(pattern, data.text)\n random_image = random.choice(all_images)\n return random_image\n","repo_name":"vdenisov-python/telegram-chat-bot","sub_path":"exrta_modules/images.py","file_name":"images.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":"3928042187","text":"# Estrutura de repetição While\n\n'''\n# Exemplo para compreensão\nenquanto não chegar:\n passo\npega\n\n# Exemplo em Python\nwhile not maça:\n passo\npega\n\n# Exemplo para compreensão 2\n\nenquanto não maça:\n if chao:\n passo\n elif buraco:\n pula\n elif moeda:\n pega\npega\n'''\n\n# Ex. 2 Python\n'''\nwhile not maça:\n if chao == True:\n passo\n elif buraco == True:\n pule\n elif moeda == True:\n pega\npega \n'''\n# Ex. 3 Python\n# Utilizando for\nfor c in range(1, 10):\n print(c)\nprint('FIM')\n\n# Ex. 3 Python\n# Utilizando while\nc = 1\nwhile c < 10:\n print(c)\n c = c + 1\nprint('Fim')\n\n# Ex. 4 Python\n# Utilizando for\nfor c in range(1, 5):\n n = int(input('Digite um valor: '))\nprint('Fim')\n\n# Ex. 4 Python\n# Utilizando while\nn = 1\nwhile n != 0:\n n = int(input('Digite um valor'))\nprint('Fim')\n\n# Ex. 5 Python\n# Utilizando while\nr = 's'\nwhile r == 's':\n n = int(input('Digite um valor'))\n r = str(input('Quer continuar? [S/N] ')).upper()\nprint('Fim') \n\n# A diferença do for e do while é justamente o limite da iteração. Enquanto o for faz a repetição com base\n# em um limite, o while faz a repetição mesmo quando não sabemos o limite da iteração\n\n# Ex. 5 Python\n# Utilizando while\n\nn = 1 \npar = impar = 0\nwhile n != 0:\n n = int(input('Digite um valor'))\n if n != 0:\n if n % 2 == 0:\n par += 1\n else:\n impar += 1\nprint('Você digitou {} números pares e {} números ímpares!'.format(par, impar))","repo_name":"Lima-oncode/Python_Practice_120Hours","sub_path":"aula14.py","file_name":"aula14.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"8728699650","text":"\"\"\"Implements an API for iris recognition\"\"\"\nimport numpy as np\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\nimport joblib\n\napp = FastAPI()\niris_classes = [\"Setosa\", \"Versicolour\", \"Virginica\"]\n\nmodel = joblib.load(\"iris_classifier.joblib\")\n\n\nclass IrisModelInput(BaseModel):\n \"\"\"Input data type for prediction\"\"\"\n\n sepal_length: float\n sepal_width: float\n petal_length: float\n petal_width: float\n\n\n@app.get(\"/\")\ndef read_root() -> dict:\n \"\"\"Default endpoint\"\"\"\n return {\"Prediction Endpoint\": \"/predict\"}\n\n\n@app.post(\"/predict\")\nasync def predict(obj_input: IrisModelInput) -> dict:\n \"\"\"Predict the type of iris flower based on its petal and sepal measurements\n\n :param obj_input: object with the measurements of sepal and petal\n :type obj_input: IrisModelInput\n :returns: iris type prediction\n :rtype: dict\n \"\"\"\n\n data = np.array(\n [\n [\n obj_input.sepal_length,\n obj_input.sepal_width,\n obj_input.petal_length,\n obj_input.petal_width,\n ]\n ]\n )\n val = model.predict(data)[0]\n\n return {\"Iris type\": iris_classes[val]}\n","repo_name":"juanse77/iris.k8s","sub_path":"iris/iris_pred.py","file_name":"iris_pred.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"26160712031","text":"import time\nfrom influxdb import InfluxDBClient\nimport commands\n\ndb_host = '10.0.0.1'\nport = 8086\nuser = 'influx'\npassword = 'password'\ndbname = 'active-vpn-connections'\nclient = InfluxDBClient(db_host, port, user, password, dbname)\n\n# Reads the output from the Perl script that runs when you call \"show vnp remote access\"\n# Pasring CLI output wasn't my first choice, but looking at the Perl there didn't seem to be an easy way to get all this data in one place\n\ndef save_influx(line):\n json_body = [\n {\n \"measurement\": \"connection\",\n \"tags\": {\n \"host\": \"router\",\n },\n \"fields\": line\n }\n ]\n print(\"Write points: {0}\".format(json_body))\n client.write_points(json_body)\n\n\nwhile True:\n connections = []\n\n client.drop_database(\"active-vpn-connections\")\n client.create_database(\"active-vpn-connections\")\n output = commands.getstatusoutput('/opt/vyatta/sbin/vyatta-show-ravpn.pl')[1]\n output = output.split('\\n')\n if len(output[0])>1: # If only one line is returned, assume no active connections\n del output [0:4] # Remove header rows\n # Assumes that each filed is a fixed width.\n # Looking at the Perl, I believe this is a safe assumption\n for line in output:\n connection = {}\n connection['user'] = line[0:16].replace(\" \",\"\")\n connection['type'] = line[16:22].replace(\" \",\"\")\n connection['interface'] = line[22:32].replace(\" \",\"\")\n connection['ip_address'] = line[32:50].replace(\" \",\"\")\n connection['tx_byte'] = line[50:58].replace(\" \",\"\")\n connection['rx_byte'] = line[58:65].replace(\" \",\"\")\n connection['connection_time'] = line[65:75].replace(\" \",\"\")\n\n connections.append(connection)\n for connection in connections:\n save_influx(connection)\n time.sleep(15)\n","repo_name":"redskyguy/vyos-grafana-scripts","sub_path":"active_vpn.py","file_name":"active_vpn.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"77"} +{"seq_id":"23673511065","text":"import os\nimport numpy as np\nimport cv2\nfrom cv2 import aruco\n\ncv2.namedWindow('Image', cv2.WINDOW_NORMAL)\ncv2.resizeWindow('Image', 1920, 1080)\n\n# load the calibration parameters\ncv_file = cv2.FileStorage(\"calibration.yaml\", cv2.FILE_STORAGE_READ)\nmtx = cv_file.getNode(\"camera_matrix\").mat()\ndist = cv_file.getNode(\"dist_coeff\").mat()\ncv_file.release()\n\naruco_dict = aruco.Dictionary_get(aruco.DICT_ARUCO_ORIGINAL)\n\ncap = cv2.VideoCapture(0)\ncap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)\ncap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)\n\nwhile cap.isOpened():\n ret, frame = cap.read()\n #frame = cv2.undistort(frame, mtx, dist, None, None)\n # frame = cv2.undistort(frame, mtx, dist)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n aruco_dict = aruco.Dictionary_get(aruco.DICT_ARUCO_ORIGINAL)\n parameters = aruco.DetectorParameters_create()\n\n corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict, parameters=parameters)\n\n font = cv2.FONT_HERSHEY_SIMPLEX # font for displaying text (below)\n\n if np.all(ids != None):\n rvec, tvec, _ = aruco.estimatePoseSingleMarkers(corners[0], 20, mtx, dist)\n\n aruco.drawAxis(frame, mtx, dist, rvec[0], tvec[0], 0.025)\n aruco.drawDetectedMarkers(frame, corners)\n pose_r, _ = cv2.Rodrigues(rvec)\n pose = np.eye(4)\n pose[0:3, 0:3] = pose_r\n pose[0:3, 3] = tvec[0]\n print(pose)\n\n ###### DRAW ID #####\n cv2.putText(frame, \"Id: \" + str(ids), (0, 64), font, 1, (0, 255, 0), 2, cv2.LINE_AA)\n\n # Display the resulting frame\n cv2.imshow('Image', frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# When everything done, release the capture\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"persmed/cas-assignment","sub_path":"exercises/camera_calibration/detect_aruco_marker.py","file_name":"detect_aruco_marker.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"45677143534","text":"import datetime\nfrom django.views.generic import DetailView, ListView, TemplateView\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.http import Http404\nfrom rest_framework import generics, viewsets\n\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\nfrom garden.models import ProjectConnection, SensorReading\nfrom garden.serializers import SensorReadingSerializer\nfrom blog.models import Post, Project\n\nfrom django.db.models import Avg, F, RowRange, Window\n\n\n\n\n\nclass SensorReadingViewSet(viewsets.ModelViewSet): \n serializer_class = SensorReadingSerializer\n\n def get_queryset(self):\n queryset = SensorReading.objects.all().order_by('timestamp')\n\n sensor = self.request.query_params.get('sensor', None)\n if sensor is not None:\n queryset = queryset.filter(sensorID=sensor)\n latest = self.request.query_params.get('latest', None)\n if latest is not None:\n most_recent = queryset.last().timestamp\n # print(most_recent)\n queryset = queryset.exclude(timestamp__lt=most_recent)\n hours = self.request.query_params.get('hours', None)\n if hours is not None:\n try:\n last_reading = queryset.last().timestamp\n earliest_reading = int(last_reading - (float(hours) * 3600))\n queryset = queryset.exclude(timestamp__lt=earliest_reading)\n print(last_reading)\n except Exception as e:\n print(\"[garden.views] we failed in SensorReadingViewSet\")\n print(e)\n pass\n return queryset\n\nclass SensorReadingList(APIView):\n \"\"\"\n List all SensorReadings, or create a new SensorReading.\n \"\"\"\n def get(self, request, format=None):\n sensor_readings = SensorReading.objects.all().order_by('timestamp')\n # print(sensor_readings.count())\n\n items = SensorReading.objects.all().order_by('timestamp')[::2]\n # print(items)\n serializer = SensorReadingSerializer(sensor_readings, many=True)\n return Response(serializer.data)\n\n def post(self, request, format=None):\n serializer = SensorReadingSerializer(data=request.data, many=True)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\nclass SensorReadingDetail(generics.RetrieveUpdateDestroyAPIView):\n queryset = SensorReading.objects.all()\n serializer_class = SensorReadingSerializer\n\nclass Plots(TemplateView):\n template_name='garden/plots.html'\n\nclass Garden(TemplateView):\n template_name='garden/garden.html'\n\n def get_context_data(self, **kwargs):\n # Call the base implementation first to get a context\n context = super().get_context_data(**kwargs)\n # Get last sensor reading\n last_reading = SensorReading.objects.all().last()\n last_reading_list = {\n \"environment\":{\n \"name\": \"Environment\",\n \"light\":last_reading.light,\n \"temp\":round(last_reading.temp1 * 1.8 + 32, 1),\n \"rh\":round(last_reading.rh1, 1),\n \"timestamp\":datetime.datetime.fromtimestamp(last_reading.timestamp)\n },\n \"greenhouse\":{\n \"name\": \"Greenhouse\",\n \"light\":last_reading.light,\n \"temp\":round(last_reading.temp2 * 1.8 + 32, 1),\n \"rh\":round(last_reading.rh2, 1),\n \"timestamp\":datetime.datetime.fromtimestamp(last_reading.timestamp)\n }\n }\n context['current_conditions'] = last_reading_list\n return context\n\nclass PostListView(ListView):\n template_name = 'garden/post_list.html'\n context_object_name = 'posts'\n queryset = Post.objects.exclude(published_date__isnull=True).order_by('-published_date')\n model = Post\n # print(queryset)\n\nclass PostDetailView(DetailView):\n model = Post\n template_name = 'garden/post_detail_view.html'\n context_object_name = 'post'\n\ndef AboutView(request):\n arduino_pk = ProjectConnection.objects.all().first()\n if arduino_pk:\n project = get_object_or_404(Project, pk=arduino_pk.project.pk) \n posts = project.post.exclude(published_date__isnull=True).order_by('-published_date')\n else:\n raise Http404()\n # print(posts)\n return render(request, 'garden/project_detail.html', {'project':project, 'posts':posts})\n# class AboutView(DetailView):\n# arduino_pk = ProjectConnection.objects.all().first()\n# print(arduino_pk)\n# template_name = 'blog/project_detail.html'\n\n\n# project = get_object_or_404(Project, pk=pk) \n# posts = project.post.exclude(published_date__isnull=True).order_by('-published_date')\n# print(posts)\n# return render(request, 'blog/project_detail.html', {'project':project, 'posts':posts})","repo_name":"tyday/port_site","sub_path":"mysite/garden/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"34576344684","text":"import geopandas as gpd\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Load Nairobi's shapefile (you may need to download this data)\nnairobi_shapefile = \"path/to/nairobi_shapefile.shp\"\nnairobi_map = gpd.read_file(nairobi_shapefile)\n\n# Load traffic data (sample data for illustration purposes)\ntraffic_data = pd.read_csv(\"sample_traffic_data.csv\")\n\n# Merge the traffic data with the Nairobi map based on location information\nnairobi_traffic = nairobi_map.merge(traffic_data, left_on=\"neighborhood\", right_on=\"neighborhood\", how=\"left\")\n\n# Visualize traffic congestion on the map\nfig, ax = plt.subplots(1, 1, figsize=(12, 8))\nnairobi_traffic.plot(column=\"congestion_level\", cmap=\"coolwarm\", linewidth=0.8, ax=ax, edgecolor=\"0.8\", legend=True)\nax.set_title(\"Traffic Congestion in Nairobi Neighborhoods\")\nplt.axis(\"off\")\n\n# Save or display the map\nplt.savefig(\"traffic_congestion_map.png\", dpi=300, bbox_inches=\"tight\")\nplt.show()\n","repo_name":"blacksnowmartin/Nairobi-Traffic-Insight","sub_path":"datanbo.py","file_name":"datanbo.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"1989757308","text":"\"\"\"\n By default, firmware does not send any stream from a MAVLink channel (except sync messages).\n In order to get default message streams, they should be requested from the autopilot.\n REQUEST_DATA_STREAM message is used to request default streams from the vehicle.\n If you want to get all available default message streams, req_stream_id=0.\n Message rate (frequency) can be configured with req_message_rate.\n\n https://mavlink.io/en/messages/common.html#REQUEST_DATA_STREAM\n\"\"\"\n\nimport time\nimport pymavlink.mavutil as utility\nimport pymavlink.dialects.v20.all as dialect\n\n# connect to vehicle\nvehicle = utility.mavlink_connection(device=\"tcp:127.0.0.1:5760\")\n\n# wait for a heartbeat\nvehicle.wait_heartbeat()\n\n# inform user\nprint(\"Connected to system:\", vehicle.target_system, \", component:\", vehicle.target_component)\n\n# create request data stream message\nmessage = dialect.MAVLink_request_data_stream_message(target_system=vehicle.target_system,\n target_component=vehicle.target_component,\n req_stream_id=0,\n req_message_rate=4,\n start_stop=1)\n\n# send request data stream message to the vehicle\nvehicle.mav.send(message)\n\n# infinite loop to catch all messages from simulated vehicle\nwhile True:\n\n # catch all messages\n message = vehicle.recv_match(blocking=True)\n\n # convert this messages to dictionary\n message = message.to_dict()\n\n # debug the message\n print(message)\n","repo_name":"mustafa-gokce/ardupilot-software-development","sub_path":"pymavlink/request-defaults.py","file_name":"request-defaults.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"77"} +{"seq_id":"13788748406","text":"\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 20 14:23:40 2017\n\n@author: JTay\n\"\"\"\nimport warnings \n\nimport numpy as np\nimport sklearn.model_selection as ms\nimport pandas as pd\nfrom helpers import basicResults,makeTimingCurve,iterationLC\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.base import BaseEstimator, ClassifierMixin\nfrom sklearn.metrics import euclidean_distances\nfrom sklearn.utils.validation import check_X_y, check_array, check_is_fitted\nfrom sklearn.utils.multiclass import unique_labels\nfrom sklearn.metrics.pairwise import rbf_kernel\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.exceptions import DataConversionWarning\n\nclass primalSVM_RBF(BaseEstimator, ClassifierMixin):\n '''http://scikit-learn.org/stable/developers/wineributing.html'''\n \n def __init__(self, alpha=1e-9,gamma_frac=0.1,n_iter=2000):\n self.alpha = alpha\n self.gamma_frac = gamma_frac\n self.n_iter = n_iter\n \n def fit(self, X, y):\n # Check that X and y have correct shape\n X, y = check_X_y(X, y)\n \n # Get the kernel matrix\n dist = euclidean_distances(X,squared=True)\n median = np.median(dist) \n del dist\n gamma = median\n gamma *= self.gamma_frac\n self.gamma = 1/gamma\n kernels = rbf_kernel(X,None,self.gamma )\n \n self.X_ = X\n self.classes_ = unique_labels(y)\n self.kernels_ = kernels\n self.y_ = y\n self.clf = SGDClassifier(loss='hinge',penalty='l2',alpha=self.alpha,\n l1_ratio=0,fit_intercept=True,verbose=False,\n average=False,learning_rate='optimal',\n class_weight='balanced',n_iter=self.n_iter,\n random_state=55) \n self.clf.fit(self.kernels_,self.y_)\n \n # Return the classifier\n return self\n\n def predict(self, X):\n # Check is fit had been called\n check_is_fitted(self, ['X_', 'y_','clf','kernels_'])\n # Input validation\n X = check_array(X)\n new_kernels = rbf_kernel(X,self.X_,self.gamma )\n pred = self.clf.predict(new_kernels)\n return pred\n \nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\nwarnings.filterwarnings(\"ignore\", category=FutureWarning)\nwarnings.filterwarnings(\"ignore\", category=DataConversionWarning)\n\n# Load Data \n#adult = pd.read_hdf('./data/datasets.hdf','adult') \n#adultX = adult.drop('TARGET',1).copy().values\n#adultY = adult['TARGET'].copy().values\n\nwine = pd.read_hdf('./data/datasets.hdf','wine') \nwineX = wine.drop('quality',1).copy().values\nwineY = wine['quality'].copy().values\n\n#adult_trgX, adult_tstX, adult_trgY, adult_tstY = ms.train_test_split(adultX, adultY, test_size=0.3, random_state=0,stratify=adultY) \nwine_trgX, wine_tstX, wine_trgY, wine_tstY = ms.train_test_split(wineX, wineY, test_size=0.3, random_state=0,stratify=wineY) \n\n#N_adult = adult_trgX.shape[0]\nN_wine = wine_trgX.shape[0]\n\nalphas = [10**-x for x in np.arange(1,9.01,1/2)]\n\n\n##Linear SVM\npipeM = Pipeline([('Scale',StandardScaler()),\n ('Cull1',SelectFromModel(RandomForestClassifier(random_state=1),threshold='median')),\n ('Cull2',SelectFromModel(RandomForestClassifier(random_state=2),threshold='median')),\n ('Cull3',SelectFromModel(RandomForestClassifier(random_state=3),threshold='median')),\n ('Cull4',SelectFromModel(RandomForestClassifier(random_state=4),threshold='median')),\n ('SVM',SGDClassifier(loss='hinge',l1_ratio=0,penalty='l2',class_weight='balanced',random_state=55))])\n#pipeA = Pipeline([('Scale',StandardScaler()), \n# ('SVM',SGDClassifier(loss='hinge',l1_ratio=0,penalty='l2',class_weight='balanced',random_state=55))])\n#\n#params_adult = {'SVM__alpha':alphas,'SVM__n_iter':[int((1e6/N_adult)/.8)+1]}\nparams_wine = {'SVM__alpha':alphas,'SVM__n_iter':[int((1e6/N_wine)/.8)+1]}\n# \nwine_clf = basicResults(pipeM,wine_trgX,wine_trgY,wine_tstX,wine_tstY,params_wine,'SVM_Lin','wine') \n#adult_clf = basicResults(pipeA,adult_trgX,adult_trgY,adult_tstX,adult_tstY,params_adult,'SVM_Lin','adult') \n#\n#wine_final_params = {'SVM__alpha': 0.031622776601683791, 'SVM__n_iter': 687.25}\nwine_final_params = wine_clf.best_params_\nwine_OF_params = {'SVM__n_iter': 1303, 'SVM__alpha': 1e-16}\n#adult_final_params ={'SVM__alpha': 0.001, 'SVM__n_iter': 54.75}\n#adult_final_params =adult_clf.best_params_\n#adult_OF_params ={'SVM__n_iter': 55, 'SVM__alpha': 1e-16}\n#\n#\npipeM.set_params(**wine_final_params) \nmakeTimingCurve(wineX,wineY,pipeM,'SVM_Lin','wine')\n#pipeA.set_params(**adult_final_params)\n#makeTimingCurve(adultX,adultY,pipeA,'SVM_Lin','adult')\n#\npipeM.set_params(**wine_final_params)\niterationLC(pipeM,wine_trgX,wine_trgY,wine_tstX,wine_tstY,{'SVM__n_iter':[2**x for x in range(12)]},'SVM_Lin','wine') \n#pipeA.set_params(**adult_final_params)\n#iterationLC(pipeA,adult_trgX,adult_trgY,adult_tstX,adult_tstY,{'SVM__n_iter':np.arange(1,75,3)},'SVM_Lin','adult') \n#\n#pipeA.set_params(**adult_OF_params)\n#iterationLC(pipeA,adult_trgX,adult_trgY,adult_tstX,adult_tstY,{'SVM__n_iter':np.arange(1,200,5)},'SVM_LinOF','adult') \npipeM.set_params(**wine_OF_params)\niterationLC(pipeM,wine_trgX,wine_trgY,wine_tstX,wine_tstY,{'SVM__n_iter':np.arange(100,2600,100)},'SVM_LinOF','wine') \n\n\n\n\n\n\n#RBF SVM\ngamma_fracsA = np.arange(0.2,2.1,0.2)\ngamma_fracsM = np.arange(0.05,1.01,0.1)\n\n#\npipeM = Pipeline([('Scale',StandardScaler()),\n ('SVM',primalSVM_RBF())])\n\n#pipeA = Pipeline([('Scale',StandardScaler()),\n# ('SVM',primalSVM_RBF())])\n\n\n#params_adult = {'SVM__alpha':alphas,'SVM__n_iter':[int((1e6/N_adult)/.8)+1],'SVM__gamma_frac':gamma_fracsA}\nparams_wine = {'SVM__alpha':alphas,'SVM__n_iter':[int((1e6/N_wine)/.8)+1],'SVM__gamma_frac':gamma_fracsM}\n# \nwine_clf = basicResults(pipeM,wine_trgX,wine_trgY,wine_tstX,wine_tstY,params_wine,'SVM_RBF','wine') \n#adult_clf = basicResults(pipeA,adult_trgX,adult_trgY,adult_tstX,adult_tstY,params_adult,'SVM_RBF','adult') \n\n\n\nwine_final_params = wine_clf.best_params_\nwine_OF_params = wine_final_params.copy()\nwine_OF_params['SVM__alpha'] = 1e-16\n#adult_final_params =adult_clf.best_params_\n#adult_OF_params = adult_final_params.copy()\n#adult_OF_params['SVM__alpha'] = 1e-16\n\npipeM.set_params(**wine_final_params) \nmakeTimingCurve(wineX,wineY,pipeM,'SVM_RBF','wine')\n#pipeA.set_params(**adult_final_params)\n#makeTimingCurve(adultX,adultY,pipeM,'SVM_RBF','adult')\n\n\npipeM.set_params(**wine_final_params)\niterationLC(pipeM,wine_trgX,wine_trgY,wine_tstX,wine_tstY,{'SVM__n_iter':[2**x for x in range(12)]},'SVM_RBF','wine') \n#pipeA.set_params(**adult_final_params)\n#iterationLC(pipeA,adult_trgX,adult_trgY,adult_tstX,adult_tstY,{'SVM__n_iter':np.arange(1,75,3)},'SVM_RBF','adult') \n\n#pipeA.set_params(**adult_OF_params)\n#iterationLC(pipeA,adult_trgX,adult_trgY,adult_tstX,adult_tstY,{'SVM__n_iter':np.arange(1,75,3)},'SVM_RBF_OF','adult') \npipeM.set_params(**wine_OF_params)\niterationLC(pipeM,wine_trgX,wine_trgY,wine_tstX,wine_tstY,{'SVM__n_iter':np.arange(100,2600,100)},'SVM_RBF_OF','wine') \n","repo_name":"mbrine555/gatech_ML","sub_path":"Assignment 1/SVM.py","file_name":"SVM.py","file_ext":"py","file_size_in_byte":7653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"9336018255","text":"from __future__ import annotations\n\nimport json\nimport pathlib\nfrom typing import Any\n\nimport h5py\nimport numpy as np\nimport pytest\nimport spacy\n\nfrom bluesearch.utils import (\n H5,\n JSONL,\n Timer,\n check_entity_type_consistency,\n find_files,\n get_available_spacy_models,\n load_spacy_model,\n)\n\n\nclass TestFindFiles:\n def test_filtering_recursive(tmp_path):\n input_path = pathlib.Path(\"tests/data/cord19_v35/document_parses/pdf_json/\")\n inputs = find_files(input_path, recursive=True)\n filenames = sorted(x.name for x in inputs)\n expected = [\n \"16e82ce0e0c8a1b36497afc0d4392b4fe21eb174.json\",\n \"5f267fa1ef3a65e239aa974329e935a4d93dafd2.json\",\n ]\n assert filenames == expected\n\n def test_filtering(tmp_path):\n input_path = pathlib.Path(\"tests/data/cord19_v35/\")\n inputs = find_files(\n input_path, recursive=True, match_filename=r\"[a-z0-9]+\\.json\"\n )\n filenames = sorted(x.name for x in inputs)\n expected = [\n \"16e82ce0e0c8a1b36497afc0d4392b4fe21eb174.json\",\n \"5f267fa1ef3a65e239aa974329e935a4d93dafd2.json\",\n ]\n assert filenames == expected\n\n def test_filtering_empty(tmp_path):\n message = \"Value for argument 'match-filename' should not be empty!\"\n input_path = pathlib.Path(\"tests/data/cord19_v35/\")\n with pytest.raises(ValueError, match=message):\n _ = find_files(input_path, recursive=True, match_filename=\"\")\n\n\nclass TestTimer:\n def test_errors(self):\n timer = Timer()\n\n with pytest.raises(ValueError):\n timer.__enter__()\n\n with pytest.raises(ValueError):\n with timer(\"a\"):\n pass\n with timer(\"a\"):\n pass\n\n with pytest.raises(ValueError):\n with timer(\"overall\"):\n pass\n\n with pytest.raises(ValueError):\n with timer(\"b\"):\n raise ValueError\n\n assert \"b\" not in timer.stats\n\n def test_basic(self):\n timer = Timer()\n\n assert len(timer.stats) == 1\n\n with timer(\"a\"):\n pass\n\n assert \"a\" in timer.stats\n assert timer[\"a\"] == timer.stats[\"a\"]\n\n with timer(\"b\"):\n pass\n\n assert len(timer.stats) == 3\n\n def test_verbose(self, capsys):\n timer_v = Timer(verbose=True)\n timer_n = Timer(verbose=False)\n\n # 1\n timer_v(\"b\", message=\"additional\")\n\n captured = capsys.readouterr()\n assert captured.out == \"additional\\n\"\n\n # 2\n with timer_n(\"a\"):\n pass\n\n captured = capsys.readouterr()\n assert not captured.out\n\n # 3\n with timer_v(\"a\"):\n pass\n\n captured = capsys.readouterr()\n assert captured.out\n\n\nclass TestH5:\n @pytest.mark.parametrize(\"fillvalue\", [1.1, np.nan])\n @pytest.mark.parametrize(\"indices\", [[0, 1], [0], [3, 2, 1]])\n def test_clear(self, tmpdir, fillvalue, indices):\n h5_path = pathlib.Path(str(tmpdir)) / \"to_be_created.h5\"\n\n shape = (4, 2)\n data = np.random.random(shape)\n indices = np.array(indices)\n\n with h5py.File(h5_path, \"w\") as f:\n dset = f.create_dataset(\"a\", shape=shape, fillvalue=fillvalue)\n\n dset[:, :] = data\n\n # Truth\n data[indices] = fillvalue\n\n # Run\n H5.clear(h5_path, \"a\", indices)\n\n with h5py.File(h5_path, \"r\") as ff:\n res = ff[\"a\"][:]\n\n assert np.allclose(res, data, equal_nan=True)\n\n @pytest.mark.parametrize(\"batch_size\", [1, 3, 10])\n @pytest.mark.parametrize(\"delete_inputs\", [True, False])\n def test_concatenate(self, tmpdir, batch_size, delete_inputs):\n tmpdir = pathlib.Path(str(tmpdir))\n\n temp_path_1 = tmpdir / \"temp_1.h5\"\n temp_path_2 = tmpdir / \"temp_2.h5\"\n\n final_path = tmpdir / \"final_1.h5\"\n\n # Create temporary files\n indices_1 = [2, 5, 7]\n indices_2 = [1, 3, 8, 11]\n dim = 4\n shape_1 = (len(indices_1), dim)\n shape_2 = (len(indices_2), dim)\n\n array_1 = np.random.random(shape_1)\n array_2 = np.random.random(shape_2)\n dataset_name = \"some_dataset\"\n dataset_name_indices = f\"{dataset_name}_indices\"\n\n with h5py.File(temp_path_1, \"w\") as f_1:\n f_1.create_dataset(\n dataset_name,\n shape=shape_1,\n )\n f_1.create_dataset(\n dataset_name_indices,\n dtype=\"int32\",\n shape=(len(indices_1), 1),\n )\n f_1[dataset_name][:] = array_1\n f_1[dataset_name_indices][:, 0] = np.array(indices_1, dtype=np.int32)\n\n with h5py.File(temp_path_2, \"w\") as f_2:\n f_2.create_dataset(\n dataset_name,\n shape=shape_2,\n )\n f_2.create_dataset(\n dataset_name_indices,\n dtype=\"int32\",\n shape=(len(indices_2), 1),\n )\n f_2[dataset_name][:] = array_2\n f_2[dataset_name_indices][:, 0] = np.array(indices_2, dtype=np.int32)\n\n # No paths\n with pytest.raises(ValueError):\n H5.concatenate(final_path, dataset_name, [])\n\n # Overlapping indices\n with pytest.raises(ValueError):\n H5.concatenate(final_path, dataset_name, [temp_path_1, temp_path_1])\n\n H5.concatenate(\n final_path,\n dataset_name,\n [temp_path_1, temp_path_2],\n delete_inputs=delete_inputs,\n batch_size=batch_size,\n )\n\n if delete_inputs:\n assert not temp_path_1.exists()\n assert not temp_path_2.exists()\n else:\n assert temp_path_1.exists()\n assert temp_path_2.exists()\n\n assert final_path.exists()\n\n with h5py.File(final_path, \"r\") as f:\n data = f[dataset_name][:]\n\n assert data.shape == (max(indices_1 + indices_2) + 1, dim)\n np.testing.assert_array_almost_equal(data[indices_1], array_1)\n np.testing.assert_array_almost_equal(data[indices_2], array_2)\n\n assert np.all(\n H5.find_populated_rows(final_path, dataset_name)\n == np.array(sorted(indices_1 + indices_2))\n )\n\n def test_create(self, tmpdir):\n h5_path = pathlib.Path(str(tmpdir)) / \"to_be_created.h5\"\n\n # New h5 file and new dataset\n H5.create(h5_path, \"a\", (20, 10), dtype=\"f2\")\n\n with h5py.File(h5_path, \"r\") as f:\n assert \"a\" in f.keys()\n assert f[\"a\"].shape == (20, 10)\n assert f[\"a\"].dtype == \"f2\"\n\n # Old h5 file and new dataset\n H5.create(h5_path, \"b\", (40, 2), dtype=\"f4\")\n\n with h5py.File(h5_path, \"r\") as f:\n assert \"b\" in f.keys()\n assert f[\"b\"].shape == (40, 2)\n assert f[\"b\"].dtype == \"f4\"\n\n # Check errors\n with pytest.raises(ValueError):\n H5.create(h5_path, \"a\", (20, 10))\n\n @pytest.mark.parametrize(\"verbose\", [True, False])\n @pytest.mark.parametrize(\"batch_size\", [1, 2, 5])\n @pytest.mark.parametrize(\"model\", [\"SBERT\"])\n def test_find_unpopulated_rows(\n self, embeddings_h5_path, model, verbose, batch_size\n ):\n unpop_rows_computed = H5.find_unpopulated_rows(\n embeddings_h5_path, model, verbose=verbose, batch_size=batch_size\n )\n\n with h5py.File(embeddings_h5_path, \"r\") as f:\n dset_np = f[model][:]\n unpop_rows_true = np.where(np.isnan(dset_np.sum(axis=1)))[0]\n\n assert np.all(unpop_rows_computed == unpop_rows_true)\n\n @pytest.mark.parametrize(\"verbose\", [True, False])\n @pytest.mark.parametrize(\"batch_size\", [1, 2, 5])\n @pytest.mark.parametrize(\"model\", [\"SBERT\"])\n def test_find_populated_rows(self, embeddings_h5_path, model, verbose, batch_size):\n unpop_rows_computed = H5.find_populated_rows(\n embeddings_h5_path, model, verbose=verbose, batch_size=batch_size\n )\n\n with h5py.File(embeddings_h5_path, \"r\") as f:\n dset_np = f[model][:]\n unpop_rows_true = np.where(~np.isnan(dset_np.sum(axis=1)))[0]\n\n assert np.all(unpop_rows_computed == unpop_rows_true)\n\n def test_get_shape(self, tmpdir):\n h5_path = pathlib.Path(str(tmpdir)) / \"to_be_created.h5\"\n\n shape = (22, 3)\n\n with h5py.File(h5_path, \"w\") as f:\n f.create_dataset(\"a\", shape=shape)\n\n assert H5.get_shape(h5_path, \"a\") == shape\n\n @pytest.mark.parametrize(\"verbose\", [True, False])\n @pytest.mark.parametrize(\"batch_size\", [1, 2, 5])\n @pytest.mark.parametrize(\"model\", [\"SBERT\"])\n @pytest.mark.parametrize(\n \"indices\",\n [\n [10, 1, 0, 4, 6, 2, 12, 5],\n [1],\n [1, 2],\n [6, 5, 4, 3, 2, 1, 0],\n [1, 5, 2, 6, 11, 12, 14],\n ],\n )\n def test_load(self, embeddings_h5_path, model, verbose, batch_size, indices):\n with h5py.File(embeddings_h5_path, \"r\") as f:\n dset_np = f[model][:]\n\n res_loaded = H5.load(\n embeddings_h5_path,\n model,\n indices=np.array(indices),\n verbose=verbose,\n batch_size=batch_size,\n )\n\n res_true = dset_np[indices]\n\n assert isinstance(res_loaded, np.ndarray)\n assert res_loaded.shape == res_true.shape\n\n # Check nans are identical\n assert np.all(np.isnan(res_loaded) == np.isnan(res_true))\n\n # Check nonnan entries\n nonnan_mask = ~np.isnan(res_loaded)\n assert np.allclose(res_loaded[nonnan_mask], res_true[nonnan_mask])\n\n def test_load_duplicates(self, embeddings_h5_path):\n with pytest.raises(ValueError):\n H5.load(embeddings_h5_path, \"SBERT\", indices=np.array([1, 2, 2]))\n\n @pytest.mark.parametrize(\"flip\", [True, False])\n def test_write(self, tmpdir, flip):\n h5_path = pathlib.Path(str(tmpdir)) / \"to_be_created.h5\"\n\n shape = (20, 3)\n dtype_h5 = \"f4\"\n dtype_np = \"float32\"\n\n with h5py.File(h5_path, \"w\") as f:\n f.create_dataset(\"a\", shape=shape, dtype=dtype_h5, fillvalue=np.nan)\n\n data = np.random.random((10, 3)).astype(dtype_np)\n indices = np.arange(0, 20, 2)\n if flip:\n indices = np.flip(indices)\n\n indices_complement = np.setdiff1d(np.arange(shape[0]), indices)\n\n H5.write(h5_path, \"a\", data, indices)\n\n with h5py.File(h5_path, \"r\") as f:\n res_np = f[\"a\"][:]\n\n assert res_np.shape == shape\n assert np.allclose(res_np[indices], data)\n assert np.all(np.isnan(res_np[indices_complement]))\n\n\ndef test_load_save_jsonl(tmpdir):\n path = pathlib.Path(str(tmpdir)) / \"file.jsonl\"\n\n li: list[dict[str, Any]] = [{\"a\": 1, \"b\": \"cc\"}, {\"k\": 23}]\n JSONL.dump_jsonl(li, path)\n lo = JSONL.load_jsonl(path)\n\n assert li == lo\n\n\n@pytest.mark.parametrize(\n \"metadata,expected_value\",\n [\n ({\"wrongkey\": \"wrongvalue\"}, False), # labels key missing\n ({\"labels\": \"wrongvalue\"}, False), # ner key missing\n ({\"labels\": {\"ner\": [\"SEVERAL\", \"ENTITIES\"]}}, False), # several entities\n ({\"labels\": {\"ner\": [\"organism\"]}}, False), # entity lower\n ({\"labels\": {\"ner\": [\"ORGANISM\"]}}, True), # Good structure\n ],\n)\ndef test_check_entity_type_consistency(tmpdir, metadata, expected_value):\n \"\"\"Test that checks are working\"\"\"\n # Wrong model directory name\n wrong_model_dir = pathlib.Path(tmpdir) / \"models\" / \"ner_er\" / \"wrongmodelname\"\n wrong_model_dir.mkdir(parents=True)\n assert check_entity_type_consistency(wrong_model_dir) is False\n\n # Missing meta.json file\n good_model_dir = pathlib.Path(tmpdir) / \"models\" / \"ner_er\" / \"model-organism\"\n good_model_dir.mkdir(parents=True)\n assert check_entity_type_consistency(good_model_dir) is False\n\n # meta.json structure\n meta_path = good_model_dir / \"meta.json\"\n with open(meta_path, \"w\") as f:\n json.dump(metadata, f)\n assert check_entity_type_consistency(good_model_dir) is expected_value\n\n\ndef test_get_available_spacy_models(spacy_model_path, entity_types):\n \"\"\"Test that available spacy models.\"\"\"\n models_dir = spacy_model_path / \"models\" / \"ner_er\"\n expected_results = {\n etype.upper(): models_dir / f\"model-{etype.lower()}\" for etype in entity_types\n }\n results = get_available_spacy_models(spacy_model_path)\n assert isinstance(results, dict)\n assert len(results) == 2\n assert sorted(results.keys()) == sorted(entity_types)\n assert results == expected_results\n\n\n@pytest.mark.filterwarnings()\ndef test_get_available_spacy_models_warning(tmpdir):\n \"\"\"Test that available spacy models warnings.\"\"\"\n wrong_path = pathlib.Path(tmpdir) / \"wrongpath\"\n wrong_model = wrong_path / \"models\" / \"ner_er\" / \"wrongmodel\"\n wrong_model.mkdir(parents=True)\n with pytest.warns(UserWarning):\n _ = get_available_spacy_models(wrong_path)\n\n\n@pytest.mark.parametrize(\n \"model_name,is_found\", [(\"en_core_web_sm\", True), (\"xx_xxxx_xxx_xx\", False)]\n)\ndef test_load_spacy_model(model_name, is_found):\n if is_found:\n nlp = load_spacy_model(model_name)\n assert isinstance(nlp, spacy.language.Language)\n else:\n with pytest.raises(ModuleNotFoundError):\n load_spacy_model(model_name)\n","repo_name":"BlueBrain/Search","sub_path":"tests/unit/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":13470,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"77"} +{"seq_id":"40483571347","text":"#!/usr/bin/python3\n\nimport flask\nimport gosso\n\napp = flask.Flask(__name__)\n\n@app.route(\"/perro/\")\ndef edad(edad_perro):\n perro = int(edad_perro)\n un_gos = gosso.Gosso(perro)\n un_gos.calculo_edad()\n return str(un_gos)\n\ndef main():\n app.run(host=\"0.0.0.0\")\n\nif __name__ == \"__main__\":\n main()","repo_name":"avs71194/API_REST_curs_SOC","sub_path":"api_gosso.py","file_name":"api_gosso.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"26740928888","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\nimport pygame\n#This takes the settings class from the settings file\nfrom settings import Settings\nfrom Ship import Ship\nimport game_functions as gf\nfrom pygame.sprite import Group\nfrom background import Background\nfrom Platforms import Platform\n\n\n#\n#mainClock=pygame.time.Clock()\n#\n#mainClock.tick(fps)\n\ndef run_game():\n pygame.init()\n ai_settings=Settings()\n \n screen=pygame.display.set_mode((\n ai_settings.screen_width,ai_settings.screen_height))\n \n pygame.display.set_caption(\"Teddy Attack\")\n \n \n #set Ship settings\n \n ship=Ship(ai_settings,screen)\n #cat=Cat(ai_settings,screen)\n \n \n #Set Attack method\n bullets=Group()\n platforms=Group()\n \n x=0\n background = Background([800,0])\n \n #x=0\n\n Cats=Group()\n \n \n while True:\n \n gf.check_events(ai_settings,screen,ship,bullets,Cats,platforms)\n \n \n ship.update()\n ship.bot()\n gf.hit_platform(ship,platforms)\n \n \n gf.update_bullets(bullets,ai_settings,Cats)\n \n \n gf.cat_check(ai_settings,screen,Cats)\n \n \n gf.update_cat(ship,Cats)\n gf.update_platforms(platforms,screen) \n \n gf.update_screen(ai_settings,screen,ship,bullets,Cats,background,\n x, platforms)\n \n \n \n ai_settings.cat_gen+=1\n \n if(ship.rect.centerx==ship.middle and ship.moving_right):\n x-=1\n \n \n\nrun_game()\n ","repo_name":"spurioushound/Teddy-Origins","sub_path":"teddy_origins.py","file_name":"teddy_origins.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"34153799478","text":"from functools import lru_cache\nimport time\nfrom typing import List, Optional\n\n# Third party\nfrom asyncpg import connect, create_pool, Connection\nfrom asyncpg.exceptions import (\n PostgresError,\n InvalidCatalogNameError,\n DuplicateDatabaseError,\n)\nfrom asyncpg.pool import Pool\nfrom fastapi import status, HTTPException\n\n# Internal\nfrom .query import (\n CREATE_DATABASE,\n CREATE_TABLE,\n DELETE,\n INSERT,\n SELECT,\n SETTINGS,\n UPDATE,\n)\n\nfrom ..internals.logger import log_postgres_error\nfrom app.models.brain_pep.device import Device\nfrom app.models.brain_pep.service import Service, GatewayService\n\n# ---------------------------------------------------------------------------------------\n\n\nclass DataBase:\n pool: Pool = None\n \"\"\"Connection pool to the database\"\"\"\n\n @staticmethod\n async def __create_table_service_mapping(sys_conn: Connection):\n await sys_conn.execute(CREATE_TABLE[\"service_mapping\"])\n\n @staticmethod\n async def __create_table_device_mapping(sys_conn: Connection):\n await sys_conn.execute(CREATE_TABLE[\"device_mapping\"])\n\n @classmethod\n async def connect(cls) -> None:\n \"\"\"\n Create a connection pool to the database\n \"\"\"\n try:\n # Try to create a connection pool to the Database\n cls.pool = await create_pool(\n user=SETTINGS.postgres_user,\n password=SETTINGS.postgres_pwd,\n database=SETTINGS.postgres_db,\n host=SETTINGS.postgres_host,\n port=SETTINGS.postgres_port,\n max_size=SETTINGS.connection_number,\n )\n\n except InvalidCatalogNameError:\n # Flag that indicates if the tables must be created\n create_tables = True\n # Connect to Database template\n sys_conn = await connect(\n host=SETTINGS.postgres_host,\n user=SETTINGS.postgres_user,\n port=SETTINGS.postgres_port,\n password=SETTINGS.postgres_pwd,\n database=\"template1\",\n )\n try:\n # Create Database\n await sys_conn.execute(CREATE_DATABASE)\n\n except DuplicateDatabaseError:\n # Another process created the database so set create_tables to False\n create_tables = False\n\n finally:\n # Disconnect from database template\n await sys_conn.close()\n\n # Create a connection pool to the Database\n cls.pool = await create_pool(\n user=SETTINGS.postgres_user,\n password=SETTINGS.postgres_pwd,\n database=SETTINGS.postgres_db,\n host=SETTINGS.postgres_host,\n port=SETTINGS.postgres_port,\n max_size=SETTINGS.connection_number,\n )\n\n # Check if the tables must be created\n if create_tables:\n async with cls.pool.acquire() as connection:\n # Create tables\n await cls.__create_table_service_mapping(connection)\n await cls.__create_table_device_mapping(connection)\n\n @classmethod\n async def insert_device(\n cls, keycloak_identifier: str, device: Device, username: str\n ):\n \"\"\"\n Insert device in the database\n\n :param keycloak_identifier: uuid associated to the mapping\n :param device: Device to store\n :param username: client\n \"\"\"\n try:\n async with cls.pool.acquire() as connection:\n await connection.execute(\n INSERT[\"device\"],\n *(\n keycloak_identifier,\n device.device_id,\n username,\n device.json(exclude_none=True),\n ),\n )\n\n except PostgresError as error:\n await log_postgres_error(error)\n raise HTTPException(\n status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n detail={\n \"resource\": \"Device\",\n \"status\": \"Something went wrong storing the data\",\n },\n )\n\n @classmethod\n async def update_device(cls, device: Device, username: str):\n \"\"\"\n Update device mapping\n\n :param device: device to update\n :param username: client\n \"\"\"\n try:\n async with cls.pool.acquire() as connection:\n await connection.execute(\n UPDATE[\"device\"],\n *(device.json(exclude_none=True), device.device_id, username),\n )\n except PostgresError as error:\n await log_postgres_error(error)\n raise HTTPException(\n status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n detail={\n \"resource\": \"Device\",\n \"status\": \"Something went wrong updating the data\",\n },\n )\n\n @classmethod\n async def delete_device(cls, device_id: str, username: str):\n \"\"\"\n Delete device from the database\n\n :param device_id: device identifier\n :param username: client\n \"\"\"\n try:\n async with cls.pool.acquire() as connection:\n await connection.execute(DELETE[\"device\"], *(device_id, username))\n except PostgresError as error:\n await log_postgres_error(error)\n raise HTTPException(\n status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n detail={\n \"resource\": \"Device\",\n \"status\": \"Something went wrong deleting the data\",\n },\n )\n\n @classmethod\n async def extract_device(cls, device_id: str) -> Device:\n \"\"\"\n Extract device info\n\n :param device_id: Device identifier\n :return: requested device\n \"\"\"\n try:\n async with cls.pool.acquire() as conn:\n device_json = await conn.fetchval(SELECT[\"device\"], device_id)\n if device_json is None:\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND, detail=\"device not found\"\n )\n return Device.parse_raw(device_json)\n except PostgresError as error:\n await log_postgres_error(error)\n raise HTTPException(\n status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n detail={\n \"resource\": \"Device\",\n \"status\": \"Something went wrong extracting the data\",\n },\n )\n\n @classmethod\n async def extract_all_devices(\n cls, keycloak_identifier: str, username: str\n ) -> List[Device]:\n \"\"\"\n Extract all devices associated to the user\n\n :param keycloak_identifier: identifier of the user stored in keycloak\n :param username: user\n :return: User device list\n \"\"\"\n try:\n async with cls.pool.acquire() as conn:\n device_list = await conn.fetch(\n SELECT[\"device_list\"], *(username, keycloak_identifier)\n )\n return [\n Device.parse_raw(device[\"policy_list\"])\n for device in device_list\n if device[\"policy_list\"]\n ]\n except PostgresError as error:\n await log_postgres_error(error)\n raise HTTPException(\n status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n detail={\n \"resource\": \"Device\",\n \"status\": \"Something went extracting the data\",\n },\n )\n\n @classmethod\n async def insert_service(\n cls, keycloak_identifier: str, username: str, service: Service\n ):\n \"\"\"\n Insert service in the database\n\n :param keycloak_identifier: keycloak identifier\n :param username: client\n :param service: service\n \"\"\"\n try:\n async with cls.pool.acquire() as connection:\n await connection.execute(\n INSERT[\"service\"],\n *(\n keycloak_identifier,\n service.name,\n username,\n service.json(exclude_none=True),\n ),\n )\n\n except PostgresError as error:\n await log_postgres_error(error)\n raise HTTPException(\n status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n detail={\n \"resource\": \"Service\",\n \"status\": \"Something went wrong storing the data\",\n },\n )\n\n @classmethod\n async def update_service(cls, service: Service, username: str):\n \"\"\"\n Update device mapping\n\n :param service: service to update\n :param username: client\n \"\"\"\n try:\n async with cls.pool.acquire() as connection:\n await connection.execute(\n UPDATE[\"service\"],\n *(service.json(exclude_none=True), service.name, username),\n )\n except PostgresError as error:\n await log_postgres_error(error)\n raise HTTPException(\n status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n detail={\n \"resource\": \"Service\",\n \"status\": \"Something went wrong updating the data\",\n },\n )\n\n @classmethod\n async def extract_service_keycloak_identifier(\n cls, service_id: str, username: str\n ) -> str:\n \"\"\"\n Extract keycloak identifier associated to the service\n :param service_id: Service of interest\n :param username: client\n :return: keycloak identifier\n \"\"\"\n try:\n async with cls.pool.acquire() as connection:\n return await connection.fetchval(\n SELECT[\"service_keycloak_id\"],\n *(\n service_id,\n username,\n ),\n )\n\n except PostgresError as error:\n await log_postgres_error(error)\n raise HTTPException(\n status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n detail={\n \"resource\": \"Service\",\n \"status\": \"Something went wrong extracting the data\",\n },\n )\n\n @classmethod\n async def extract_all_services(cls, username: str) -> List[Service]:\n \"\"\"\n Extract all services associated to the user\n\n :param username: user\n :return: Service list\n \"\"\"\n try:\n async with cls.pool.acquire() as connection:\n service_list = await connection.fetch(\n SELECT[\"service_list\"],\n username,\n )\n return [\n Service.parse_raw(service[\"policy_list\"])\n for service in service_list\n if service[\"policy_list\"]\n ]\n\n except PostgresError as error:\n await log_postgres_error(error)\n raise HTTPException(\n status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n detail={\n \"resource\": \"Service\",\n \"status\": \"Something went wrong extracting the data\",\n },\n )\n\n @classmethod\n async def delete_service(cls, service_id: str, username: str):\n \"\"\"\n Delete device from the database\n\n :param service_id: service identifier\n :param username: client\n \"\"\"\n try:\n async with cls.pool.acquire() as connection:\n await connection.execute(DELETE[\"service\"], *(service_id, username))\n except PostgresError as error:\n await log_postgres_error(error)\n raise HTTPException(\n status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n detail={\n \"resource\": \"Service\",\n \"status\": \"Something went wrong deleting the data\",\n },\n )\n\n @classmethod\n async def filter_service_list(\n cls, gateway_service: GatewayService\n ) -> List[Optional[Service]]:\n \"\"\"\n Extract a list of service from the database\n\n :param gateway_service: message to be routed by the gateway towards the services\n :return: Services requested\n \"\"\"\n\n try:\n service_list = []\n async with cls.pool.acquire() as connection:\n for service_id in gateway_service.service_list:\n service_json = await connection.fetchval(\n SELECT[\"policy_list\"], service_id\n )\n if service_json is None:\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"service {service_id} not found\",\n )\n service = Service.parse_raw(service_json)\n service_scopes_set = set(service.resource_scopes)\n control_flag = True\n if \"storage_policy\" in service_scopes_set:\n service_scopes_set = service_scopes_set.difference(\n {\"storage_policy\"}\n )\n if gateway_service.sign_device.storage_policy:\n if (\n gateway_service.sign_device.storage_policy.timestamp()\n < time.time()\n ):\n control_flag = False\n else:\n control_flag = False\n\n if control_flag:\n if service_scopes_set.issubset(\n set(gateway_service.sign_device.policy_list)\n ):\n service_list.append(service)\n return service_list\n except PostgresError as error:\n await log_postgres_error(error)\n raise HTTPException(\n status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n detail={\n \"resource\": \"Service\",\n \"status\": \"Something went wrong storing the data\",\n },\n )\n\n @classmethod\n async def disconnect(cls):\n \"\"\"\n Disconnect from the database\n \"\"\"\n await cls.pool.close()\n\n\n# ---------------------------------------------------------------------------------------\n\n\n@lru_cache(maxsize=1)\ndef get_database() -> DataBase:\n \"\"\"Obtain as a singleton an instance of the database\"\"\"\n return DataBase()\n\n\n# ---------------------------------------------------------------------------------------\n","repo_name":"eclipse-researchlabs/brain-iot-privacy-control-system-api","sub_path":"app/db/postgresql.py","file_name":"postgresql.py","file_ext":"py","file_size_in_byte":15261,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"4638664988","text":"# python need to use traditional DFS and binary search and in addition, we need to use prune, with flag = 1 to deal with symetry.\n\n# 1, use dp, would TLE\n# 2, use dfs and binary search, assign worker to deal with ubset states, would also TLE\n# 3, use traditional dfs, and binary search. It is easy to prune, use a flag, to assign to worker = 0 obly once, meaning try only once.\nclass Solution:\n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n n = len(jobs)\n \n #dp[0][0] = 0\n \n jobs.sort(reverse = True)\n def dfs( worker, limit, m):\n if m >= n :\n return True\n flag = 0\n for j in range(k):\n if worker[j] + jobs[m] > limit:\n continue\n if worker[j] == 0:\n if flag:\n continue\n else:\n flag = 1\n worker[j] += jobs[m]\n if dfs( worker, limit, m + 1) :\n return True\n worker[j] -= jobs[m]\n\n \n return False\n \n #print(time_subset)\n low = 1\n high = sum(jobs) + 1\n \n \n \n while low < high:\n m = (low + high) // 2\n worker = [0]* k \n if dfs(worker, m, 0):\n high = m\n else:\n low = m + 1\n \n return low\n \n \n \n","repo_name":"littlefattiger/My_LC_solution","sub_path":"python/1723.py","file_name":"1723.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"39834896560","text":"import json\nimport asyncio\nfrom urllib.parse import quote\n\nfrom autobahn.asyncio.wamp import ApplicationRunner, ApplicationSession\n\n\nclass Component(ApplicationSession):\n async def onJoin(self, details):\n print(details)\n await self.register(self.authorizer, 'com.weather.authorize')\n await self.register(self.login, 'com.weather.login')\n\n async def authorizer(self, session, uri, action, options):\n if action != 'subscribe':\n return False\n\n cities = session.get('authextra', {}).get('cities', [])\n cities = [f'com.weather.city-{c}' for c in cities]\n\n return uri in cities\n\n async def login(self, realm, authid, details):\n print('------- login ---------', realm, authid)\n from pprint import pprint\n pprint(details['authextra'])\n\n print('-------------')\n # loop = asyncio.get_event_loop()\n session_id = details[\"authextra\"][\"token\"]\n data2 = await self.call(\"com.myapp.get_cities\",\n method='GET',\n url=f'{quote(session_id)}/')\n print('d2', data2)\n cities = await asyncio.get_event_loop().run_in_executor(\n None,\n json.loads,\n data2['content']\n )\n cities = cities['cities']\n return {\n 'role': 'frontend',\n 'authid': details[\"authextra\"][\"token\"].split(':')[0],\n 'extra': {\n 'cities': cities\n }\n }\n\n\nif __name__ == '__main__':\n realm = 'realm1'\n url = 'rs://localhost:8081'\n runner = ApplicationRunner(url, realm)\n runner.run(Component)\n","repo_name":"IBestuzhev/weather","sub_path":"crossb/authorizer.py","file_name":"authorizer.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"20553603402","text":"\"\"\"bb_controller controller.\"\"\"\n\nfrom controller import Robot, Receiver\n\nclass Controller:\n def __init__(self, robot): \n # taken from e-puck_line_lab1.py -------------------------------------------------------\n # Robot Parameters\n self.robot = robot\n self.time_step = 32 # ms\n self.max_speed = 1 # m/s\n \n # Enable Motors\n self.left_motor = self.robot.getDevice('left wheel motor')\n self.right_motor = self.robot.getDevice('right wheel motor')\n self.left_motor.setPosition(float('inf'))\n self.right_motor.setPosition(float('inf'))\n self.left_motor.setVelocity(0.0)\n self.right_motor.setVelocity(0.0)\n \n # Enable Proximity Sensors\n self.proximity_sensors = []\n for i in range(8):\n sensor_name = 'ps' + str(i)\n self.proximity_sensors.append(self.robot.getDevice(sensor_name))\n self.proximity_sensors[i].enable(self.time_step)\n # taken from e-puck_line_lab1.py -------------------------------------------------------\n \n # Enable Ground Sensors\n self.ground_sensors = [] # left, center, right\n for i in range(3):\n sensor_name = \"gs\" + str(i)\n self.ground_sensors.append(self.robot.getDevice(sensor_name))\n self.ground_sensors[i].enable(self.time_step)\n\n # taken from e-puck_light_lab2.py ------------------------------------------------------- \n self.light_sensors = []\n for i in range(8):\n sensor_name = \"ls\" + str(i)\n self.light_sensors.append(self.robot.getDevice(sensor_name))\n self.light_sensors[i].enable(self.time_step)\n # taken from e-puck_light_lab2.py -------------------------------------------------------\n\n self.light_on = False\n self.leave_obstacle_avoidance = False\n \n self.receiver = Receiver(\"receiver\")\n self.receiver.enable(self.time_step)\n self.message = \"\"\n\n\n # This methods checks to see if the simullation is still running when the program is within while loops. - Reece\n def sim_check(self):\n # If the simulation has stopped, terminate bb_controller.py\n if (self.robot.step(self.time_step) == -1):\n exit()\n\n # This method delays the program execution by a specified amount of iterations, it acts as a time.sleep() substitute as this didn't work for some reason. - Reece\n def delay(self, value):\n i = 0\n while(i <= value):\n self.sim_check()\n i = i + 1\n\n # This method checks the beacon and updates the light_on variable to dictate what route the robot goes along. - Reece\n def check_illumination_levels(self): \n for i in range(8):\n # If beacon detected on any light sensor, change light_on state\n if (self.light_sensors[i].getValue() == 0.0):\n self.light_on = True\n\n # This method is responsible for the robot following the line. - Reece\n def follow_line(self):\n \n #print(\"L: \", self.ground_sensors[0].getValue(), \" C: \", self.ground_sensors[1].getValue(), \" R: \", self.ground_sensors[2].getValue()) \n\n # No line\n if (self.ground_sensors[0].getValue() > 500 and self.ground_sensors[1].getValue() > 500 and self.ground_sensors[2].getValue() > 500):\n if (self.light_on == True):\n self.left_motor.setVelocity(0.1)\n self.right_motor.setVelocity(1)\n # else:\n # self.left_motor.setVelocity(1)\n # self.right_motor.setVelocity(0.1) \n\n # No line on left, Turn right\n elif (self.ground_sensors[0].getValue() > 500):\n self.left_motor.setVelocity(1)\n self.right_motor.setVelocity(0.5)\n\n # No line on right, Turn left\n elif (self.ground_sensors[2].getValue() > 500):\n self.left_motor.setVelocity(0.5)\n self.right_motor.setVelocity(1)\n\n # Line in the middle, Go forward\n elif (self.ground_sensors[1].getValue() < 500):\n self.left_motor.setVelocity(1)\n self.right_motor.setVelocity(1)\n\n # This method is responsible for realigning the ground sensors with the line so that the follow_line() method can take over once the program breaks out of the loops in avoid_obstacles(). - Reece \n def exit_obstacle_avoidance(self, i):\n if (i > 5 and self.ground_sensors[0].getValue() < 500 and self.ground_sensors[1].getValue() < 500 and self.ground_sensors[2].getValue() < 500):\n self.left_motor.setVelocity(1)\n self.right_motor.setVelocity(0.1)\n self.delay(100)\n self.leave_obstacle_avoidance = True\n\n # This method is responsible for avoiding obstacles on the line. - Reece\n def avoid_obstacles(self): \n # Set threshold\n threshold = 200\n\n # If obstacle close to front:\n if (self.proximity_sensors[0].getValue() > threshold or self.proximity_sensors[7].getValue() > threshold):\n\n #print(\"obstacle detected!\")\n\n # Spin right until the left side sensor is facing the obstacle,\n while (self.proximity_sensors[5].getValue() < threshold):\n self.sim_check() \n\n #print(\"re-aligning left sensor by right turn...\")\n self.left_motor.setVelocity(1)\n self.right_motor.setVelocity(-1)\n\n i = 0\n while(1):\n self.sim_check()\n self.exit_obstacle_avoidance(i)\n if (self.leave_obstacle_avoidance):\n break\n\n # Spin left until the left side sensor is facing the obstacle, \n while (self.proximity_sensors[5].getValue() < threshold):\n self.sim_check()\n self.exit_obstacle_avoidance(i)\n if (self.leave_obstacle_avoidance):\n break\n\n #print(\"re-aligning left sensor by left turn...\")\n self.left_motor.setVelocity(-1)\n self.right_motor.setVelocity(1)\n\n # If the robot has undershot and is spinning too far left:\n if (self.proximity_sensors[6].getValue() > threshold):\n \n # Correct by spinning right until the left side sensor is facing the obstacle,\n while (self.proximity_sensors[5].getValue() < threshold):\n self.sim_check()\n self.exit_obstacle_avoidance(i)\n if (self.leave_obstacle_avoidance):\n break\n\n #print(\"correcting far left undershoot...\")\n self.left_motor.setVelocity(1)\n self.right_motor.setVelocity(-1)\n\n # If the robot has overshot and is spinning too far right:\n elif (self.proximity_sensors[4].getValue() > threshold):\n\n # Correct by spinning left until the left side sensor is facing the obstacle,\n while (self.proximity_sensors[5].getValue() < threshold):\n self.sim_check()\n self.exit_obstacle_avoidance(i)\n if (self.leave_obstacle_avoidance):\n break\n\n #print(\"correcting far right overshoot...\")\n self.left_motor.setVelocity(-1)\n self.right_motor.setVelocity(1)\n\n # Move forward until the left side sensor is no longer facing the obstacle.\n while (self.proximity_sensors[5].getValue() > threshold):\n self.sim_check()\n self.exit_obstacle_avoidance(i)\n if (self.leave_obstacle_avoidance):\n break\n\n #print(\"scooting along the obstacle...\")\n self.left_motor.setVelocity(1)\n self.right_motor.setVelocity(1)\n\n i = i + 1\n\n # This is the main robot control loop. - Reece\n def run_bb_controller(self):\n while self.robot.step(self.time_step) != -1:\n \n self.follow_line()\n\n self.check_illumination_levels() \n \n self.follow_line()\n\n if (self.receiver.getQueueLength() > 0):\n self.message = self.receiver.getString()\n self.receiver.nextPacket()\n\n # Once the robot approches the final destination, don't avoid obstacles so it docks within the port\n if (self.message == \"E\"):\n self.avoid_obstacles()\n self.leave_obstacle_avoidance = False\n \n\nif __name__ == \"__main__\":\n my_robot = Robot()\n controller = Controller(my_robot)\n controller.run_bb_controller()\n ","repo_name":"kyleamitch/marsrover","sub_path":"bb_controller.py","file_name":"bb_controller.py","file_ext":"py","file_size_in_byte":9009,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"14380532155","text":"#!/bin/env python\n# -*- coding: utf-8 -*- vim: set ts=4 et sw=4 fdm=indent :\nimport unittest, tempfile, simplejson, os, random\n\nimport mcollectiveah\n\nclass TestFunctions(unittest.TestCase):\n def test_raise_environ(self):\n try:\n del os.environ['MCOLLECTIVE_REQUEST_FILE']\n del os.environ['MCOLLECTIVE_REPLY_FILE']\n except: pass\n self.assertRaises(mcollectiveah.MCollectiveActionNoEnv, mcollectiveah.MCollectiveAction)\n\n def test_raise_file_error(self):\n os.environ['MCOLLECTIVE_REQUEST_FILE'] = '/tmp/mcollectiveah-test-request.%d' % random.randrange(100000)\n os.environ['MCOLLECTIVE_REPLY_FILE'] = '/tmp/mcollectiveah-test-reply.%d' % random.randrange(100000)\n\n self.assertRaises(mcollectiveah.MCollectiveActionFileError, mcollectiveah.MCollectiveAction)\n\n os.unlink(os.environ['MCOLLECTIVE_REPLY_FILE'])\n\n def test_echo(self):\n tin = tempfile.NamedTemporaryFile(mode='w', delete=False)\n self.data = {'message': 'test'}\n\n simplejson.dump(self.data, tin)\n os.environ['MCOLLECTIVE_REQUEST_FILE'] = tin.name\n tin.close()\n\n tout = tempfile.NamedTemporaryFile(mode='w')\n os.environ['MCOLLECTIVE_REPLY_FILE'] = tout.name\n tout.close()\n\n mc = mcollectiveah.MCollectiveAction()\n mc.reply['message'] = mc.request['message']\n del mc\n\n tout = open(os.environ['MCOLLECTIVE_REPLY_FILE'], 'r')\n data = simplejson.load(tout)\n tout.close()\n\n self.assertEqual(data, self.data)\n\n\n os.unlink(os.environ['MCOLLECTIVE_REQUEST_FILE'])\n os.unlink(os.environ['MCOLLECTIVE_REPLY_FILE'])\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"choria-legacy/marionette-collective","sub_path":"ext/action_helpers/python/romke/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":204,"dataset":"github-code","pt":"77"} +{"seq_id":"23093418011","text":"\"\"\"\nUtility functions for computing the n-gram-based harmonic similarity.\n\"\"\"\n\n\ndef intersection(collection_a, collection_b):\n \"\"\"\n The intersection between two collections considered\n as sets (duplicated items will be removed).\n \"\"\"\n set_a = set(collection_a)\n set_b = set(collection_b)\n\n return set_a.intersection(set_b)\n\n\ndef degree_max_repetition(recpat_bag:list):\n \"\"\"\n Computes the degree of maximal repetition from a bag of\n recurring patterns -- a list of ngram tuples.\n \"\"\"\n return max([len(recpat) for recpat in recpat_bag])\n\n\ndef ngram_hsim(rpg_a:list, rpg_b:list):\n \"\"\"\n Computes the degree of maximal repetition from a bag of\n recurring patterns -- a list of tuples.\n \"\"\"\n degree_a = degree_max_repetition(rpg_a)\n degree_b = degree_max_repetition(rpg_b)\n\n common_rpg = intersection(rpg_a, rpg_b)\n if len(common_rpg) == 0: # nothing in common\n return 0., [] # no need to go further\n\n degree_common_rp = degree_max_repetition(common_rpg)\n # Retrieve all the longest recurrent pattern in common\n longest_common_rps = [rp for rp in common_rpg \n if len(rp) == degree_common_rp]\n # These two make sense independently, because one sequence\n # can be shorter and contained in the other, so the level\n # of similarity from their side can reflect this (FW).\n sim_a = degree_common_rp/degree_a\n sim_b = degree_common_rp/degree_b\n\n return (sim_a + sim_b) / 2, longest_common_rps\n\n\ndef pairwise_harmonic_similarity(track_rpbag:dict, hsim_fn=ngram_hsim):\n \"\"\"\n Computes the pair-wise harmonic similarity among tracks.\n\n Args:\n track_rpbag (dict): a dictionary mapping each track to the list\n of recurrent patterns that were extracted from the track.\n hsim_fn (function): the similarity function to consider.\n\n Returns:\n A dictionary mapping each couple of tracks to their harmonic\n similarity and the longest recurrent pattern they share, if any.\n If two tracks have no recurrent pattern in common, no match will\n be found in the dictionary (this is to limit space complexity).\n\n \"\"\"\n track_ids = list(track_rpbag.keys())\n hsim_map = {track_id: {} for track_id in track_ids}\n\n for i, track_a in enumerate(track_ids):\n a_rpbag = track_rpbag[track_a] # fix for now\n for j in range(i + 1, len(track_ids)): # move ahead\n track_b = track_ids[j]\n b_rpbag = track_rpbag[track_b]\n # Compute the harmonic similarity\n hsim, longest_rps = hsim_fn(a_rpbag, b_rpbag)\n if hsim > 0.: # save only non-trivial\n hsim_map[track_a][track_b] = hsim, longest_rps\n hsim_map[track_b][track_a] = hsim, longest_rps","repo_name":"polifonia-project/lharp","sub_path":"src/harmonic_lib.py","file_name":"harmonic_lib.py","file_ext":"py","file_size_in_byte":2787,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"2890339837","text":"import streamlit as st\r\nimport pandas as pd\r\nimport numpy as np\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom operator import itemgetter\r\nfrom nltk.corpus import stopwords\r\nfrom sklearn.metrics.pairwise import linear_kernel\r\nfrom sklearn.metrics.pairwise import sigmoid_kernel\r\nfrom joblib import Parallel, delayed\r\nimport joblib\r\nimport pickle\r\nfrom tensorflow.keras.models import load_model\r\n\r\n\r\nif \"visibility\" not in st.session_state:\r\n st.session_state.visibility = \"visible\"\r\n st.session_state.disabled = False\r\n\r\n# Sidebar Design\r\nwith st.sidebar:\r\n st.write('List of Recommendation Systems')\r\n #name = st.text_input(\r\n #\"Enter product here 👇\",\r\n #label_visibility=st.session_state.visibility,\r\n #disabled=st.session_state.disabled,)\r\n response=st.radio(\"Please choose your recommendation method..\",('Void','Content-based filtering','Collaborative Filtering','Hybrid Model', 'Neural Network'))\r\n if response=='Content-based filtering':\r\n st.write('You have selected Content-based filtered recommendations.')\r\n elif response=='Neural Network':\r\n st.write('You have selected neural network based recommendations.')\r\n else:\r\n st.write('You have selected void recommendations.')\r\n\r\n\r\n# The function below will be used in content based filtering\r\ndef similarity(result, title):\r\n desc_vector = tfidf.fit_transform(result['description'].apply(lambda x:x.lower()).apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)])))\r\n similarity_matrix = linear_kernel(desc_vector, desc_vector)\r\n mapping = pd.Series(result.index, index=result['title'])\r\n product_index = mapping[title]\r\n similarity_score = list(enumerate(similarity_matrix[product_index]))\r\n similarity_score = sorted(similarity_score, key=lambda x: x[1], reverse=True)\r\n list_similarity = []\r\n for i in range(len(similarity_score)):\r\n list_similarity.append(similarity_score[i][1])\r\n result['similarity'] = list_similarity\r\n return result\r\n\r\n\r\n# This function will also be used in content based filtering\r\ndef get_rec(title):\r\n i=indices[title]\r\n x=data.iloc[i]['label']\r\n t=[x]\r\n idx=list(data[data['label'].isin(t)].index)\r\n sig_temp=list(enumerate(sig[i]))\r\n sig_scores=itemgetter(*idx)(sig_temp)\r\n scores=sorted(sig_scores, key=lambda x:x[0], reverse=True)\r\n product_indices=[i[0] for i in scores]\r\n result = data.iloc[product_indices]\r\n result=result.reset_index(drop=True)\r\n output = similarity(result, title)\r\n output.drop(['label','similarity'], axis=1, inplace=True)\r\n return output[['title','description','asin','ratings','n_ratings']][:20]\r\n\r\n# This will be called while executing hybrid recommendation\r\ndef hybrid(user_id):\r\n if user_id!=0 or len(user_id)!=0:\r\n with open('user_id_map_pkl.pkl', 'rb') as f:\r\n user_id_map = pickle.load(f)\r\n\r\n with open('nteractions_pkl.pkl', 'rb') as f:\r\n interactions = pickle.load(f)\r\n\r\n with open('model_pkl.pkl', 'rb') as f:\r\n model = pickle.load(f)\r\n\r\n with open('item_id_map_pkl.pkl', 'rb') as f:\r\n item_id_map = pickle.load(f)\r\n\r\n with open('idx_pkl.pkl', 'rb') as f:\r\n idx = pickle.load(f)\r\n\r\n df=pd.read_csv('./df.csv')\r\n\r\n user_x = user_id_map[user_id]\r\n n_users, n_items = interactions.shape # no of users * no of items\r\n result=model.predict(user_x, np.arange(n_items))\r\n res = [val for (_, val) in sorted(zip(result, list(item_id_map)), key=lambda x: x[0], reverse=True)]\r\n final=pd.DataFrame()\r\n for i in res[:11]:\r\n final=final.append(pd.DataFrame({'Product':[idx[idx['asin']==i].values[0][0]],'id':[idx[idx['asin']==i].values[0][1]],'Rating':[round(df[df['item']==i]['r'].mean(),2)]}),ignore_index = True)\r\n return final\r\n else:\r\n return 'Enter a valid user ID'\r\n\r\n\r\n\r\n# Radio Button processing\r\nif response=='Content-based filtering':\r\n try:\r\n name = st.text_input(\"Enter the product name here 👇\", label_visibility=st.session_state.visibility, disabled=st.session_state.disabled,)\r\n if name:\r\n welcome='You are searching for '+name+' and you have selected content-based filtering.'\r\n st.header(welcome)\r\n st.subheader('Product Recommendations')\r\n\r\n data = pd.read_csv('data.csv')\r\n # Data Pre-processing\r\n documents = data['description'].values.astype(\"U\")\r\n vectorizer = TfidfVectorizer(stop_words='english')\r\n features = vectorizer.fit_transform(documents)\r\n # Importing the model\r\n model = joblib.load('kmeans.pkl')\r\n # Predicting clusters usng model\r\n label = model.fit_predict(features)\r\n unique_labels = np.unique(label)\r\n # Concatanating the values\r\n data['label']=np.array(label)\r\n # Data Processing\r\n tfidf = TfidfVectorizer(min_df=3, max_features=None,strip_accents='unicode', analyzer='word',token_pattern=r'\\w{1,}', ngram_range=(1,3), stop_words='english')\r\n tfidf_matrix=tfidf.fit_transform(data['description'])\r\n sig = sigmoid_kernel(tfidf_matrix,tfidf_matrix)\r\n indices = pd.Series(data.index,index=data['title'])\r\n stop = stopwords.words('english')\r\n extras=['benefits
','','a','this','that','these','those','to','of','at','with','for','also','is']\r\n stop.append(extras)\r\n result=get_rec(name)\r\n st.write(result)\r\n except:\r\n st.write(\"Please enter a product title to view similar products.\")\r\n\r\nelif response=='Collaborative Filtering':\r\n welcome='You have selected collaborative filtering.'\r\n st.header(welcome)\r\n label_visibility=st.session_state.visibility,\r\n disabled=st.session_state.disabled\r\n st.write(\"Please click on the following link for collaborative filtering based recommendations: \")\r\n st.write(\"https://colab.research.google.com/drive/1HaLrSvDIGsam30a3dF6FqBBAjUPdRjxV#scrollTo=rqFx9Wc_NDZ8\")\r\n # Call function for hyperlinking to collaborative filtering notebook here...\r\n\r\nelif response=='Hybrid Model':\r\n welcome='You have selected hybrid model.'\r\n st.header(welcome)\r\n user_id = st.text_input(\"Enter your user id here 👇\", label_visibility='visible', disabled=False,)\r\n try:\r\n if user_id:\r\n st.write('Welcome user: ',user_id)\r\n st.subheader('Product Recommendations for ', user_id)\r\n result = hybrid(user_id)\r\n st.write(result)\r\n except:\r\n st.write(\"Please enter a valid user ID for recommendations.\")\r\n\r\nelif response=='Neural Network':\r\n welcome='You have selected neural network.'\r\n st.header(welcome)\r\n user_id = st.text_input(\"Enter your user id here 👇\", label_visibility=st.session_state.visibility, disabled=st.session_state.disabled,)\r\n\r\n try:\r\n if user_id:\r\n st.write('Welcome user: ',user_id)\r\n le = pickle.load(open('label_encoder.pkl', 'rb'))\r\n #w2v = Word2Vec.load('word2vec_model.pkl')\r\n model = load_model('neural_recommendation_model.h5')\r\n with open('scaler.pkl', 'rb') as f:\r\n scaler = pickle.load(f)\r\n df = pd.read_csv('reviews_and_metadata_updated.csv')\r\n user_encoded = le.transform([user_id])\r\n\r\n # Generate the title vectors for all products in the dataset\r\n all_title_vectors = np.vstack(df['title_vectors'].apply(lambda x: np.fromstring(x[1:-1], sep=' ')))\r\n # Normalize the user ID\r\n user_encoded = scaler.transform(user_encoded.reshape(-1,1))\r\n # Make predictions for all products\r\n predictions = model.predict([all_title_vectors, np.repeat(user_encoded, len(df), axis=0)])\r\n # Get the recommendation scores for all products\r\n recommendation_scores = predictions.flatten()\r\n # Sort the products based on their scores\r\n sorted_indices = np.argsort(recommendation_scores)[::-1]\r\n # Get the top 10 recommended products\r\n top_products = df.iloc[sorted_indices][:10]\r\n # Print the top 10 recommended products\r\n st.subheader('Product Recommendations for you')\r\n st.write(pd.DataFrame(top_products[['title', 'description', 'asin']]))\r\n except:\r\n st.write(\"Please enter a valid User ID to get product recommendations\")\r\n\r\n\r\n\r\nelif response=='Void':\r\n welcome= 'Recommendation Systems'\r\n st.header(welcome)\r\n\r\n\r\n st.subheader('Content-based Filtering')\r\n st.write(\"Content-based filtering is a type of recommender system that attempts to guess what a user may like based on that user's activity.\")\r\n st.write(\"Content-based filtering makes recommendations by using keywords and attributes assigned to objects in a database (e.g., items in an online marketplace) and matching them to a user profile. The user profile is created based on data derived from a user’s actions, such as purchases, ratings (likes and dislikes), downloads, items searched for on a website and/or placed in a cart, and clicks on product links.\")\r\n\r\n st.subheader('Collaborative Filtering')\r\n st.write(\"Collaborative filtering filters information by using the interactions and data collected by the system from other users. It’s based on the idea that people who agreed in their evaluation of certain items are likely to agree again in the future.\")\r\n st.write(\"Collaborative-filtering systems focus on the relationship between users and items. The similarity of items is determined by the similarity of the ratings of those items by the users who have rated both items.\")\r\n\r\n st.subheader('Hybrid Recommendations')\r\n st.write(\"A hybrid recommendation system is a special type of recommendation system which can be considered as the combination of the content and collaborative filtering method. Combining collaborative and content-based filtering together may help in overcoming the shortcoming we are facing at using them separately and also can be more effective in some cases.\")\r\n\r\n st.subheader('Neural Network-based Recommendations')\r\n st.write(\"Neural networks are trained to approximate an objective function by minimizing the estimation error with a gradient descent algorithm. We can use their inherent optimization capability to perform matrix factorization.\")\r\n st.write(\"In order to do so, we project the users and the items into a latent space of dimension d by using embedding layers. Embedding layers learn to map a high-dimensional, sparse set of discrete features to a dense array of real numbers in a continuous space, the equivalent of projecting our n users and m items into d-dimensional vectors.\")\r\n\r\nelse:\r\n st.subheader('Recommendation Systems')\r\n st.write(\"A recommender system is a subclass of information filtering that seeks to predict the “rating” or “preference” a user will give an item, such as a product, movie, song, etc.\")\r\n st.write(\"Recommender systems provide personalized information by learning the user’s interests through traces of interaction with that user. Much like machine learning algorithms, a recommender system makes a prediction based on a user’s past behaviors. Specifically, it’s designed to predict user preference for a set of items based on experience.\")\r\n\r\n st.subheader('Content-based Filtering')\r\n st.write(\"Content-based filtering is a type of recommender system that attempts to guess what a user may like based on that user's activity.\")\r\n st.write(\"Content-based filtering makes recommendations by using keywords and attributes assigned to objects in a database (e.g., items in an online marketplace) and matching them to a user profile. The user profile is created based on data derived from a user’s actions, such as purchases, ratings (likes and dislikes), downloads, items searched for on a website and/or placed in a cart, and clicks on product links.\")\r\n\r\n st.subheader('Collaborative Filtering')\r\n st.write(\"Collaborative filtering filters information by using the interactions and data collected by the system from other users. It’s based on the idea that people who agreed in their evaluation of certain items are likely to agree again in the future.\")\r\n st.write(\"Collaborative-filtering systems focus on the relationship between users and items. The similarity of items is determined by the similarity of the ratings of those items by the users who have rated both items.\")\r\n\r\n st.subheader('Hybrid Recommendations')\r\n st.write(\"A hybrid recommendation system is a special type of recommendation system which can be considered as the combination of the content and collaborative filtering method. Combining collaborative and content-based filtering together may help in overcoming the shortcoming we are facing at using them separately and also can be more effective in some cases.\")\r\n\r\n st.subheader('Neural Network-based Recommendations')\r\n st.write(\"Neural networks are trained to approximate an objective function by minimizing the estimation error with a gradient descent algorithm. We can use their inherent optimization capability to perform matrix factorization.\")\r\n st.write(\"In order to do so, we project the users and the items into a latent space of dimension d by using embedding layers. Embedding layers learn to map a high-dimensional, sparse set of discrete features to a dense array of real numbers in a continuous space, the equivalent of projecting our n users and m items into d-dimensional vectors.\")\r\n","repo_name":"TeamEpicProjects/Recommendation-Systems","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":13561,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"4005519643","text":"import sqlite3\n\n# Fichero con clase para gestionar los datos de nuestra base de datos SQLITE3\n\n\nclass DBmanager():\n def __init__(self, ruta_baseDatos):\n self.database_path = ruta_baseDatos\n\n def __toDict__(self, cur):\n # Obtenemos los datos de la consulta\n claves = cur.description\n filas = cur.fetchall()\n\n # Procesar los datos para devolver una lista de diccionarios. Un diccionario por fila\n resultado = []\n for fila in filas:\n d = {}\n for tclave, valor in zip(claves, fila):\n d[tclave[0]] = valor\n resultado.append(d) # lista de diccionarios con los movimientos\n\n return resultado\n\n def consultaMuchasSQL(self, query, parametros=[]):\n # Abrimos la conexion\n conexion = sqlite3.connect(self.database_path)\n cur = conexion.cursor()\n\n # Ejecutamos la consulta\n cur.execute(query, parametros)\n resultado = self.__toDict__(cur) # resultado = lista de diccionarios \n conexion.close()\n return resultado\n\n def consultaUnaSQL(self, query, parametros=[]):\n resultado = self.consultaMuchasSQL(query, parametros) # resultado = lista de diccionarios \n if len(resultado) > 0:\n return resultado[0] # resultado = primer diccionario\n\n def modificaTablaSQL(self, query, parametros=[]):\n conexion = sqlite3.connect(self.database_path)\n cur = conexion.cursor()\n\n cur.execute(query, parametros)\n\n conexion.commit() # commit the changes made after any transaction that modifies data \n conexion.close()\n","repo_name":"yalaska04/myCripto","sub_path":"myCripto/dataaccess.py","file_name":"dataaccess.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"22176052626","text":"import warnings\nfrom typing import Any, cast, Iterable, Optional, Sequence, Tuple, TYPE_CHECKING, TypeVar, Union\n\nimport numpy as np\nfrom typing_extensions import Protocol\n\nfrom cirq import linalg, qis\nfrom cirq._doc import doc_private\nfrom cirq.protocols import qid_shape_protocol\nfrom cirq.protocols.decompose_protocol import _try_decompose_into_operations_and_qubits\nfrom cirq.type_workarounds import NotImplementedType\n\nif TYPE_CHECKING:\n import cirq\n\n# This is a special indicator value used by the apply_unitary method\n# to determine whether or not the caller provided a 'default' argument. It must\n# be of type np.ndarray to ensure the method has the correct type signature in\n# that case. It is checked for using `is`, so it won't have a false positive if\n# the user provides a different np.array([]) value.\n\nRaiseTypeErrorIfNotProvided: np.ndarray = np.array([])\n\nTDefault = TypeVar('TDefault')\n\n\nclass ApplyUnitaryArgs:\n \"\"\"Arguments for performing an efficient left-multiplication by a unitary.\n\n The receiving object is expected to mutate `target_tensor` so that it\n contains the state after multiplication, and then return `target_tensor`.\n Alternatively, if workspace is required, the receiving object can overwrite\n `available_buffer` with the results and return `available_buffer`. Or, if\n the receiving object is attempting to be simple instead of fast, it can\n create an entirely new array and return that.\n\n Attributes:\n target_tensor: The input tensor that needs to be left-multiplied by\n the unitary effect of the receiving object. The tensor will\n have the shape (2, 2, 2, ..., 2). It usually corresponds to\n a multi-qubit superposition, but it could also be a multi-qubit\n unitary transformation or some other concept.\n available_buffer: Pre-allocated workspace with the same shape and\n dtype as the target tensor.\n axes: Which axes the unitary effect is being applied to (e.g. the\n qubits that the gate is operating on).\n subspaces: Which subspace (in the computational basis) the unitary\n effect is being applied to, on each axis. By default it applies\n to subspace 0..d-1 on each axis, where d is the dimension of the\n unitary effect on that axis. Subspaces on each axis must be\n representable as a slice, so the dimensions specified here need to\n have a consistent step size.\n \"\"\"\n\n def __init__(\n self,\n target_tensor: np.ndarray,\n available_buffer: np.ndarray,\n axes: Iterable[int],\n subspaces: Optional[Sequence[Tuple[int, ...]]] = None,\n ):\n \"\"\"Inits ApplyUnitaryArgs.\n\n Args:\n target_tensor: The input tensor that needs to be left-multiplied by\n the unitary effect of the receiving object. The tensor will\n have the shape (2, 2, 2, ..., 2). It usually corresponds to\n a multi-qubit superposition, but it could also be a multi-qubit\n unitary transformation or some other concept.\n available_buffer: Pre-allocated workspace with the same shape and\n dtype as the target tensor.\n axes: Which axes the unitary effect is being applied to (e.g. the\n qubits that the gate is operating on).\n subspaces: Which subspace (in the computational basis) the unitary\n effect is being applied to, on each axis. By default it applies\n to subspace 0..d-1 on each axis, where d is the dimension of\n the unitary effect on that axis. Subspaces on each axis must be\n representable as a slice, so the dimensions specified here need\n to have a consistent step size.\n Raises:\n ValueError: If the subspace count does not equal the axis count, if\n any subspace has zero dimensions, or if any subspace has\n dimensions specified without a consistent step size.\n \"\"\"\n self.target_tensor = target_tensor\n self.available_buffer = available_buffer\n self.axes = tuple(axes)\n if subspaces is not None:\n if len(self.axes) != len(subspaces):\n raise ValueError('Subspace count does not match axis count.')\n for subspace, axis in zip(subspaces, self.axes):\n if any(s >= target_tensor.shape[axis] for s in subspace):\n raise ValueError('Subspace specified does not exist in axis.')\n self.slices = None if subspaces is None else tuple(map(_to_slice, subspaces))\n\n @staticmethod\n def default(\n num_qubits: Optional[int] = None, *, qid_shape: Optional[Tuple[int, ...]] = None\n ) -> 'ApplyUnitaryArgs':\n \"\"\"A default instance starting in state |0⟩.\n\n Specify exactly one argument.\n\n Args:\n num_qubits: The number of qubits to make space for in the state.\n qid_shape: The shape of the state, specifying the dimension of each\n qid.\n\n Raises:\n TypeError: If exactly neither `num_qubits` or `qid_shape` is provided or\n both are provided.\n \"\"\"\n if (num_qubits is None) == (qid_shape is None):\n raise TypeError('Specify exactly one of num_qubits or qid_shape.')\n if num_qubits is not None:\n qid_shape = (2,) * num_qubits\n qid_shape = cast(Tuple[int, ...], qid_shape) # Satisfy mypy\n num_qubits = len(qid_shape)\n state = qis.one_hot(index=(0,) * num_qubits, shape=qid_shape, dtype=np.complex128)\n return ApplyUnitaryArgs(state, np.empty_like(state), range(num_qubits))\n\n @classmethod\n def for_unitary(\n cls, num_qubits: Optional[int] = None, *, qid_shape: Optional[Tuple[int, ...]] = None\n ) -> 'ApplyUnitaryArgs':\n \"\"\"A default instance corresponding to an identity matrix.\n\n Specify exactly one argument.\n\n Args:\n num_qubits: The number of qubits to make space for in the state.\n qid_shape: A tuple representing the number of quantum levels of each\n qubit the identity matrix applies to. `qid_shape` is (2, 2, 2) for\n a three-qubit identity operation tensor.\n\n Raises:\n TypeError: If exactly neither `num_qubits` or `qid_shape` is provided or\n both are provided.\n \"\"\"\n if (num_qubits is None) == (qid_shape is None):\n raise TypeError('Specify exactly one of num_qubits or qid_shape.')\n if num_qubits is not None:\n qid_shape = (2,) * num_qubits\n qid_shape = cast(Tuple[int, ...], qid_shape) # Satisfy mypy\n num_qubits = len(qid_shape)\n state = qis.eye_tensor(qid_shape, dtype=np.complex128)\n return ApplyUnitaryArgs(state, np.empty_like(state), range(num_qubits))\n\n def with_axes_transposed_to_start(self) -> 'ApplyUnitaryArgs':\n \"\"\"Returns a transposed view of the same arguments.\n\n Returns:\n A view over the same target tensor and available workspace, but\n with the numpy arrays transposed such that the axes field is\n guaranteed to equal `range(len(result.axes))`. This allows one to\n say e.g. `result.target_tensor[0, 1, 0, ...]` instead of\n `result.target_tensor[result.subspace_index(0b010)]`.\n \"\"\"\n axis_set = set(self.axes)\n other_axes = [axis for axis in range(len(self.target_tensor.shape)) if axis not in axis_set]\n perm = (*self.axes, *other_axes)\n target_tensor = self.target_tensor.transpose(*perm)\n available_buffer = self.available_buffer.transpose(*perm)\n return ApplyUnitaryArgs(target_tensor, available_buffer, range(len(self.axes)))\n\n def _for_operation_with_qid_shape(\n self, indices: Iterable[int], slices: Tuple[Union[int, slice], ...]\n ) -> 'ApplyUnitaryArgs':\n \"\"\"Creates a sliced and transposed view of `self` appropriate for an\n operation with shape `qid_shape` on qubits with the given indices.\n\n Example:\n sub_args = args._for_operation_with_qid_shape(indices, (2, 2, 2))\n # Slice where the first qubit is |1>.\n sub_args.target_tensor[..., 1, :, :]\n\n Args:\n indices: Integer indices into `self.axes` specifying which qubits\n the operation applies to.\n slices: The slices of the operation, the subdimension in each qubit\n the operation applies to.\n\n Returns: A new `ApplyUnitaryArgs` where `sub_args.target_tensor` and\n `sub_args.available_buffer` are sliced and transposed views of\n `self.target_tensor` and `self.available_buffer` respectively.\n \"\"\"\n slices = tuple(size if isinstance(size, slice) else slice(0, size) for size in slices)\n sub_axes = [self.axes[i] for i in indices]\n axis_set = set(sub_axes)\n other_axes = [axis for axis in range(len(self.target_tensor.shape)) if axis not in axis_set]\n ordered_axes = (*other_axes, *sub_axes)\n # Transpose sub_axes to the end of the shape and slice them\n target_tensor = self.target_tensor.transpose(*ordered_axes)[(..., *slices)]\n available_buffer = self.available_buffer.transpose(*ordered_axes)[(..., *slices)]\n new_axes = range(len(other_axes), len(ordered_axes))\n return ApplyUnitaryArgs(target_tensor, available_buffer, new_axes)\n\n def subspace_index(\n self, little_endian_bits_int: int = 0, *, big_endian_bits_int: int = 0\n ) -> Tuple[Union[slice, int, 'ellipsis'], ...]:\n \"\"\"An index for the subspace where the target axes equal a value.\n\n Args:\n little_endian_bits_int: The desired value of the qubits at the\n targeted `axes`, packed into an integer. The least significant\n bit of the integer is the desired bit for the first axis, and\n so forth in increasing order. Can't be specified at the same\n time as `big_endian_bits_int`.\n big_endian_bits_int: The desired value of the qubits at the\n targeted `axes`, packed into an integer. The most significant\n bit of the integer is the desired bit for the first axis, and\n so forth in decreasing order. Can't be specified at the same\n time as `little_endian_bits_int`.\n\n Returns:\n A value that can be used to index into `target_tensor` and\n `available_buffer`, and manipulate only the part of Hilbert space\n corresponding to a given bit assignment.\n\n Example:\n If `target_tensor` is a 4 qubit tensor and `axes` is `[1, 3]` and\n then this method will return the following when given\n `little_endian_bits=0b01`:\n\n `(slice(None), 0, slice(None), 1, Ellipsis)`\n\n Therefore the following two lines would be equivalent:\n\n args.target_tensor[args.subspace_index(0b01)] += 1\n\n args.target_tensor[:, 0, :, 1] += 1\n \"\"\"\n return linalg.slice_for_qubits_equal_to(\n self.axes,\n little_endian_qureg_value=little_endian_bits_int,\n big_endian_qureg_value=big_endian_bits_int,\n qid_shape=self.target_tensor.shape,\n )\n\n\nclass SupportsConsistentApplyUnitary(Protocol):\n \"\"\"An object that can be efficiently left-multiplied into tensors.\"\"\"\n\n @doc_private\n def _apply_unitary_(\n self, args: ApplyUnitaryArgs\n ) -> Union[np.ndarray, None, NotImplementedType]:\n \"\"\"Left-multiplies a unitary effect onto a tensor with good performance.\n\n This method is given both the target tensor and workspace of the same\n shape and dtype. The method then either performs inline modifications of\n the target tensor and returns it, or writes its output into the\n workspace tensor and returns that. This signature makes it possible to\n write specialized simulation methods that run without performing large\n allocations, significantly increasing simulation performance.\n\n The target may represent a wave function, a unitary matrix, or some\n other tensor. Implementations will work in all of these cases as long as\n they correctly focus on only operating on the given axes.\n\n Args:\n args: A `cirq.ApplyUnitaryArgs` object with the `args.target_tensor`\n to operate on, an `args.available_workspace` buffer to use as\n temporary workspace, and the `args.axes` of the tensor to target\n with the unitary operation. Note that this method is permitted\n (and in fact expected) to mutate `args.target_tensor` and\n `args.available_workspace`.\n\n Returns:\n If the receiving object is not able to apply its unitary effect,\n None or NotImplemented should be returned.\n\n If the receiving object is able to work inline, it should directly\n mutate `args.target_tensor` and then return `args.target_tensor`.\n The caller will understand this to mean that the result is in\n `args.target_tensor`.\n\n If the receiving object is unable to work inline, it can write its\n output over `args.available_buffer` and then return\n `args.available_buffer`. The caller will understand this to mean\n that the result is in `args.available_buffer` (and so what was\n `args.available_buffer` will become `args.target_tensor` in the next\n call, and vice versa).\n\n The receiving object is also permitted to allocate a new\n numpy.ndarray and return that as its result.\n \"\"\"\n\n\ndef apply_unitary(\n unitary_value: Any,\n args: ApplyUnitaryArgs,\n default: Union[np.ndarray, TDefault] = RaiseTypeErrorIfNotProvided,\n *,\n allow_decompose: bool = True,\n) -> Union[np.ndarray, TDefault]:\n \"\"\"High performance left-multiplication of a unitary effect onto a tensor.\n\n Applies the unitary effect of `unitary_value` to the tensor specified in\n `args` by using the following strategies:\n\n A. Try to use `unitary_value._apply_unitary_(args)`.\n Case a) Method not present or returns `NotImplemented`.\n Continue to next strategy.\n Case b) Method returns `None`.\n Conclude `unitary_value` has no unitary effect.\n Case c) Method returns a numpy array.\n Forward the successful result to the caller.\n\n B. Try to use `unitary_value._unitary_()`.\n Case a) Method not present or returns `NotImplemented`.\n Continue to next strategy.\n Case b) Method returns `None`.\n Conclude `unitary_value` has no unitary effect.\n Case c) Method returns a numpy array.\n Multiply the matrix onto the target tensor and return to the caller.\n\n C. Try to use `unitary_value._decompose_()` (if `allow_decompose`).\n Case a) Method not present or returns `NotImplemented` or `None`.\n Continue to next strategy.\n Case b) Method returns an OP_TREE.\n Delegate to `cirq.apply_unitaries`.\n\n D. Conclude that `unitary_value` has no unitary effect.\n\n The order that the strategies are tried depends on the number of qubits\n being operated on. For small numbers of qubits (4 or less) the order is\n ABCD. For larger numbers of qubits the order is ACBD (because it is expected\n that decomposing will outperform generating the raw matrix).\n\n Args:\n unitary_value: The value with a unitary effect to apply to the target.\n args: A mutable `cirq.ApplyUnitaryArgs` object describing the target\n tensor, available workspace, and axes to operate on. The attributes\n of this object will be mutated as part of computing the result.\n default: What should be returned if `unitary_value` doesn't have a\n unitary effect. If not specified, a TypeError is raised instead of\n returning a default value.\n allow_decompose: Defaults to True. If set to False, and applying the\n unitary effect requires decomposing the object, the method will\n pretend the object has no unitary effect.\n\n Returns:\n If the receiving object does not have a unitary effect, then the\n specified default value is returned (or a TypeError is raised). If\n this occurs, then `target_tensor` should not have been mutated.\n\n Otherwise the result is the `np.ndarray` instance storing the result.\n This may be `args.target_tensor`, `args.available_workspace`, or some\n other numpy array. It is the caller's responsibility to correctly handle\n all three of these cases. In all cases `args.target_tensor` and\n `args.available_buffer` may have been mutated.\n\n Raises:\n TypeError: `unitary_value` doesn't have a unitary effect and `default`\n wasn't specified.\n \"\"\"\n # Decide on order to attempt application strategies.\n if len(args.axes) <= 4:\n strats = [\n _strat_apply_unitary_from_apply_unitary,\n _strat_apply_unitary_from_unitary,\n _strat_apply_unitary_from_decompose,\n ]\n else:\n strats = [\n _strat_apply_unitary_from_apply_unitary,\n _strat_apply_unitary_from_decompose,\n _strat_apply_unitary_from_unitary,\n ]\n if not allow_decompose:\n strats.remove(_strat_apply_unitary_from_decompose)\n\n # Try each strategy, stopping if one works.\n # Also catch downcasting warnings and throw an error: #2041\n with warnings.catch_warnings():\n warnings.filterwarnings(action=\"error\", category=np.ComplexWarning)\n for strat in strats:\n result = strat(unitary_value, args)\n if result is None:\n break\n if result is not NotImplemented:\n return result\n\n # Don't know how to apply. Fallback to specified default behavior.\n if default is not RaiseTypeErrorIfNotProvided:\n return default\n raise TypeError(\n \"cirq.apply_unitary failed. \"\n \"Value doesn't have a (non-parameterized) unitary effect.\\n\"\n \"\\n\"\n f\"type: {type(unitary_value)}\\n\"\n f\"value: {unitary_value!r}\\n\"\n \"\\n\"\n \"The value failed to satisfy any of the following criteria:\\n\"\n \"- An `_apply_unitary_(self, args) method that returned a value \"\n \"besides None or NotImplemented.\\n\"\n \"- A `_unitary_(self)` method that returned a value \"\n \"besides None or NotImplemented.\\n\"\n \"- A `_decompose_(self)` method that returned a \"\n \"list of unitary operations.\\n\"\n )\n\n\ndef _strat_apply_unitary_from_apply_unitary(\n unitary_value: Any, args: ApplyUnitaryArgs\n) -> Optional[np.ndarray]:\n # Check for magic method.\n func = getattr(unitary_value, '_apply_unitary_', None)\n if func is None:\n return NotImplemented\n if args.slices is None:\n op_qid_shape = qid_shape_protocol.qid_shape(unitary_value, (2,) * len(args.axes))\n slices = tuple(slice(0, size) for size in op_qid_shape)\n else:\n slices = args.slices\n sub_args = args._for_operation_with_qid_shape(range(len(slices)), slices)\n sub_result = func(sub_args)\n if sub_result is NotImplemented or sub_result is None:\n return sub_result\n return _incorporate_result_into_target(args, sub_args, sub_result)\n\n\ndef _apply_unitary_from_matrix(matrix: np.ndarray, unitary_value: Any, args: ApplyUnitaryArgs):\n if args.slices is None:\n val_qid_shape = qid_shape_protocol.qid_shape(unitary_value, default=(2,) * len(args.axes))\n slices = tuple(slice(0, size) for size in val_qid_shape)\n else:\n slices = args.slices\n val_qid_shape = tuple(\n ((s.step if s.stop is None else s.stop) - s.start) // (s.step or 1) for s in slices\n )\n sub_args = args._for_operation_with_qid_shape(range(len(slices)), slices)\n matrix = matrix.astype(sub_args.target_tensor.dtype)\n if len(val_qid_shape) == 1 and val_qid_shape[0] <= 2:\n # Special case for single-qubit, 2x2 or 1x1 operations.\n # np.einsum is faster for larger cases.\n subspaces = [(..., level) for level in range(val_qid_shape[0])]\n sub_result = linalg.apply_matrix_to_slices(\n sub_args.target_tensor, matrix, subspaces, out=sub_args.available_buffer\n )\n else:\n # General case via np.einsum.\n sub_result = linalg.targeted_left_multiply(\n matrix.reshape(val_qid_shape * 2),\n sub_args.target_tensor,\n sub_args.axes,\n out=sub_args.available_buffer,\n )\n return _incorporate_result_into_target(args, sub_args, sub_result)\n\n\ndef _strat_apply_unitary_from_unitary(\n unitary_value: Any, args: ApplyUnitaryArgs\n) -> Optional[np.ndarray]:\n # Check for magic method.\n method = getattr(unitary_value, '_unitary_', None)\n if method is None:\n return NotImplemented\n\n # Attempt to get the unitary matrix.\n matrix = method()\n if matrix is NotImplemented or matrix is None:\n return matrix\n\n return _apply_unitary_from_matrix(matrix, unitary_value, args)\n\n\ndef _strat_apply_unitary_from_decompose(val: Any, args: ApplyUnitaryArgs) -> Optional[np.ndarray]:\n operations, qubits, _ = _try_decompose_into_operations_and_qubits(val)\n if operations is None:\n return NotImplemented\n all_qubits = frozenset([q for op in operations for q in op.qubits])\n ancilla = tuple(sorted(all_qubits.difference(qubits)))\n if not len(ancilla):\n return apply_unitaries(operations, qubits, args, None)\n ordered_qubits = ancilla + tuple(qubits)\n all_qid_shapes = qid_shape_protocol.qid_shape(ordered_qubits)\n result = apply_unitaries(\n operations, ordered_qubits, ApplyUnitaryArgs.for_unitary(qid_shape=all_qid_shapes), None\n )\n if result is None or result is NotImplemented:\n return result\n result = result.reshape((np.prod(all_qid_shapes, dtype=np.int64), -1))\n val_qid_shape = qid_shape_protocol.qid_shape(qubits)\n state_vec_length = np.prod(val_qid_shape, dtype=np.int64)\n result = result[:state_vec_length, :state_vec_length]\n return _apply_unitary_from_matrix(result, val, args)\n\n\ndef apply_unitaries(\n unitary_values: Iterable[Any],\n qubits: Sequence['cirq.Qid'],\n args: Optional[ApplyUnitaryArgs] = None,\n default: Any = RaiseTypeErrorIfNotProvided,\n) -> Optional[np.ndarray]:\n \"\"\"Apply a series of unitaries onto a state tensor.\n\n Uses `cirq.apply_unitary` on each of the unitary values, to apply them to\n the state tensor from the `args` argument.\n\n CAUTION: if one of the given unitary values does not have a unitary effect,\n forcing the method to terminate, the method will not rollback changes\n from previous unitary values.\n\n Args:\n unitary_values: The values with unitary effects to apply to the target.\n qubits: The qubits that will be targeted by the unitary values. These\n qubits match up, index by index, with the `indices` property of the\n `args` argument.\n args: A mutable `cirq.ApplyUnitaryArgs` object describing the target\n tensor, available workspace, and axes to operate on. The attributes\n of this object will be mutated as part of computing the result. If\n not specified, this defaults to the zero state of the given qubits\n with an axis ordering matching the given qubit ordering.\n default: What should be returned if any of the unitary values actually\n don't have a unitary effect. If not specified, a TypeError is\n raised instead of returning a default value.\n\n Returns:\n If any of the unitary values do not have a unitary effect, the\n specified default value is returned (or a TypeError is raised).\n CAUTION: If this occurs, the contents of `args.target_tensor`\n and `args.available_buffer` may have been mutated.\n\n If all of the unitary values had a unitary effect that was\n successfully applied, this method returns the `np.ndarray`\n storing the final result. This `np.ndarray` may be\n `args.target_tensor`, `args.available_buffer`, or some\n other instance. The caller is responsible for dealing with\n this potential aliasing of the inputs and the result.\n\n Raises:\n TypeError: An item from `unitary_values` doesn't have a unitary effect\n and `default` wasn't specified.\n ValueError: If the number of qubits does not match the number of\n axes provided in the `args`.\n \"\"\"\n if args is None:\n qid_shape = qid_shape_protocol.qid_shape(qubits)\n args = ApplyUnitaryArgs.default(qid_shape=qid_shape)\n if len(qubits) != len(args.axes):\n raise ValueError('len(qubits) != len(args.axes)')\n qubit_map = {q.with_dimension(1): args.axes[i] for i, q in enumerate(qubits)}\n state = args.target_tensor\n buffer = args.available_buffer\n\n for op in unitary_values:\n indices = [qubit_map[q.with_dimension(1)] for q in op.qubits]\n result = apply_unitary(\n unitary_value=op, args=ApplyUnitaryArgs(state, buffer, indices), default=None\n )\n\n # Handle failure.\n if result is None:\n if default is RaiseTypeErrorIfNotProvided:\n raise TypeError(\n \"cirq.apply_unitaries failed. \"\n \"There was a non-unitary value in the `unitary_values` \"\n \"list.\\n\"\n \"\\n\"\n f\"non-unitary value type: {type(op)}\\n\"\n f\"non-unitary value: {op!r}\"\n )\n return default\n\n # Handle aliasing of results.\n if result is buffer:\n buffer = state\n state = result\n\n return state\n\n\ndef _incorporate_result_into_target(\n args: 'ApplyUnitaryArgs', sub_args: 'ApplyUnitaryArgs', sub_result: np.ndarray\n):\n \"\"\"Takes the result of calling `_apply_unitary_` on `sub_args` and\n copies it back into `args.target_tensor` or `args.available_buffer` as\n necessary to return the result of applying the unitary to the full args.\n Also swaps the buffers so the result is always in `args.target_tensor`.\n\n Args:\n args: The original args.\n sub_args: A version of `args` with transposed and sliced views of\n it's tensors.\n sub_result: The result of calling an object's `_apply_unitary_`\n method on `sub_args`. A transposed subspace of the desired\n result.\n\n Returns:\n The full result tensor after applying the unitary. Always\n `args.target_tensor`.\n\n Raises:\n ValueError: If `sub_args` tensors are not views of `args` tensors.\n\n \"\"\"\n if not (\n np.may_share_memory(args.target_tensor, sub_args.target_tensor)\n and np.may_share_memory(args.available_buffer, sub_args.available_buffer)\n ):\n raise ValueError(\n 'sub_args.target_tensor and subargs.available_buffer must be views of '\n 'args.target_tensor and args.available_buffer respectively.'\n )\n is_subspace = sub_args.target_tensor.size < args.target_tensor.size\n if sub_result is sub_args.target_tensor:\n return args.target_tensor\n if sub_result is sub_args.available_buffer:\n if is_subspace:\n # The subspace that was modified is likely much smaller than\n # the whole tensor so copy sub_result back into target_tensor.\n sub_args.target_tensor[...] = sub_result\n return args.target_tensor\n return args.available_buffer\n # The subspace that was modified is likely much smaller than\n # the whole tensor so copy sub_result back into target_tensor.\n # It's an uncommon case where sub_result is a new array.\n if np.may_share_memory(sub_args.target_tensor, sub_result):\n # Someone did something clever. E.g. implementing SWAP with a\n # reshape.\n # Copy to available_buffer instead.\n if is_subspace:\n args.available_buffer[...] = args.target_tensor\n sub_args.available_buffer[...] = sub_result\n return args.available_buffer\n sub_args.target_tensor[...] = sub_result\n return args.target_tensor\n\n\ndef _to_slice(subspace_def: Tuple[int, ...]):\n if len(subspace_def) < 1:\n raise ValueError(f'Subspace {subspace_def} has zero dimensions.')\n\n if len(subspace_def) == 1:\n return slice(subspace_def[0], subspace_def[0] + 1, 1)\n\n step = subspace_def[1] - subspace_def[0]\n for i in range(len(subspace_def) - 1):\n if subspace_def[i + 1] - subspace_def[i] != step:\n raise ValueError(f'Subspace {subspace_def} does not have consistent step size.')\n stop = subspace_def[-1] + step\n return slice(subspace_def[0], stop if stop >= 0 else None, step)\n","repo_name":"quantumlib/Cirq","sub_path":"cirq-core/cirq/protocols/apply_unitary_protocol.py","file_name":"apply_unitary_protocol.py","file_ext":"py","file_size_in_byte":29115,"program_lang":"python","lang":"en","doc_type":"code","stars":3974,"dataset":"github-code","pt":"77"} +{"seq_id":"37798725336","text":"\"\"\"\nURL configuration for core project.\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\n\nfrom reservation import views\nfrom user.views import student_login\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('users/', include('user.urls'), name='users'),\n path('reservations/', include('reservation.urls'), name='reservations'),\n path('rooms/', include('room.urls'), name='rooms'),\n path('payments/', views.payments, name='payments'),\n path('payments/new/', views.add_payment, name='add_payment'),\n path('payments/edit//', views.edit_payment, name='edit_payment'),\n path('payments/delete//', views.delete_payment, name='delete_payment'),\n path('', views.all_reservations, name='main'),\n]\n","repo_name":"robmainah/simple_pojects","sub_path":"hostel/core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"26197306791","text":"n=int(input())\nlst=list(map(int,input().split()))\nflag=1\nfor i in lst:\n cnt=0\n for j in lst:\n if i==j:\n cnt+=1\n if cnt==1:\n print(i, end=\" \")\n flag=0\nif flag:\n print(\"-1\")","repo_name":"manjunath269/codemind-python","sub_path":"Display_unique_values_in_an_Array.py","file_name":"Display_unique_values_in_an_Array.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"43047184334","text":"\nimport pymjin2\n\nclass CameraControllerComponentListener(pymjin2.ComponentListener):\n def __init__(self, parent):\n pymjin2.ComponentListener.__init__(self)\n self.parent = parent\n self.lastX = None\n self.lastY = None\n self.center = None\n def centerMouse(self):\n s = pymjin2.State()\n s.set(\"mouse.position\", self.center)\n v = self.center.split(\" \")\n self.lastX = int(v[0])\n self.lastY = int(v[1])\n self.parent.core.wnd.setState(s)\n def onComponentStateChange(self, st):\n #print \"CameraController.onComponentStateChange\"\n for key in st.keys:\n #print \"key\", key, \"value\", st.value(key)\n value = st.value(key)[0]\n if (key == self.parent.keyPos):\n self.parent.syncCameraWithNode(value)\n elif (key == self.parent.keyRot):\n self.parent.syncCameraWithNode(None, value)\n elif (key == \"camera.position\"):\n self.parent.syncNodeWithCamera(value)\n elif (key == \"camera.rotationq\"):\n self.parent.syncNodeWithCamera(None, value)\n elif (key == \"mouse.center\"):\n self.center = value\n elif (key == \"mouse.position\"):\n v = value.split(\" \")\n x = int(v[0])\n y = int(v[1])\n if (self.parent.enableRotation):\n deltaX = self.lastX - x\n deltaY = self.lastY - y\n self.parent.rotateNodeBy(deltaX, deltaY)\n self.centerMouse()\n else:\n self.lastX = x\n self.lastY = y\n\nclass CameraControllerUIActions(object):\n def __init__(self, parent):\n self.parent = parent\n def name(self):\n return \"CameraController\"\n def onUIActionsExecute(self, action, state):\n self.parent.processUIAction(action, state)\n\nclass CameraController(pymjin2.DSceneNodeScriptInterface):\n def __init__(self):\n pymjin2.DSceneNodeScriptInterface.__init__(self)\n self.mouseSensitivity = 0.1\n self.ignoreCameraSync = False\n self.enableRotation = False\n self.mouseCenter = None\n self.mouseLastX = None\n self.mouseLastY = None\n def __del__(self):\n pass\n def deinit(self):\n self.core.dscene.removeListener(self.componentListener)\n self.core.wnd.removeListener(self.componentListener)\n self.componentListener = None\n self.core.uiActions.removeListener(self.uiActions)\n self.uiActions = None\n def init(self, core, nodeName):\n self.core = core\n self.nodeName = nodeName\n self.keyPos = \"node.{0}.position\".format(nodeName)\n self.keyRot = \"node.{0}.rotationq\".format(nodeName)\n self.componentListener = CameraControllerComponentListener(self)\n self.core.dscene.addListener([self.keyPos,\n self.keyRot],\n self.componentListener)\n self.core.wnd.addListener(\n [\"camera.position\",\n \"camera.rotationq\",\n \"mouse.position\",\n \"mouse.center\"],\n self.componentListener)\n # Sync right after assignment.\n self.syncCameraWithNode()\n self.uiActions = CameraControllerUIActions(self)\n self.core.uiActions.addListener(self.uiActions)\n # Setup camera shortcuts.\n st = self.core.pini.load(\"camera.shortcuts\")\n self.core.uiActionsShortcuts.clear()\n self.core.uiActionsShortcuts.setState(st)\n self.core.uiActionsShortcuts.setGroupEnabled(\"CameraController\", True)\n def processUIAction(self, action, state):\n s = pymjin2.State()\n if (action == \"ToggleMove\"):\n self.enableRotation = state\n s.set(\"mouse.visible\", \"0\" if self.enableRotation else \"1\")\n # Disable all movement.\n if (not self.enableRotation):\n s.set(\"camera.moveBackward\", \"0\")\n s.set(\"camera.moveDown\", \"0\")\n s.set(\"camera.moveForward\", \"0\")\n s.set(\"camera.moveLeft\", \"0\")\n s.set(\"camera.moveRight\", \"0\")\n s.set(\"camera.moveUp\", \"0\")\n if (self.enableRotation):\n postfix = None\n if (action == \"MoveBackward\"):\n postfix = \"Backward\"\n elif (action == \"MoveDown\"):\n postfix = \"Down\"\n elif (action == \"MoveForward\"):\n postfix = \"Forward\"\n elif (action == \"MoveLeft\"):\n postfix = \"Left\"\n elif (action == \"MoveRight\"):\n postfix = \"Right\"\n elif (action == \"MoveUp\"):\n postfix = \"Up\"\n if (postfix):\n s.set(\"camera.move\" + postfix , \"1\" if state else \"0\")\n self.core.wnd.setState(s)\n def rotateNodeBy(self, dz, dx):\n keys = []\n keyx = \"node.{0}.rotationx\".format(self.nodeName)\n keyz = \"node.{0}.rotationz\".format(self.nodeName)\n if (dz != 0):\n keys.append(keyz)\n if (dx != 0):\n keys.append(keyx)\n if (len(keys)):\n st = self.core.dscene.state(keys)\n if (dx != 0):\n valuex = float(st.value(keyx)[0])\n diff = float(dx) * self.mouseSensitivity\n valuex += diff\n st.set(keyx, str(valuex))\n if (dz != 0):\n valuez = float(st.value(keyz)[0])\n diff = float(dz) * self.mouseSensitivity\n valuez += diff\n st.set(keyz, str(valuez))\n self.core.dscene.setState(st)\n def syncCameraWithNode(self, posValue = None, rotValue = None):\n if (self.ignoreCameraSync):\n return;\n # Position.\n newPosValue = posValue\n if (newPosValue is None):\n st = self.core.dscene.state([self.keyPos])\n newPosValue = st.value(self.keyPos)[0]\n # Rotation.\n newRotValue = rotValue\n if (newRotValue is None):\n st = self.core.dscene.state([self.keyRot])\n newRotValue = st.value(self.keyRot)[0]\n # Application.\n st = pymjin2.State()\n st.add(\"camera.position\", newPosValue)\n st.add(\"camera.rotationq\", newRotValue)\n self.core.wnd.setState(st)\n def syncNodeWithCamera(self, posValue = None, rotValue = None):\n # Position.\n newPosValue = posValue\n if (newPosValue is None):\n st = self.core.dscene.state([self.keyPos])\n newPosValue = st.value(self.keyPos)[0]\n # Rotation.\n newRotValue = rotValue\n if (newRotValue is None):\n st = self.core.dscene.state([self.keyRot])\n newRotValue = st.value(self.keyRot)[0]\n st = pymjin2.State()\n st.add(self.keyPos, newPosValue)\n st.add(self.keyRot, newRotValue)\n self.ignoreCameraSync = True\n self.core.dscene.setState(st)\n self.ignoreCameraSync = False\n\ndef create():\n return CameraController()\n\n","repo_name":"kornerr/default.ogs","sub_path":"scripts/CameraController.py","file_name":"CameraController.py","file_ext":"py","file_size_in_byte":7148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"38523451736","text":"from marketradar.utils.Exception import FilterError\nimport numpy as np\n\n#[温和放量上涨]\n#规则:\n#1.成交量相对于前一天放大\n#2.价格相对于前一天上涨\n#3.是否温和:每天的涨幅不能超过3%\n#[持续缩量下跌]\n#规则:\n#1.成交量相对于前一天缩小\n#2.价格相对于前一天下跌\ndef rule_1001(df, tag, ybts):\n if df.iloc[:,0].size != ybts+1:\n return False\n\n vol_series = df[\"VOTURNOVER\"] #成交量 列表\n pchg_series = df[\"PCHG\"] #涨幅 列表\n turnover_series = df[\"TURNOVER\"] #换手率 列表\n\n if tag == \"A\":\n #step.1\n for i in range(0,ybts):\n if (vol_series[i] / vol_series[i+1] < 1.0) or (vol_series[i] / vol_series[i+1] > 1.5):#如果最近几天不是温和放量,则不满足条件,返回False\n return False\n # step.2\n for i in range(0, ybts):\n if pchg_series[i] < 0 or pchg_series[i] > 3.0: # 如果最近几天股价不是稳步上涨或涨幅过大,则不满足条件,返回False\n return False\n\n if tag == \"B\":\n # step.1\n for i in range(0, ybts):\n if vol_series[i] / vol_series[i + 1] >= 1.0: # 如果最近几天成交量没有持续缩量,则不满足条件,返回False\n return False\n # step.2\n for i in range(0, ybts):\n if pchg_series[i] > 0: # 如果最近几天价格涨幅没有持续为负,则不满足条件,返回False\n return False\n # step.3\n for i in range(0, ybts):\n if turnover_series[i] > 1.2: # 换手率不能超过1.2%\n return False\n\n return True\n\n#[突放巨量]\n#规则:\n#2.今天的成交量是过去4天成交量的N倍\ndef rule_1002(df, multiple):\n if df.iloc[:,0].size != (5):\n return False\n\n series = df[\"VOTURNOVER\"]\n #step.2\n for i in range(0,4):\n if series[0]/series[i+1] < multiple:#放大天数内的每一天成交量都是巨量\n return False\n return True\n\n#[持续缩量后首次放量]\n#规则:\n\n#1.至少有slts天的换手率不高于1%\n#2.今日的成交量是前10天成交均量的multiple=2倍以上\n#3.今日的成交量是昨日的3倍以上,且今天收盘价是上涨的\ndef rule_1003(df, slts, multiple,turnover):\n if df.iloc[:,0].size != 20:\n return False\n\n vot_series = df[\"VOTURNOVER\"] #成交量\n pchg_series = df[\"PCHG\"] #涨幅\n #step.1\n if vot_series[0]/vot_series[1] < multiple:\n return False\n if pchg_series[0] <= 0:\n return False\n #step.2\n avg_vol = vot_series[1:11].sum()/10\n if vot_series[0]/avg_vol < multiple:\n return False\n #step.3 过去20日内的缩量天数至少有N天\n count = 0\n for i in range(1,20):\n if df.iloc[i].TURNOVER <= turnover: #当日换手率不超过1%\n count += 1\n if count < slts:\n return False\n\n return True\n\n#[换手率选股]\n#规则:\n#1.确定fdts放大天数\n#2.放大天数内每日成交量至少是放大前一日的multiple=7倍\ndef rule_1004(df, ybts, changehand):\n if df.iloc[:,0].size != ybts:\n return False\n\n series = df[\"TURNOVER\"]\n #step.2\n if series[0:ybts].sum() < changehand:\n return False\n return True\n\n#[启明星/十字启明星# ]\n#规则:\n#满足启明星的几个基本条件:\n#1.行情经过多日的下跌,K2日出现十字星线(收/开盘价一致)\n#2.K2相对K1的实体必须有向下跳空缺口(另外如果K3相对K2的实体也有向上跳空缺口则更佳)\n#3.K1成交量较小,预示下跌势头已经趋缓,K3成交量放大\ndef rule_2001(df, tag,throwBaby,k3up,vol_increase):\n if tag == '2d':\n if df.iloc[:, 0].size != 2:\n return False\n k2 = df.iloc[0] #今天 返回一个series 如果是iloc[0:0]返回的就是dataframe\n k1 = df.iloc[1] #昨天\n\n # 检查是否K1 K2 实体有向下跳空缺口\n if (k1['TCLOSE'] > k2['TCLOSE'] and k1['TCLOSE'] > k2['TOPEN'] and k1['TOPEN'] > k2['TCLOSE'] and k1['TOPEN'] > k2['TOPEN']) != True:\n return False\n\n # 检查是否为十字星\n if __isCrissStar(k2) != True:\n return False\n return True\n\n if tag == '3d':\n if df.iloc[:, 0].size != 3:\n return False\n k3 = df.iloc[0] # 今天 返回一个series 如果是iloc[0:0]返回的就是dataframe\n k2 = df.iloc[1] # 昨天 返回一个series 如果是iloc[0:0]返回的就是dataframe\n k1 = df.iloc[2] # 前天\n\n # 检查是否K1 K2 实体有向下跳空缺口\n if (k1['TCLOSE'] > k2['TCLOSE'] and k1['TCLOSE'] > k2['TOPEN'] and k1['TOPEN'] > k2['TCLOSE'] and k1['TOPEN'] > k2['TOPEN']) != True:\n return False\n # 检查是否K2 K3 实体有向上跳空缺口\n if (k3['TCLOSE'] > k2['TCLOSE'] and k3['TCLOSE'] > k2['TOPEN'] and k3['TOPEN'] > k2['TCLOSE'] and k3['TOPEN'] > k2['TOPEN']) != True:\n return False\n #如果k3日的最低价不能低于k2日的最低价\n if k3.LOW < k2.LOW:\n return False\n # 需要检查是否有向上跳空缺口(弃婴形态)\n if throwBaby == 'yes':\n if (k3.LOW >= k2['TCLOSE'] and k3.LOW >= k2['TOPEN']) != True:\n return False\n # 检查是否为十字星\n if __isCrissStar(k2) != True:\n return False\n # 需要检查K3成交量是否放大\n if vol_increase == 'yes':\n if k3.VOTURNOVER < k1.VOTURNOVER + k2.VOTURNOVER:\n return False\n #K3日股价大涨(相较K1形成刺透或看涨吞没形态)\n if k3up == 'yes':\n if __ctxt(k1,k3) != True or __kztmxt(k1,k3) != True:\n return False\n return True\n\n#[锤子线]\n#规则:\n#满足锤子线的几个基本条件:\n#1.行情经过多日的下跌\n#2.下影线越长越好\ndef rule_2003(df, tag, no_head):\n if df.iloc[:, 0].size != 5:\n return False\n\n if tag == 'A':\n k = df.iloc[0] # 今日锤子\n # 去掉一字涨跌停的股票\n if k.HIGH == k.LOW:\n return False\n # 实体和上影线长度不超过总的1/3\n if k.TCLOSE >= k.TOPEN:\n if (k.HIGH - k.LOW) / (k.TOPEN - k.LOW + 0.00001) > 1.5:\n return False\n elif k.TCLOSE < k.TOPEN:\n if (k.HIGH - k.LOW) / (k.TCLOSE - k.LOW + 0.00001) > 1.5:\n return False\n\n # 5天内是否持续下跌\n if __is_falling(df[0:]) != True:\n return False\n\n # 必须是光头阳线\n if no_head == 'yes':\n if k.TCLOSE != k.HIGH:\n return False\n if tag == 'B':\n k3 = df.iloc[0] #\n k = df.iloc[1] # 昨日是锤子\n\n # 去掉一字涨跌停的股票\n if k.HIGH == k.LOW:\n return False\n # 实体和上影线长度不超过总的1/3\n if k.TCLOSE >= k.TOPEN:\n if (k.HIGH - k.LOW) / (k.TOPEN - k.LOW + 0.00001) > 1.5:\n return False\n elif k.TCLOSE < k.TOPEN:\n if (k.HIGH - k.LOW) / (k.TCLOSE - k.LOW + 0.00001) > 1.5:\n return False\n # 5-1天内是否持续下跌\n if __is_falling(df[1:]) != True:\n return False\n # 必须是光头阳线\n if no_head == 'yes':\n if k.TCLOSE != k.HIGH:\n return False\n\n #第二天没有创新低\n if k3.LOW < k.LOW:\n return False\n #第二天收盘价高于前日的最高价\n if k3.TCLOSE < k.HIGH:\n return False\n\n return True\n\n\n#[看涨吞没形态]\n#规则:\n#满足锤子线的几个基本条件:\n#1.行情经过多日的下跌\n#2.相邻的两根K线,一根阴一根阳\n#3.K2实体完全吞没K1实体,(如果向前吞没更多则更更好)\n#4.K2的成交量比较大\ndef rule_2004(df, ybts):\n if df.iloc[:, 0].size != ybts:\n return False\n\n k2 = df.iloc[0] # 今日\n k1 = df.iloc[1] # 昨日\n #4\n if k2.VOTURNOVER < k1.VOTURNOVER * 1.5: #成交量放大低于1.5倍\n return False\n #1\n if __is_falling(df[1:]) != True:\n return False\n\n return __kztmxt(k1,k2)\n\n\n#[缺口]\ndef rule_2005(df, optionsRadios):\n if df.iloc[:, 0].size != 20:\n return False\n\n if optionsRadios == '_A':\n k2 = df.iloc[0] # 今日\n k1 = df.iloc[1] # 昨日\n\n if k2.LOW > k1.HIGH:\n return True\n if optionsRadios == '_B':\n for i in range(1, 20-1): #过去18天 最后一天不往下对比\n if df.iloc[i].LOW > df.iloc[i+1].HIGH : #找到向上跳空缺口,并且不是今日缺口\n LOWS = np.array(df.iloc[0:i].LOW)\n #print(df.iloc[0].CODE)\n #print(df.iloc[i].DAY)\n #print(df.iloc[i].LOW)\n #print(df.iloc[i+1].HIGH)\n #print((LOWS.min()))\n if LOWS.min() > df.iloc[i+1].HIGH: #如果后面几个交易日缺口始终没有没有完全补上\n if df.iloc[0].LOW < df.iloc[i+1].HIGH * 1.01: #今日收盘价格已经接近缺口位置,涨幅小于1%\n return True\n else:\n continue #找下一个缺口\n\n return False\n\n#[上行三法]\ndef rule_2006(df, optionsRadios):\n if df.iloc[:, 0].size != 5:\n return False\n\n for i in range(2,5):\n k = df.iloc[i]\n if k.PCHG > 4: #在过去10日内的某一日涨幅超过4个点,后面至少两日都是缩量调整\n if df.iloc[i-1].TCLOSE > k.LOW and df.iloc[i-1].TCLOSE < k.HIGH: #第二日出现下跌\n if df.iloc[i-2].TCLOSE < df.iloc[i-1].TCLOSE and df.iloc[i-2].LOW < df.iloc[i-1].LOW and df.iloc[i-2].LOW > k.TOPEN: #第三日继续下跌 但是最低价也不低于某日的开盘价\n if optionsRadios == 'yes': #之后又出现一跟大阳线并且突破前期大阳线的收盘价\n if max(df.iloc[0:i-1].TCLOSE) > k.TCLOSE:\n return True\n else:\n return False\n return True\n return False\n\n#[一阳穿多线]\ndef rule_3003(df, day):\n if df.iloc[:, 0].size != 3:\n return False\n\n k0 = df.iloc[0] # 今日\n k1 = df.iloc[1] # 昨日\n k2 = df.iloc[2] # 前日\n\n if 'today' in day:\n if k0.TCLOSE > k0.TOPEN: #收盘价高于开盘价\n if k0.TCLOSE > k0.MA5 and k0.TCLOSE > k0.MA10 and k0.TCLOSE > k0.MA20: #收盘价高于MA5\\10\\20\n if k0.TOPEN < k0.MA5 and k0.TOPEN < k0.MA10 and k0.TOPEN < k0.MA20: #开盘价低于MA5\\10\\20\n if k0.VOTURNOVER > k1.VOTURNOVER * 1.5: #成交量放大\n return True\n\n if 'yesterday' in day:\n if k1.TCLOSE > k1.TOPEN:\n if k1.TCLOSE > k1.MA5 and k1.TCLOSE > k1.MA10 and k1.TCLOSE > k1.MA20:\n if k1.TOPEN < k1.MA5 and k1.TOPEN < k1.MA10 and k1.TOPEN < k1.MA20:\n if k1.VOTURNOVER > k2.VOTURNOVER * 1.5: # 成交量放大\n if k0.TCLOSE > k0.MA5 and k0.TCLOSE > k0.MA10 and k0.TCLOSE > k0.MA20: #今日的成交量收在三根均线上方\n return True\n\n return False\n\n#[回落到均线附近]\ndef rule_3004(df, ma):\n if df.iloc[:, 0].size != 3:\n return False\n\n k0 = df.iloc[0] # 今日\n k1 = df.iloc[1] # 昨日\n k2 = df.iloc[2] # 前日\n\n if k0.LOW <= k1.LOW and k0.LOW <= k2.LOW : #过去三日每日最低价逐日下跌\n s = k0.TCLOSE if k0.TCLOSE < k0.TOPEN else k0.TOPEN\n if (s - k0.LOW)/ k0.TCLOSE > 0.01: #测量下影线的长度,要有明显的企稳痕迹(长下影线) 下影线长度超过1个点\n if ma == 5:\n if abs(k0.LOW - k0.MA5)/ k0.TCLOSE < 0.003 and k0.TCLOSE > k0.MA5 : #今日最低价落在MA5附近且今日收盘价高于MA5\n return True\n if ma == 10:\n if abs(k0.LOW - k0.MA10) / k0.TCLOSE < 0.003 and k0.TCLOSE > k0.MA10 :\n return True\n if ma == 20:\n if abs(k0.LOW - k0.MA20)/ k0.TCLOSE < 0.003 and k0.TCLOSE > k0.MA20 :\n return True\n return False\n\n#[历史底部]\ndef rule_4001(df, ybts):\n if df.iloc[:, 0].size != ybts:\n return False\n\n LOWS = np.array(df.iloc[0:ybts-1].LOW)\n\n min = LOWS.min()\n\n if (df.iloc[0].LOW - min) / min < 0.03:\n return True\n return False\n\n\n# 检查是否持续下跌\ndef __is_falling(df):\n LOWS = np.array(df['LOW'])\n if LOWS.min() != df.iloc[0].LOW: #完美的持续下跌形态中,最近一日LOW值应为最低值\n return False\n # 检查这几日是否持续下跌形态\n offset = 0\n i = 1\n while i < df.iloc[:,0].size:\n if df.iloc[i-1].LOW <= df.iloc[i].LOW:\n offset += 1\n i+=1\n if offset / df.iloc[:, 0].size < 0.57: # 如果走低天数/总天数>0.57 则认为是持续下跌形态\n return False\n return True\n\n\n#检查是否标准十字星\ndef __isCrissStar(k):\n v = k['TCLOSE'] / k['TOPEN']\n if v > 0.997 and v < 1.003:\n return True\n return False\n\n#检查是否为刺透形态\n##通常刺透形态 ka是阴线 kb是阳线, kb刺入越深越好\ndef __ctxt(ka,kb):\n if ka.PCHG <= 0 and kb.PCHG > 0:\n p = ka.TCLOSE + (ka.TOPEN-ka.TCLOSE)/2\n if kb.TCLOSE > p:\n return True\n return False\n\n#检查是否为看涨吞没形态\n#通常看涨吞没 ka是阴线 kb是阳线。\ndef __kztmxt(ka,kb):\n if ka.PCHG <= 0 and kb.PCHG >=0:\n return kb.TCLOSE > ka.TOPEN and kb.TOPEN <= ka.TCLOSE\n else:\n return False\n\nif __name__ == '__main__':\n a = 1.1\n b = 1.7\n c = 1.8\n d=1.9\n print(cb)\n","repo_name":"usaspy/project","sub_path":"marketradar/module/analyzer_engine.py","file_name":"analyzer_engine.py","file_ext":"py","file_size_in_byte":13870,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"42712136700","text":"#!/usr/bin/python3\n\nimport sys\nimport can\nimport time\n\nchannel = {}\nchannel['gps1'] = 7\nchannel['gps2'] = 11\nchannel['clkb'] = 12\nchannel['hkb'] = 13\n\nif len(sys.argv) > 3:\n busname = sys.argv[1]\n if(sys.argv[2] == 'all'):\n deviceList = ['gps1','gps2','hkb','clkb']\n else:\n deviceList = [sys.argv[2]]\n command = sys.argv[3]\nelse:\n print('usage: pdu on/off/state')\n print(' bus: {can0, can1}')\n print(' device: { gps1, gps2, hkb, clkb, all }')\n sys.exit()\n\nif (busname.lower() not in ['can0', 'can1']):\n print(f'E: bus {busname} not found')\n\nfor device in deviceList:\n if (channel.get(device) is None):\n print(f'E: device {device} not found')\n sys.exit(-1)\n\nif (command.lower() not in ['on', 'off', 'state']):\n print(f'E: command {command} not valid for device {deviceList}')\n sys.exit(-1)\n\nbus = can.Bus(interface=\"socketcan\", channel=busname, bitrate=250000)\n\n# state\n\nif (command.lower() == 'state'):\n for device in deviceList:\n msg = can.Message(arbitration_id=0x18efcf50, data=[0x25, 0x00, channel[device], 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], is_extended_id=True)\n bus.send(msg)\n ntry = 0\n while True:\n if(ntry == 5):\n print(f\"E: CAN response not received from {busname}\")\n sys.exit(-1)\n rep = bus.recv(2) # timeout 3 seconds\n if rep is not None:\n arbitrationId = hex(rep.arbitration_id)\n repid = rep.data[0]\n repch = rep.data[2]\n if(repid == 0x26 and repch == channel[device]):\n pwstatus = (rep.data[3] & 0x0C) >> 2\n print(f\"{device} is {'ON' if pwstatus else 'OFF'}\")\n break\n ntry = ntry + 1\n sys.exit(0) \n\n# power on / power off\n\nif (command.lower() == 'on'):\n power = 1\nelif (command.lower() == 'off'):\n power = 0\n\nfor device in deviceList:\n msg = can.Message(arbitration_id=0x18efcf50, data=[0x01, 0x40, channel[device], power, 0xFF, 0xFF, 0xFF, 0xFF], is_extended_id=True)\n\n try:\n bus.send(msg)\n print(f'{device} OK')\n except can.CanError:\n print(\"E: {device} CAN message not sent\")\n","repo_name":"gtortone/spb2-utils","sub_path":"pdu/pdu.py","file_name":"pdu.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"10168204659","text":"import cv2\r\nimport os\r\n\r\n# 选择第摄影机\r\ncap = cv2.VideoCapture(0)\r\n# 设定影像的尺寸大小\r\ncap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)\r\ncap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)\r\n\r\n# 读取资料夹资讯\r\nfile_path = 'E:\\\\training_data'\r\nall_file = os.listdir(file_path)\r\npic_num = len(all_file)\r\n\r\nwhile(True):\r\n # 从摄影机撷取一张影像\r\n ret, frame = cap.read()\r\n \r\n if cv2.waitKey(1) & 0xFF == ord('s'): # 若按下 s 键则拍照\r\n # 决定储存图片路径与名称\r\n pic_num = pic_num + 1\r\n output_path = file_path + '\\\\pic_' + str(pic_num) + '.jpg'\r\n # 储存图片\r\n cv2.imwrite(output_path, frame)\r\n # 拍照闪光效果,视觉辅助用\r\n #frame = cv2.convertScaleAbs(frame, alpha = 1, beta = 128)\r\n\r\n elif cv2.waitKey(1) & 0xFF == ord('q'): # 若按下 q 键则离开循环\r\n break\r\n \r\n # 显示图片\r\n cv2.imshow('frame', frame)\r\n\r\n# 释放摄影机\r\ncap.release()\r\n\r\n# 关闭所有 OpenCV 视窗\r\ncv2.destroyAllWindows()","repo_name":"tuosteven/foraminifera_detect","sub_path":"webcam_save_pic_button.py","file_name":"webcam_save_pic_button.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"9197101216","text":"import turtle\nfrom game import Game\nimport pandas\n\nscreen = turtle.Screen()\nscreen.title(\"US States Game\")\n\nimage = \"Us States Game/blank_states_img.gif\"\nscreen.addshape(image)\nturtle.shape(image)\n\ngame = Game()\n\n\n# while \ngame.correct_guess()\n# User Guess\n# guess = screen.textinput(title=\"Guess the state\",\n# prompt=\"What's another state name\").capitalize()\n# print(guess)\n\n# Read the csv file\n# data = pandas.read_csv(\"../../Documents/GITHUB/US States Game/50_states.csv\")\n\n\n# # Step 2\n# for state in data.state:\n# if state == guess:\n# print(\"Correct guess\")\n# game.correct_guess(guess)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nscreen.exitonclick()\n","repo_name":"wanicedude/Us-States-Game","sub_path":"main1.py","file_name":"main1.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"9071873759","text":"__license__ = 'GPL v3'\n__copyright__ = '2023, Kelly Larson'\n\n# Import m3u handling utilities\nfrom calibre_plugins.AudioM3U.m3u_utils import export_tags\n\nfrom calibre_plugins.AudioM3U.progress import ProgressBarWindow\n\nfrom qt.core import (QDialog, QVBoxLayout, QLabel, QListWidget, QListWidgetItem, QDialogButtonBox,\n QGridLayout, QPushButton)\nfrom PyQt5.QtCore import (Qt, QCoreApplication, QMetaObject)\n\nfrom calibre_plugins.AudioM3U.config import prefs\n\n\nclass ExportDialog(QDialog):\n\n def __init__(self, gui, icon, do_user_config):\n QDialog.__init__(self, gui)\n self.gui = gui\n self.do_user_config = do_user_config\n\n self.fields = [\"cover\", \"title\", \"author\", \"genre\", \"narrator\"]\n\n # The current database shown in the GUI\n # db is an instance of the class LibraryDatabase from db/legacy.py\n # This class has many, many methods that allow you to do a lot of\n # things. For most purposes you should use db.new_api, which has\n # a much nicer interface from db/cache.py\n self.db = gui.current_db\n self.initializeUI()\n\n def initializeUI(self):\n \"\"\"\n Initialize the window and display its contents to the screen\n \"\"\"\n self.setGeometry(100, 100, 500, 150)\n self.setWindowTitle('Export metadata')\n self.setupWidgets()\n\n def setupWidgets(self):\n \"\"\"\n Create widgets for metadata output GUI and arrange them in window\n \"\"\"\n # create grid layout\n self.verticalLayout = QVBoxLayout()\n self.verticalLayout.setObjectName(\"verticalLayout\")\n\n # Top Label\n self.top_label = QLabel(self)\n self.top_label.setObjectName(\"top_label\")\n self.verticalLayout.addWidget(self.top_label)\n\n # Field List Widget\n self.field_list = QListWidget(self)\n self.field_list.setObjectName(\"field_list\")\n self.field_list.setAlternatingRowColors(True)\n for item in self.fields:\n list_item = QListWidgetItem()\n list_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)\n list_item.setCheckState(Qt.Unchecked)\n list_item.setText(item)\n self.field_list.addItem(list_item)\n self.verticalLayout.addWidget(self.field_list)\n\n # Selection Button Grid\n self.gridLayout = QGridLayout()\n self.gridLayout.setContentsMargins(-1, 0, -1, -1)\n self.gridLayout.setObjectName(\"gridLayout\")\n self.nonePushButton = QPushButton(self)\n self.nonePushButton.setObjectName(\"nonePushButton\")\n self.gridLayout.addWidget(self.nonePushButton, 0, 1, 1, 1)\n self.allPushButton = QPushButton(self)\n self.allPushButton.setObjectName(\"allPushButton\")\n self.gridLayout.addWidget(self.allPushButton, 0, 0, 1, 1)\n self.defaultPushButton = QPushButton(self)\n self.defaultPushButton.setObjectName(\"defaultPushButton\")\n self.gridLayout.addWidget(self.defaultPushButton, 1, 0, 1, 1)\n self.setDefaultPushButton = QPushButton(self)\n self.setDefaultPushButton.setObjectName(\"setDefaultPushButton\")\n self.gridLayout.addWidget(self.setDefaultPushButton, 1, 1, 1, 1)\n self.verticalLayout.addLayout(self.gridLayout)\n\n self.nonePushButton.setText(\"Select None\")\n self.allPushButton.setText(\"Select All\")\n self.defaultPushButton.setText(\"Select Default\")\n self.setDefaultPushButton.setText(\"Set as Default\")\n\n # Dialog Button Box\n self.buttonBox = QDialogButtonBox(self)\n self.buttonBox.setOrientation(Qt.Horizontal)\n self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)\n self.buttonBox.setCenterButtons(True)\n self.buttonBox.setObjectName(\"buttonBox\")\n self.verticalLayout.addWidget(self.buttonBox)\n\n # Set the text fields\n self.retranslateUi(self)\n self.buttonBox.accepted.connect(self.accept) # type: ignore\n self.buttonBox.rejected.connect(self.reject) # type: ignore\n QMetaObject.connectSlotsByName(self)\n\n self.setLayout(self.verticalLayout)\n\n # Hide unenabled fields\n self.apply_settings()\n\n # Progress Bar Window\n self.progress_window = ProgressBarWindow()\n self.progress_window.cancel_button.clicked.connect(self.set_stop)\n self.stop_op = False\n\n # Connect button actions\n self.nonePushButton.clicked.connect(self.do_sel_none)\n self.allPushButton.clicked.connect(self.do_sel_all)\n self.defaultPushButton.clicked.connect(self.do_sel_default)\n self.setDefaultPushButton.clicked.connect(self.do_set_default)\n\n def set_stop(self):\n self.stop_op = True\n \n def do_sel_none(self):\n all_items = self.field_list.findItems('', Qt.MatchRegularExpression)\n for item in all_items:\n item.setCheckState(Qt.Unchecked)\n\n def do_sel_all(self):\n all_items = self.field_list.findItems('', Qt.MatchRegularExpression)\n for item in all_items:\n item.setCheckState(Qt.Checked)\n\n def do_sel_default(self):\n checked_items = prefs['import_selected']\n all_items = self.field_list.findItems('', Qt.MatchRegularExpression)\n for item in all_items:\n if item.text() in checked_items:\n item.setCheckState(Qt.Checked)\n else:\n item.setCheckState(Qt.Unchecked)\n\n def do_set_default(self):\n checked_items = []\n all_items = self.field_list.findItems('', Qt.MatchRegularExpression)\n for item in all_items:\n if ((not item.isHidden()) and (item.checkState() == Qt.Checked)):\n checked_items.append(item.text())\n prefs['import_selected'] = checked_items\n\n def accept(self):\n #print(\"ACCEPT!\")\n self.export_metadata()\n #self.setWindowTitle('Whassup!')\n super().accept()\n \n def retranslateUi(self, ImportDialog):\n _translate = QCoreApplication.translate\n ImportDialog.setWindowTitle(_translate(\"ExportDialog\", \"Export Metadata\"))\n self.top_label.setText(_translate(\"ExportDialog\", \"Metadata fields to export to audio files:\"))\n\n def is_checked(self, label):\n found = self.field_list.findItems(label, Qt.MatchExactly)\n if (len(found) != 1):\n return False\n if found[0].isHidden():\n return False\n #print(f\"{label} Found: {type(found)} {len(found)}\")\n return found[0].checkState() == Qt.Checked\n\n def trim_genre(self, input_genre):\n if isinstance(input_genre, str): # Handle a single string\n last_dot_index = input_genre.rfind('.')\n if last_dot_index != -1:\n return input_genre[last_dot_index + 1:]\n else:\n return input_genre\n elif isinstance(input_genre, list): # Handle a list of strings\n return [self.trim_genre(string) for string in input_genre]\n else:\n raise TypeError(\"Input genre must be a string or a list of strings.\")\n \n def get_audio_paths(self, book_id):\n db = self.db.new_api\n book_data = db.format(book_id, \"M3U\")\n m3u_text = book_data.decode(\"utf-8\")\n lines = m3u_text.splitlines()\n lines = [line for line in lines if ((line != \"\") and (line[0] != '#'))]\n return lines\n\n def export_metadata(self):\n '''\n Set the metadata in the files in the selected book's record to\n match the current metadata in the database.\n '''\n from calibre.ebooks.metadata.meta import set_metadata\n from calibre.gui2 import error_dialog, info_dialog\n\n # Get currently selected books\n rows = self.gui.library_view.selectionModel().selectedRows()\n if not rows or len(rows) == 0:\n return error_dialog(self.gui, 'Cannot update metadata',\n 'No books selected', show=True)\n # Map the rows to book ids\n ids = list(map(self.gui.library_view.model().id, rows))\n db = self.db.new_api\n m3u_ids = list(filter(lambda x: (db.has_format(x, \"M3U\")), ids))\n\n # Initialize progress bar window\n self.progress_window.progress_bar.setRange(0,len(m3u_ids)-1)\n self.progress_window.show()\n self.stop_op = False\n i = 0\n\n for book_id in m3u_ids:\n # Update progress bar\n self.progress_window.update_progress(i)\n i += 1\n if (self.stop_op): # Did we press 'cancel' from the progress bar?\n break\n \n # Get the paths for the audio files from the M3U file\n audio_file_paths = self.get_audio_paths(book_id)\n if (not len(audio_file_paths)):\n continue \n # Get the current metadata for this book from the db\n mi = db.get_metadata(book_id, get_cover=True, cover_as_data=True)\n # Now determine which fields, based on config and options, need to be updated\n export_fields = list(filter(lambda x: (self.is_checked(x)),self.fields))\n\n export_meta = {}\n #print(f\"export_fields: {export_fields}\")\n for field in export_fields:\n if ((field == \"author\") and (not mi.is_null(\"authors\"))):\n export_meta[\"author\"] = \" & \".join(mi.get(\"authors\"))\n if ((field == \"title\") and (not mi.is_null(\"title\"))):\n export_meta[\"title\"] = mi.get(\"title\")\n if (field == \"narrator\"):\n column = prefs['narrator']['column']\n if not mi.is_null(column):\n #print(f\"Getting narrator {column}: {mi.get(column)} type {type(mi.get(column))}\")\n # Support either ampersand separated names (list), or straight text field for narrator\n if type(mi.get(column)) == list:\n export_meta[\"narrator\"] = \" & \".join(mi.get(column))\n elif type(mi.get(column)) == str:\n export_meta[\"narrator\"] = mi.get(column)\n if (field == \"genre\"):\n column = prefs['genre']['column']\n if not mi.is_null(column):\n # Support either multiple genres (list), or straight text field for genre\n if (prefs['genre']['trim']):\n gen_export = self.trim_genre(mi.get(column))\n else:\n gen_export = mi.get(column)\n if type(gen_export) == list:\n export_meta[\"genre\"] = \", \".join(gen_export)\n #print(\"GENRE LIST\")\n elif type(gen_export) == str:\n export_meta[\"genre\"] = gen_export\n #print(\"GENRE STR\")\n if ((field == \"cover\") and (not mi.is_null(\"cover_data\"))):\n export_meta[\"cover\"] = mi.get(\"cover_data\")\n #print(f\"export_meta: {export_meta}\")\n export_tags(audio_file_paths, export_meta)\n \n # Hide the progress bar\n self.progress_window.hide()\n\n info_dialog(self, 'Updated audio files',\n f'Exported the metadata to the audio files for {i} of {len(ids)} book(s)',\n show=True)\n\n def apply_settings(self):\n all_items = self.field_list.findItems('', Qt.MatchRegularExpression) \n for field in all_items:\n if field.text() in (\"cover\", \"title\", \"author\"): # Never hidden\n continue\n field.setHidden(not prefs[field.text()]['enabled'])\n\n def config(self):\n self.do_user_config(parent=self)\n # Apply the changes\n self.label.setText(prefs['hello_world_msg'])\n","repo_name":"kelzan/AudioM3U","sub_path":"meta_out.py","file_name":"meta_out.py","file_ext":"py","file_size_in_byte":11920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"34509939453","text":"import os\n\nimport gradio as gr\nimport openai\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\n# Set OpenAI API key\nopenai.api_key = os.getenv(\"OPENAI_API_KEY\")\n\n\ndef get_sentiment(user_prompt, system_prompt=None):\n \"\"\"Summarize text using OpenAI's GPT-3 API.\n\n Args:\n user_prompt (str): Text to be classified.\n system_prompt (str): Instructions for summarizing text.\n\n Returns:\n prompt_and_response (dict): Dictionary containing the prompt and response.\n \"\"\"\n\n response = openai.ChatCompletion.create(\n model=\"gpt-3.5-turbo\",\n messages=[\n {\"role\": \"system\", \"content\": system_prompt},\n {\"role\": \"user\", \"content\": user_prompt},\n ],\n )\n\n prompt_and_response = {\n \"prompt\": user_prompt,\n \"response\": response.choices[0].message.content,\n }\n\n return prompt_and_response\n\n\ndef llm_response(message):\n # Create system prompt for LLM behavior\n instructions = \"Classify the following text as either 'positive', 'negative', or 'neutral': \"\n # adding more instructions to the system prompt such as few shot learning may improve the model's performance\n\n # Get prompt & response from Summarize function\n prompt_and_response = get_sentiment(message, instructions)\n\n response = prompt_and_response[\"response\"]\n\n return response\n\n\niface = gr.Interface(\n fn=llm_response,\n inputs=[\n \"text\",\n ],\n outputs=\"text\",\n live=False,\n)\n\nif __name__ == \"__main__\":\n\n iface.launch(debug=True)\n","repo_name":"sagecodes/llm-sentiment-classifier-openai","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"42610360548","text":"# import packages for framework part\nfrom django.shortcuts import render\nfrom rest_framework.views import APIView\nfrom django.conf import settings\nfrom django.http import JsonResponse\nimport base64\n# import the necessary packages for prediction\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.applications import imagenet_utils\nfrom PIL import Image\nimport numpy as np\nimport io\n\n\nclass Predict(APIView):\n\n def post(self, request, filename='lol', format=None):\n data = {\"success\": False}\n model = None\n\n def prepare_image(image, target):\n # if the image mode is not RGB, convert it\n if image.mode != \"RGB\":\n image = image.convert(\"RGB\")\n\n # resize the input image and preprocess it\n image = image.resize(target)\n image = img_to_array(image)\n image = np.expand_dims(image, axis=0)\n image = imagenet_utils.preprocess_input(image) # ResNet\n # return the processed image\n return image\n\n # ensure an image was properly uploaded to our endpoint\n if request.FILES.get(\"image\"):\n # read the image in PIL format\n image = request.FILES[\"image\"].read()\n image = Image.open(io.BytesIO(image))\n # preprocess the image and prepare it for classification\n image = prepare_image(image, target=(224, 224)) # for ResNet\n # Use already loaded model from settings\n model = settings.MODEL\n preds = model.predict(image)\n # After prediction\n results = imagenet_utils.decode_predictions(preds)\n data[\"predictions\"] = []\n # loop over the results and add them to the list of\n # returned predictions\n for (imagenetID, label, prob) in results[0]:\n r = {\"label\": label, \"probability\": float(prob)}\n data[\"predictions\"].append(r)\n\n # indicate that the request was a success\n data[\"success\"] = True\n\n return JsonResponse(data)","repo_name":"dmitriy-kisil/keras-prediction-examples","sub_path":"django_keras/keras_prediction/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"21600045725","text":"T = int(input())\nfor case in range(T):\n N = int(input())\n S = input()\n mdis = [float(\"inf\")] * N\n mp = float(\"inf\")\n for i in range(N):\n if S[i] == \"1\":\n mdis[i] = 0\n mp = i\n elif mp == float(\"inf\"):\n continue\n else:\n mdis[i] = min(mdis[i], i - mp)\n mp = float(\"inf\")\n for i in range(N-1,-1,-1):\n if S[i] == \"1\":\n mdis[i] = 0\n mp = i\n elif mp == float(\"inf\"):\n continue\n else:\n mdis[i] = min(mdis[i], mp - i)\n print(f\"Case #{case+1}: {sum(mdis)}\")","repo_name":"Programmerryoki/Competitive-Programming","sub_path":"Google Kick Start/F 2021/Trash Bins.py","file_name":"Trash Bins.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"32019227989","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread('Paris.jpg')\nheight, width = img.shape[:2]\ny = np.ones((height, width), np.uint8) * 128\noutput = np.zeros((height, width), np.uint8)\n# generating the kernels\nkernel1 = np.array([[0, -1, -1], # kernel for embossing bottom left side\n [1, 0, -1],\n [1, 1, 0]])\nkernel2 = np.array([[-1, -1, 0], # kernel for embossing bottom right side\n [-1, 0, 1],\n [0, 1, 1]])\n# you can generate kernels for embossing top as well\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\noutput1 = cv2.add(cv2.filter2D(gray, -1, kernel1), y) # emboss on bottom left side\noutput2 = cv2.add(cv2.filter2D(gray, -1, kernel2), y) # emboss on bottom right side\nfor i in range(height):\n for j in range(width):\n output[i, j] = max(output1[i, j], output2[i, j]) # combining both embosses to produce stronger emboss\ncv2.imshow(\"Image\", img)\ncv2.imshow(\"Output1\", output1)\ncv2.imshow(\"Output2\", output2)\ncv2.imshow(\"Output\", output)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","repo_name":"yojulab/learn_computervision","sub_path":"codes/embossings.py","file_name":"embossings.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":"17308320081","text":"from django.urls import path\n\nfrom . import views\n\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"wiki/\", views.get_entry, name=\"get_entry\"),\n path(\"search/\", views.search, name=\"search\"),\n path(\"create_page/\", views.create_page, name=\"create_page\"),\n path(\"edit/\", views.edit, name=\"edit\"),\n path(\"random\", views.random, name=\"random\")\n]\n","repo_name":"limjp/CS50-Web-Dev","sub_path":"Week 3/wiki/encyclopedia/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"71926198328","text":"from openpyxl import Workbook\r\nfrom openpyxl import load_workbook\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport re\r\nimport urllib.parse as up\r\n\r\nheaders = {'Accept': '*/*',\r\n 'Accept-Language': 'en-US,en;q=0.8',\r\n 'Cache-Control': 'max-age=0',\r\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome'\r\n '/48.0.2564.116 Safari/537.36',\r\n 'Connection': 'keep-alive',\r\n 'Referer': 'http://www.baidu.com/'\r\n }\r\nheaders2 = {\r\n \"Proxy-Connection\": \"keep-alive\",\r\n \"Pragma\": \"no-cache\",\r\n \"Cache-Control\": \"no-cache\",\r\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome\"\r\n \"/52.0.2743.116 Safari/537.36\",\r\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\r\n \"DNT\": \"1\",\r\n \"Accept-Encoding\": \"gzip, deflate, sdch\",\r\n \"Accept-Language\": \"zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4\",\r\n \"Referer\": \"https://www.baidu.com/s?wd=%BC%96%E7%A0%81&rsv_spt=1&rsv_iqid=0x9fcbc99a0000b5d7&issp=1\"\r\n \"&f=8&rsv_bp=1&rsv_idx=2&ie=utf-8&rqlang=cn&tn=baiduhome_pg&rsv_enter=0&oq=If-None-Match\"\r\n \"&inputT=7282&rsv_t=3001MlX2aUzape9perXDW%2FezcxiDTWU4Bt%2FciwbikdOLQHYY98rhPyD2LDNevDKyLLg2\"\r\n \"&rsv_pq=c4163a510000b68a&rsv_sug3=24&rsv_sug1=14&rsv_sug7=100&rsv_sug2=0&rsv_sug4=7283\",\r\n \"Accept-Charset\": \"gb2312,gbk;q=0.7,utf-8;q=0.7,*;q=0.7\",\r\n }\r\nhds = [{'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'},\r\n {'User-Agent':'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/535.11 (KHTML, like Gecko) Chrome'\r\n '/17.0.963.12 Safari/535.11'},\r\n {'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)'}]\r\n\r\n\r\n# 获取按类别的全部单页基础爬虫用链接,返回2维列表\r\ndef urls_get(lists):\r\n urls_list = []\r\n tags_list = lists\r\n for tag in tags_list:\r\n url_list = []\r\n url_list.append(tag)\r\n urls_tag = 'https://www.douban.com/tag/' + up.quote(tag) + '/book'\r\n for i in range(2):\r\n url = urls_tag + '?start=' + str(i*15)\r\n url_list.append(url)\r\n urls_list.append(url_list)\r\n return urls_list\r\n\r\n\r\n# 接受2维列表作为参数,对其中每一类别的单页链接进行提取并处理爬取得到信息,调用存储函数进行保存\r\ndef deal(urls):\r\n count_sheet = 0\r\n wb = Workbook()\r\n for i in range(len(urls)):\r\n count = 0\r\n books_list = []\r\n for url in urls[i]:\r\n if count == 0:\r\n count += 1 # 跳过第一个tag标签:书籍类别\r\n continue\r\n else:\r\n r = requests.get(url, headers=headers2)\r\n r_bs = BeautifulSoup(r.text, features='lxml')\r\n html_tag = re.compile(r']+>')\r\n attr = r_bs.find_all('dl')\r\n\r\n # 以一本书为独立单元进行属性列表的构建,对传入的链接参数(单页)进行for循环遍历即可获得单页上的所有书信息列表\r\n for one in attr:\r\n one_list = []\r\n\r\n # 书名----0\r\n title_ini = one.find('a', 'title')\r\n title_str = str(title_ini)\r\n title_sub = html_tag.sub('', title_str)\r\n one_list.append(title_sub)\r\n\r\n # 评分----1\r\n rating_ini = one.find('span', 'rating_nums')\r\n rating_str = str(rating_ini)\r\n rating_sub = html_tag.sub('', rating_str)\r\n one_list.append(rating_sub)\r\n\r\n # 价格,出版日期,出版社,作者----2 3 4 5\r\n four_ini = one.find('div', 'desc')\r\n four_str = str(four_ini)\r\n four_sub = html_tag.sub('', four_str)\r\n four_strip = four_sub.strip(' \\n')\r\n four_split = re.split(' / ', four_strip)\r\n one_list.append(four_split[-1])\r\n one_list.append(four_split[-2])\r\n one_list.append(four_split[-3])\r\n one_list.append(four_split[0])\r\n\r\n # 评论人数----6\r\n href_ini = one.find('a').get('href')\r\n r_href = requests.get(href_ini, headers=headers2)\r\n r_href_bs = BeautifulSoup(r_href.text, features='lxml')\r\n critic_ini = r_href_bs.find('span', {'property': 'v:votes'})\r\n critic_str = str(critic_ini)\r\n critic_sub = html_tag.sub('', critic_str)\r\n one_list.append(critic_sub)\r\n\r\n # 添加到总列表\r\n books_list.append(one_list)\r\n count += 1\r\n\r\n # 调用内部存储函数对爬取的单标签结果list进行存储到excel\r\n if count_sheet == 0:\r\n ws = wb.create_sheet(urls[i][0])\r\n for j in range(len(books_list)):\r\n ws.append(books_list[j])\r\n wb.save('books.xlsx')\r\n else:\r\n wb = load_workbook('books.xlsx')\r\n wb.create_sheet(urls[i][0]).append(books_list)\r\n ws = wb.create_sheet(urls[i][0])\r\n for j in range(len(books_list)):\r\n ws.append(books_list[j])\r\n wb.save('books.xlsx')\r\n wb.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n tags_str = input('请输入需要下载的图书类别(用,隔开):')\r\n tags_list = tags_str.split(',')\r\n urls = urls_get(tags_list)\r\n deal(urls)\r\n","repo_name":"DDDAZ/study","sub_path":"book_crawl_douban.py","file_name":"book_crawl_douban.py","file_ext":"py","file_size_in_byte":5899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"17455436253","text":"import os\nimport cv2\nimport dlib\nimport shutil\nimport argparse\nimport cv_tools\nfrom pathlib import Path\nfrom face_128D import FaceFeatureTo128D\n\n\nclass FaceRegisterTool:\n \"\"\"\n 注册人脸,保存到地址的路径\n \"\"\"\n\n def __init__(self, save_path='./faces'):\n \"\"\"\n param: save_path 人脸图片保存路径\n \"\"\"\n self.save_path = save_path\n self.detector = dlib.get_frontal_face_detector()\n self.face128D = FaceFeatureTo128D(self.save_path)\n self.prepare()\n\n\n def prepare(self):\n \"\"\"\n 注册之前先清理 save_path 目录确保下面没有其他文件\n \"\"\"\n path = Path(self.save_path)\n if not path.exists():\n os.makedirs(self.save_path)\n else:\n print('rm %s' % self.save_path)\n shutil.rmtree(self.save_path)\n os.makedirs(self.save_path)\n \n\n def has_faces(self, image, data):\n \"\"\"\n param:image\n param:data\n \"\"\"\n left = 0\n rigth = 0\n bottom = 0\n top = 0\n faces = len(data)\n if not faces:\n cv_tools.putText(image, \"No face was detected!\", color=(0, 0, 255))\n for _, face in enumerate(data):\n # 拿到面部的位置\n left = face.left()\n rigth = face.right()\n top = face.top()\n bottom = face.bottom()\n # rectangle函数 绘制面部的区域\n cv2.rectangle(image, pt1=(left, top), pt2=(rigth, bottom), color=(0, 255, 0), thickness=2)\n\n def add_face_from_image(self, image):\n \"\"\"\n 注册人脸(图片方式)\n \"\"\"\n imdata = cv2.imread(image)\n rgb_image = cv_tools.bgr2rgb(imdata)\n faces = self.detector(rgb_image, 1)\n if len(faces) == 0:\n print(\"No face was detected!: %s\" % image)\n return\n elif len(faces) > 1:\n print(\"Too many face\")\n return\n\n else:\n shutil.copy2(image, self.save_path)\n self.face128D.faces_to_128D()\n\n def add_face_from_camera(self):\n \"\"\"\n 注册人脸(摄像头方式)\n \"\"\"\n frames = cv_tools.read_camera0()\n count = 0\n for frame in frames:\n image_rgb = cv_tools.bgr2rgb(frame)\n title = 'Register'\n press = cv2.waitKey(2)\n data = self.detector(image_rgb)\n if len(data) == 0:\n cv_tools.putText(frame, \"No face was detected!\", color=(0, 0, 255))\n if press == ord('q'):\n break\n if press == ord('a'):\n if len(data) == 0:\n cv_tools.putText(frame, \"No face was detected!\", color=(0, 0, 255))\n elif len(data) > 1:\n cv_tools.putText(frame, \"Too many face!\", color=(0, 0, 255))\n else:\n count += 1\n impath = Path(self.save_path).joinpath('%s.jpg' % count)\n print(\"save picture %s\" % impath)\n cv2.imwrite(str(impath), frame)\n self.has_faces(frame, data)\n cv_tools.putText(frame, 'a:Add', location=(40, 300))\n cv_tools.putText(frame, 'q:Quit', location=(40, 350))\n cv_tools.putText(frame, 'save count:%s' % count, location=(40, 400), size=1.0)\n cv2.imshow(title, frame)\n cv2.destroyAllWindows()\n self.face128D.faces_to_128D()\n\n def run(self):\n \"\"\"\n \"\"\"\n parse = argparse.ArgumentParser(description=\"face recognition tools\")\n parse.add_argument('-t', '--type', required=True, choices=['0', '1'], help=\"face recognition type: 0(image), 1(camera)\")\n parse.add_argument('-i', '--image', required=False, help=\"image path\")\n args = parse.parse_args()\n if args.type == '0':\n img = args.image\n if not img:\n print(\"face register from image need a image not None\")\n return\n if not os.path.exists(img):\n print(\"image not exists %s\" % img)\n return\n else:\n self.add_face_from_image(img)\n else:\n self.add_face_from_camera()\n\nif __name__ == '__main__':\n save_path = './faces'\n img = '/home/fantasy/faces/harden1.jpeg'\n tools = FaceRegisterTool(save_path)\n # tools.add_face_from_camera()\n # tools.add_face_from_image(img)\n tools.run()","repo_name":"pythondever/face-recognition","sub_path":"cv/face_register.py","file_name":"face_register.py","file_ext":"py","file_size_in_byte":4475,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"77"} +{"seq_id":"19688792608","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Created by Z Lei on 2019-10-19.\n\n\narray = [\n [1, 2, 3, 4, 5, 6],\n [7, 8, 9, 10, 11, 12],\n [13, 14, 15, 16, 17, 18]\n]\n\n\ndef hui_print(array):\n if len(array) == 0:\n return\n\n start_r = 0\n start_c = 0\n end_r = len(array) - 1\n end_c = len(array[0]) - 1\n\n while (start_r <= end_r and start_c <= end_c):\n xx_print(array, start_r, start_c, end_r, end_c)\n start_r += 1\n start_c += 1\n end_r -= 1\n end_c -= 1\n\n\ndef xx_print(array, start_r, start_c, end_r, end_c):\n if start_r == end_r:\n\n while (start_c <= end_c):\n print(array[start_r][start_c])\n start_c += 1\n\n elif start_c == end_c:\n while (start_r <= end_r):\n print(array[start_r][start_c])\n start_r += 1\n\n\n else:\n\n cur_r = start_r\n cur_c = start_c\n\n while cur_c < end_c:\n print(array[cur_r][cur_c])\n cur_c += 1\n\n while cur_r < end_r:\n print(array[cur_r][cur_c])\n cur_r += 1\n\n while cur_c > start_c:\n print(array[cur_r][cur_c])\n cur_c -= 1\n\n while cur_r > start_r:\n print(array[cur_r][cur_c])\n cur_r -= 1\n\n\nhui_print(array)\n","repo_name":"Zidoing/programer_interview_guide","sub_path":"print_array.py","file_name":"print_array.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"32655372708","text":"# simply moving the drone\n#\nimport numpy as np\nimport gym\nimport time\nimport random\nimport airsim\n\n\n\ndef test():\n\tclient = airsim.MultirotorClient(ip=\"127.0.0.1\")\n\tclient.confirmConnection()\n\tclient.enableApiControl(True)\n\tclient.armDisarm(True)\n\n\tclient.moveByVelocityAsync(0, 0, -1, 3).join()\n\ttry:\n\t\tfor each in range(0,1000):\n\t\t\tpitch = random.uniform(-0.25,0.25)\n\t\t\tx = random.uniform(-3.0,5.0)\n\t\t\ty = random.uniform(-3.0,5.0)\n\t\t\tyaw = random.uniform(0,360)\n\t\t\t#print(\"step:\"+str(each)+\"[\"+str(pitch)+\",\"+str(roll)+\",\"+str(yaw)+\"]\")\n\t\t\t#client.moveByAngleZAsync(pitch, roll, -6, yaw, 0.3).join()\n\t\t\t#client.moveByVelocityZAsync(vx, vy, -6, 0.25, 1, yaw_mode=airsim.YawMode(False,0)).join()\n\t\t\tclient.moveToPositionAsync(x, y, -6, 1, yaw_mode=airsim.YawMode(False, 0)).join()\n\t\tclient.reset()\n\texcept KeyboardInterrupt:\n\t\tclient.reset()\n\n\n\ttime.sleep(1)\n\n\ntest()\n","repo_name":"harvard-edge/airlearning-rl","sub_path":"test_suites/move.py","file_name":"move.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"77"} +{"seq_id":"7355357742","text":"from sklearn.metrics import f1_score\r\nimport re\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nimport argparse\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"--input-model-truth\", help=\"comma separated file with an input and output row\")\r\n parser.add_argument(\"--input-predictions\", args=\"+\", help=\"comma separated file with an input and output row\")\r\n parser.add_argument(\"--output\", help=\"the text file to save the accuracy data into\")\r\n\r\n args = parser.parse_args()\r\n\r\n y_true = pd.read_csv(args.input_model_truth)\r\n test_offY_val = list(y_true[\"offensiveYN\"])\r\n\r\n for i in range(len(args.input_predictions)):\r\n y_pred = pd.read_csv(args.input_predictions[i], index_col=0)\r\n\r\n y_pred.columns = [\"input\", \"generated\"]\r\n\r\n pred_offY_val = [0 if string.contains(\"OffY\") else 1 for string in list(y_pred[\"generated\"])]\r\n\r\n\r\n assert pred_offY_val == test_offY_val\r\n\r\n sum_int = sum(pred_offY_val == test_offY_val)\r\n\r\n accuracy_score = sum_int / len(test_offY_val)\r\n\r\n f1_val = f1_score(pred_offY_val, test_offY_val)\r\n\r\n with open(args.output[i], 'w') as f:\r\n f.write(\"sum of the Offensive YN: \\n\" + str(sum_int))\r\n f.write(\"raw accuracy of the Offensive YN: \\n\" + str(accuracy_score))\r\n f.write(\"f1 accuracy score of Offensive YN: \\n\" + str(f1_val))\r\n\r\n f.close()","repo_name":"nandsra21/NLPProject","sub_path":"old_scripts/accuracy_offNvsY.py","file_name":"accuracy_offNvsY.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"19159026631","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Predicting Migration Rate\n\n# The objective of this project is to develop a machine learning model that can accurately predict migration rates based on various socio-economic and demographic factors.\n\n# # Importing Libraries\n\n# These are just a few examples of popular Python libraries. You can import any other library using the same import statement followed by the library name or alias:\n# \n# NumPy: for numerical operations and array manipulation\n# \n# Pandas: for data manipulation and analysis\n# \n# Matplotlib: for creating visualizations\n# \n# Scikit-learn: for machine learning algorithms\n\n# In[1]:\n\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In[2]:\n\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n# # Importing Dataset\n\n# In[3]:\n\n\ndataframe = pd.read_csv('migration_nz.csv')\n\n\n# # Data Exploration\n\n# Data exploration is an essential step in the data analysis process. It involves examining and understanding the data to gain insights, identify patterns, and make informed decisions. \n\n# In[4]:\n\n\ndataframe.head()\n\n\n# In[5]:\n\n\ndataframe.tail()\n\n\n# In[6]:\n\n\ndataframe.shape\n\n\n# In[7]:\n\n\ndataframe.info()\n\n\n# In[8]:\n\n\ndataframe.columns\n\n\n# In[9]:\n\n\ndataframe['Measure'].unique()\n\n\n# In[10]:\n\n\nprint(dataframe['Measure'])\n\n\n# In[11]:\n\n\ndataframe['Measure'].replace(\"Arrivals\", 0, inplace = True)\ndataframe['Measure'].replace(\"Departures\", 1, inplace = True)\ndataframe['Measure'].replace(\"Net\", 2, inplace = True)\n\n\n# In[12]:\n\n\ndataframe['Measure'].value_counts()\n\n\n# In[13]:\n\n\ndataframe.columns\n\n\n# In[14]:\n\n\ndataframe['Country'].unique()\n\n\n# In[16]:\n\n\ndataframe['CountryID'] = pd.factorize(dataframe.Country)[0]\ndataframe['CitID'] = pd.factorize(dataframe.Citizenship)[0]\n\n\n# In[18]:\n\n\ndataframe['CountryID'].unique()\n\n\n# # Imputing Missing Values\n\n# In[20]:\n\n\ndataframe.isnull().sum()\n\n\n# In[22]:\n\n\ndataframe[\"Value\"].fillna(dataframe[\"Value\"].median(),inplace=True)\n\n\n# In[23]:\n\n\ndataframe.isna().sum().any()\n\n\n# In[24]:\n\n\ndataframe.drop('Country', axis=1, inplace=True)\ndataframe.drop('Citizenship', axis=1, inplace=True)\n\n\n# # Splitting Dataset\n\n# Splitting a dataset refers to the process of dividing a given dataset into two or more subsets for training and evaluation purposes. The most common type of split is between the training set and the testing (or validation) set. This division allows us to assess the performance of a machine learning model on unseen data and evaluate its generalization capabilities.\n# \n# Train-Test Split: This is the most basic type of split, where the dataset is divided into a training set and a testing set. The training set is used to train the machine learning model, while the testing set is used to evaluate its performance. The split is typically done using a fixed ratio, such as 70% for training and 30% for testing.\n\n# In[25]:\n\n\nfrom sklearn.model_selection import train_test_split\n\n\n# In[28]:\n\n\nX = dataframe[['CountryID', 'Measure', 'Year', 'CitID']].values\nY = dataframe['Value'].values\n\n\n# In[31]:\n\n\nX.shape, Y.shape\n\n\n# In[32]:\n\n\nX_train, X_test, Y_train, Y_test = train_test_split(X, \n Y, \n test_size = 0.3, \n random_state = 42)\n\n\n# In[33]:\n\n\nX_train.shape, X_test.shape, Y_train.shape, Y_test.shape\n\n\n# # Random Forest Regressor\n\n# Random Forest Regressor is a machine learning algorithm that is based on the Random Forest ensemble method and used for regression tasks. It is an extension of the Random Forest Classifier, but instead of predicting categorical variables, it predicts continuous numeric values.\n\n# In[35]:\n\n\nfrom sklearn.ensemble import RandomForestRegressor\nmodel = RandomForestRegressor(n_estimators=70,max_features = 3,max_depth=5,n_jobs=-1)\nmodel.fit(X_train ,Y_train)\nmodel.score(X_test, Y_test)\n\n\n# # Migration Rate\n\n# In[39]:\n\n\nX = dataframe[['CountryID','Measure','Year','CitID']]\nY = dataframe['Value']\nX_train, X_test, y_train, y_test = train_test_split(\n X, Y, test_size=0.3, random_state=9)\ngrouped = dataframe.groupby(['Year']).aggregate({'Value' : 'sum'})\n\n\ngrouped.plot(kind='line');plt.axhline(0, color='g')\nplt.show()\n\n\n# In[41]:\n\n\ncorr = dataframe.corr()\n\n\n# In[42]:\n\n\ncorr\n\n\n# In[44]:\n\n\nsns.heatmap(corr, \n xticklabels=corr.columns.values,\n yticklabels=corr.columns.values)\nplt.show()\n\n","repo_name":"ranzeet013/Machine_Learning_Projects","sub_path":"Migration Prediction/Predicting Migration Rate.py","file_name":"Predicting Migration Rate.py","file_ext":"py","file_size_in_byte":4514,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"4895169886","text":"from django import forms\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.gis.forms import PointField\nfrom django.contrib.gis.geos import Point\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import ugettext as _\n\nfrom services.models import Provider, Service, SelectionCriterion, ServiceType, ServiceArea, \\\n ProviderType\n\n\ndef try_to_get_one(model, **query_kwargs):\n \"\"\"\n Return the best match instance of `model` using as many of the given\n query args as we can. Returns None if we can't find a combination of\n the args that gives us exactly one result.\n :param model:\n :param query_kwargs:\n :return:\n \"\"\"\n # If all the args gives us one result, use it.\n qset = model.objects.filter(**query_kwargs)\n if qset.count() == 1:\n return qset[0]\n if qset.count() > 1:\n # We got more than one result even using all the args, so\n # it's hopeless. Removing args cannot get us down to 1 result.\n return None\n\n # Start a breadth-first search for a workable combination.\n # First try all the ways of dropping one of the kwargs.\n # If we're not successful, then start calling this recursively,\n # each time starting by dropping a different arg.\n\n # Try dropping just one\n keys = query_kwargs.keys()\n if len(keys) <= 1:\n return None\n for key_to_omit in keys:\n kwargs_to_use = dict(query_kwargs)\n del kwargs_to_use[key_to_omit]\n qset = model.objects.filter(**kwargs_to_use)\n if qset.count() == 1:\n return qset[0]\n # No luck - recurse\n for key_to_omit in keys:\n kwargs_to_use = dict(query_kwargs)\n del kwargs_to_use[key_to_omit]\n result = try_to_get_one(model, **kwargs_to_use)\n if result:\n return result\n\n\n# We're using form widgets to adapt from the values coming from\n# the imported spreadsheet object to the values that Django\n# would commonly expect in a form submission.\n\nclass ProviderTypeWidget(forms.Widget):\n def value_from_datadict(self, data, files, name):\n \"\"\"\n Find the relevant provider type record and return its ID\n\n Try to allow exact specification of a type but be forgiving\n if they misspell a field or two or leave some blank and the\n rest is still enough to identify a unique provider type:\n \"\"\"\n provider_type = try_to_get_one(\n ProviderType,\n number=data['type__number'],\n name_en=data['type__name_en'],\n name_ar=data['type__name_ar'],\n name_fr=data['type__name_fr'])\n if provider_type:\n return provider_type.id\n\n\nclass UserWidget(forms.Widget):\n def value_from_datadict(self, data, files, name):\n User = get_user_model()\n return User.objects.get(email__iexact=data['email']).id\n\n\nclass ProviderForm(forms.ModelForm):\n # Validate provider data as imported in an Excel spreadsheet edited from an export\n type = forms.ModelChoiceField(\n queryset=ProviderType.objects.all(),\n widget=ProviderTypeWidget\n )\n user = forms.ModelChoiceField(\n queryset=get_user_model().objects.all(),\n widget=UserWidget\n )\n\n class Meta:\n model = Provider\n # Setting fields to '__all__' here is reasonably safe since we\n # are careful elsewhere to only export and import certain fields.\n fields = '__all__'\n\n\nclass ServiceTypeWidget(forms.Widget):\n # Widget that looks up a service type object from\n # the type__name_en, type__name_ar, and type__name_fr fields\n # in the provided data.\n def value_from_datadict(self, data, files, name):\n \"\"\"\n Given a dictionary of data and this widget's name, returns the value\n of this widget. Returns None if it's not provided.\n \"\"\"\n service_type = try_to_get_one(\n ServiceType,\n name_en=data['type__name_en'],\n name_ar=data['type__name_ar'],\n name_fr=data['type__name_fr'],\n )\n if service_type:\n return service_type.id\n raise ValidationError(_('There is no service type with English name %r')\n % data['type__name_en'])\n\n\nclass ServiceAreaWidget(forms.Widget):\n # Like ServiceTypeWidget but for ServiceArea\n def value_from_datadict(self, data, files, name):\n \"\"\"\n Given a dictionary of data and this widget's name, returns the value\n of this widget. Returns None if it's not provided.\n \"\"\"\n try:\n return ServiceArea.objects.get(\n name_en=data['area_of_service__name_en'],\n name_ar=data['area_of_service__name_ar'],\n name_fr=data['area_of_service__name_fr'],\n ).id\n except ServiceArea.DoesNotExist:\n raise ValidationError(_('There is no service area with English name %r')\n % data['area_of_service__name_en'])\n\n\nclass ProviderWidget(forms.Widget):\n def value_from_datadict(self, data, files, name):\n return int(data['provider__id'])\n\n\nclass PointWidget(forms.Widget):\n def value_from_datadict(self, data, files, name):\n return Point(data['longitude'], data['latitude'])\n\n\nclass ServiceForm(forms.ModelForm):\n type = forms.ModelChoiceField(\n queryset=ServiceType.objects.all(),\n widget=ServiceTypeWidget\n )\n area_of_service = forms.ModelChoiceField(\n queryset=ServiceArea.objects.all(),\n widget=ServiceAreaWidget\n )\n provider = forms.ModelChoiceField(\n queryset=Provider.objects.all(),\n widget=ProviderWidget\n )\n location = PointField(\n widget=PointWidget\n )\n\n class Meta:\n model = Service\n exclude = ['status']\n # Setting fields to '__all__' here is reasonably safe since we\n # are careful elsewhere to only export and import certain fields.\n fields = '__all__'\n\n\nclass SelectionCriterionForm(forms.ModelForm):\n class Meta:\n model = SelectionCriterion\n # Setting fields to '__all__' here is reasonably safe since we\n # are careful elsewhere to only export and import certain fields.\n fields = '__all__'\n","repo_name":"theirc/ServiceInfo","sub_path":"services/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":6245,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"35566418083","text":"import random\nimport tempfile\n\nimport coords\nimport dual_net\nimport preprocessing\nimport features\nimport go\nimport symmetries\nfrom tests import test_utils\n\nimport numpy as np\nimport tensorflow as tf\n\n\nTEST_SGF = \"(;CA[UTF-8]SZ[9]PB[Seth the best]PW[Andrew opens H4]KM[6.5]HA[0]RE[W+1.5]GM[1];B[fd];W[cf])\"\n\n\nclass TestPreprocessing(test_utils.MinigoUnitTest):\n def create_random_data(self, num_examples):\n planes = dual_net.get_features_planes()\n raw_data = []\n for _ in range(num_examples):\n feature = (256 * np.random.random([\n go.N, go.N, planes])).astype(np.uint8)\n pi = np.random.random([go.N * go.N + 1]).astype(np.float32)\n value = np.random.random()\n raw_data.append((feature, pi, value))\n return raw_data\n\n def get_data_tensors(self, pos_tensor, label_tensors):\n recovered_data = []\n with tf.Session() as sess:\n while True:\n try:\n pos_value, label_values = sess.run(\n [pos_tensor, label_tensors])\n recovered_data.append((\n pos_value,\n label_values['pi_tensor'],\n label_values['value_tensor']))\n except tf.errors.OutOfRangeError:\n break\n return recovered_data\n\n def extract_data(self, tf_record, filter_amount=1, random_rotation=False):\n pos_tensor, label_tensors = preprocessing.get_input_tensors(\n 1, 'nhwc', [tf_record], num_repeats=1, shuffle_records=False,\n shuffle_examples=False, filter_amount=filter_amount,\n random_rotation=random_rotation)\n return self.get_data_tensors(pos_tensor, label_tensors)\n\n def extract_tpu_data(self, tf_record, random_rotation=False):\n dataset = preprocessing.get_tpu_input_tensors(\n 1, 'nhwc', [tf_record], num_repeats=1, shuffle_records=False,\n shuffle_examples=False, filter_amount=1,\n random_rotation=random_rotation)\n pos_tensor, label_tensors = dataset.make_one_shot_iterator().get_next()\n return self.get_data_tensors(pos_tensor, label_tensors)\n\n def assertEqualData(self, data1, data2):\n \"\"\"Assert that the two datas are equal.\n\n Args:\n data1: List>\n data2: Same form as data1\n \"\"\"\n self.assertEqual(len(data1), len(data2))\n for datum1, datum2 in zip(data1, data2):\n # feature\n self.assertEqualNPArray(datum1[0], datum2[0])\n # pi\n self.assertEqualNPArray(datum1[1], datum2[1])\n # value\n self.assertEqual(datum1[2], datum2[2])\n\n def reset_random(self):\n random.seed(1)\n tf.set_random_seed(1)\n\n def find_symmetry(self, x, pi, x2, pi2):\n for sym in symmetries.SYMMETRIES:\n x_equal = (x == symmetries.apply_symmetry_feat(sym, x2)).all()\n pi_equal = (pi == symmetries.apply_symmetry_pi(sym, pi2)).all()\n if x_equal and pi_equal:\n return sym\n\n self.assertTrue(False, \"No rotation makes {} equal {}\".format(pi, pi2))\n\n def x_and_pi_same(self, run_a, run_b):\n x_a, pi_a, values_a = zip(*run_a)\n x_b, pi_b, values_b = zip(*run_b)\n self.assertEqual(values_a, values_b, \"Values are not same\")\n return np.array_equal(x_a, x_b) and np.array_equal(pi_a, pi_b)\n\n def assert_rotate_data(self, run_one, run_two, run_three):\n \"\"\"Verify run_one is rotated and run_two is identical to run_three\"\"\"\n self.assertTrue(\n self.x_and_pi_same(run_two, run_three),\n \"Not deterministic\")\n self.assertFalse(\n self.x_and_pi_same(run_one, run_two),\n \"Not randomly rotated\")\n\n syms = []\n for (x, pi, v), (x2, pi2, v2) in zip(run_one, run_two):\n self.assertEqual(v, v2, \"values not the same\")\n # For each record find the symmetry that makes them equal\n syms.extend(\n map(lambda r: self.find_symmetry(*r), zip(x, pi, x2, pi2)))\n\n difference = set(symmetries.SYMMETRIES) - set(syms)\n self.assertEqual(len(run_one), len(syms), \"Not same number of records\")\n self.assertEqual(set(), difference, \"Didn't find these rotations\")\n\n def test_serialize_round_trip(self):\n np.random.seed(1)\n raw_data = self.create_random_data(10)\n tfexamples = list(map(preprocessing.make_tf_example, *zip(*raw_data)))\n\n with tempfile.NamedTemporaryFile() as f:\n preprocessing.write_tf_examples(f.name, tfexamples)\n recovered_data = self.extract_data(f.name)\n\n self.assertEqualData(raw_data, recovered_data)\n\n def test_filter(self):\n raw_data = self.create_random_data(100)\n tfexamples = list(map(preprocessing.make_tf_example, *zip(*raw_data)))\n\n with tempfile.NamedTemporaryFile() as f:\n preprocessing.write_tf_examples(f.name, tfexamples)\n recovered_data = self.extract_data(f.name, filter_amount=.05)\n\n # TODO: this will flake out very infrequently. Use set_random_seed\n self.assertLess(len(recovered_data), 50)\n\n def test_make_dataset_from_sgf(self):\n with tempfile.NamedTemporaryFile() as sgf_file, \\\n tempfile.NamedTemporaryFile() as record_file:\n sgf_file.write(TEST_SGF.encode('utf8'))\n sgf_file.seek(0)\n preprocessing.make_dataset_from_sgf(\n sgf_file.name, record_file.name)\n recovered_data = self.extract_data(record_file.name)\n start_pos = go.Position()\n first_move = coords.from_sgf('fd')\n next_pos = start_pos.play_move(first_move)\n second_move = coords.from_sgf('cf')\n f = dual_net.get_features()\n expected_data = [\n (\n features.extract_features(start_pos, f),\n preprocessing._one_hot(coords.to_flat(first_move)),\n -1\n ), (\n features.extract_features(next_pos, f),\n preprocessing._one_hot(coords.to_flat(second_move)),\n -1\n )]\n self.assertEqualData(expected_data, recovered_data)\n\n def test_rotate_pyfunc(self):\n num_records = 20\n raw_data = self.create_random_data(num_records)\n tfexamples = list(map(preprocessing.make_tf_example, *zip(*raw_data)))\n\n with tempfile.NamedTemporaryFile() as f:\n preprocessing.write_tf_examples(f.name, tfexamples)\n\n self.reset_random()\n run_one = self.extract_data(f.name, random_rotation=False)\n\n self.reset_random()\n run_two = self.extract_data(f.name, random_rotation=True)\n\n self.reset_random()\n run_three = self.extract_data(f.name, random_rotation=True)\n\n self.assert_rotate_data(run_one, run_two, run_three)\n\n def test_tpu_rotate(self):\n num_records = 100\n raw_data = self.create_random_data(num_records)\n tfexamples = list(map(preprocessing.make_tf_example, *zip(*raw_data)))\n\n with tempfile.NamedTemporaryFile() as f:\n preprocessing.write_tf_examples(f.name, tfexamples)\n\n self.reset_random()\n run_one = self.extract_tpu_data(f.name, random_rotation=False)\n\n self.reset_random()\n run_two = self.extract_tpu_data(f.name, random_rotation=True)\n\n self.reset_random()\n run_three = self.extract_tpu_data(f.name, random_rotation=True)\n\n self.assert_rotate_data(run_one, run_two, run_three)\n","repo_name":"tensorflow/minigo","sub_path":"tests/test_preprocessing.py","file_name":"test_preprocessing.py","file_ext":"py","file_size_in_byte":7678,"program_lang":"python","lang":"en","doc_type":"code","stars":3409,"dataset":"github-code","pt":"77"} +{"seq_id":"8792576387","text":"import ui\nimport os\nimport log\nimport shutil\n\nRESOURCES_PATH = \"../resources/\"\nRES_PATH = \"../res/\"\nPNGGUANT = \"pngquant/pngquant\"\n\n\ndef _compress_png(_file_full_path):\n arg = os.path.abspath('.') + os.sep + PNGGUANT\n arg += \" --force\"\n arg += \" --ordered\"\n arg += \" --output \" + _file_full_path\n arg += \" --speed=11\"\n arg += \" --quality=0-100\"\n arg += \" \" + _file_full_path\n os.system(arg)\n log.debug(\"compre image : \" + _file_full_path)\n\n\ndef _find_png(_dir):\n for _file in os.listdir(_dir):\n if os.path.isdir(_dir + os.sep + _file):\n _find_png(_dir + os.sep + _file)\n else:\n name = _file.split(\".\")\n if name[1] == \"png\" or name[1] == \"jpg\":\n _file_full_path = _dir + os.sep + _file\n _compress_png(_file_full_path)\n\n\ndef copy_resources():\n log.debug(\"****** del old res begin ******\")\n if os.path.exists(RES_PATH):\n shutil.rmtree(RES_PATH)\n log.debug(\"****** del old res over ******\")\n log.debug(\"****** copy resouece begin ******\")\n shutil.copytree(RESOURCES_PATH, RES_PATH)\n log.debug(\"****** copy resouece over ******\")\n\n\ndef publish():\n log.debug(\"****** publish res begin ******\")\n copy_resources()\n ui.publish()\n log.debug(\"****** publish res over ******\")\n # _find_png(RES_PATH)\n\n\npublish()\n","repo_name":"qbzjs/CocosTools","sub_path":"publish_res.py","file_name":"publish_res.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":"15197953213","text":"#!/usr/bin/python\nimport sys\nimport argparse\n\nparser=argparse.ArgumentParser(\n description='''Parse REPEAT MASKER annotation and expand them to position specific values on Y. ''')\nparser.add_argument('--INPUT', '-i', required=True, help=' REPEAT MASKER output format ', metavar='')\nparser.add_argument('--CHR', '-c', required=True, help=' Chromosome annotation as found in the REPEAT MASKER output file. ', choices=['Y','chrY'])\nparser.add_argument('--LENGTH','-l', type=int, required=True, help='Length of the Y chromosome in the reference.')\n\t\nargs=parser.parse_args()\n\nINPUT=args.INPUT #REPEAT MASKER output\nCHR=args.CHR #chromosome name as defined in the mappability output Y or chrY\nlen_chr=args.LENGTH #Length of Y chromosome in reference\n\n#INPUT='/nfs/brubeck.bx.psu.edu/scratch6/rahul/GTEx/REF/RM/hg38.sorted.fa.out'\n\nrepeatmask_val = [1]*len_chr\nwith open(INPUT,\"r\") as rFH:\n\tnext(rFH)#heading\n\tnext(rFH)#heading\n\tnext(rFH)#empty line\n\tfor line in rFH :\n\t\tcol=line.rstrip('\\n').split()\n\t\tif col[4] == CHR:\n\t\t\trepeatmask_val[int(col[5]):int(col[6])]=[0]*(int(col[6])-int(col[5]))\n\nrFH.close()\n\nfile = open(str(CHR)+\"_REPEAT_MASKED.txt\", \"w\")\nfile.write(\"RepeatMasked\\n\")\nfor index in range(len(repeatmask_val)):\n\tfile.write(str(repeatmask_val[index])+ \"\\n\")\n\nfile.close()\n","repo_name":"makovalab-psu/AmpliCoNE-tool","sub_path":"bin/parse_Ychr_RepeatMasker.py","file_name":"parse_Ychr_RepeatMasker.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"42054663154","text":"__author__ = 'Johnatan Astudillo'\n__date__ = '2019-10-12'\n__copyright__ = '(C) 2019 by LlactaLAB'\n\n# This will get replaced with a git SHA1 when you do a git archive\n\n__revision__ = '$Format:%H$'\n\nimport os\n\nfrom qgis.PyQt.QtCore import QCoreApplication\nfrom qgis.PyQt.QtGui import QIcon\nfrom qgis.core import (QgsProcessing,\n QgsProcessingMultiStepFeedback,\n QgsFeatureSink,\n QgsProcessingParameterEnum,\n QgsProcessingParameterFile,\n QgsProcessingAlgorithm,\n QgsProcessingParameterFeatureSource,\n QgsProcessingParameterField,\n QgsProcessingParameterNumber,\n QgsProcessingParameterFeatureSink)\nfrom .ZProcesses import *\nfrom .Zettings import *\nfrom .ZHelpers import *\n\n#pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0]\n\nclass IC00WrapC(QgsProcessingAlgorithm):\n \"\"\"\n Calcula todos los indicadores de ambiente construido\n \"\"\"\n BLOCKS = 'BLOCKS'\n FIELD_POPULATION = 'FIELD_POPULATION'\n FIELD_HOUSING = 'FIELD_HOUSING' \n CELL_SIZE = 'CELL_SIZE'\n STUDY_AREA_GRID = 'STUDY_AREA_GRID'\n\n #-----------------C01----------------------\n WALK_ROAD = 'WALK_ROAD'\n ROADS = 'ROADS'\n #-----------------C03----------------------\n ROADS_LINES = 'ROADS_LINES'\n #-----------------C04----------------------\n DISTANCE_OPTIONS = 'DISTANCE_OPTIONS'\n ROADS = 'ROADS' \n BUSSTOP = 'BUSSTOP' \n TRAMSTOP = 'TRAMSTOP' \n BIKESTOP = 'BIKESTOP' \n BIKEWAY = 'BIKEWAY' \n CROSSWALK = 'CROSSWALK'\n #-----------------C05----------------------\n PARKING = 'PARKING'\n AREA_PER_PARKING = 'AREA_PER_PARKING'\n DPA_MAN = 'DPA_MAN'\n #-----------------C09------------------------\n CENSO_VIVIENDA = 'CENSO_VIVIENDA'\n CENSO_HOGAR = 'CENSO_HOGAR' \n #-----------------C13----------------------\n SEWERAGE = 'SEWERAGE'\n #-----------------OUTPUTS----------------------\n OUTPUT_C01 = 'OUTPUT_C01'\n OUTPUT_C03 = 'OUTPUT_C03'\n OUTPUT_C04 = 'OUTPUT_C04'\n OUTPUT_C05 = 'OUTPUT_C05'\n OUTPUT_C09 = 'OUTPUT_C09'\n OUTPUT_C13 = 'OUTPUT_C13'\n\n\n def initAlgorithm(self, config):\n\n currentPath = getCurrentPath(self)\n FULL_PATH_C01 = buildFullPathName(currentPath, nameWithOuputExtension(NAMES_INDEX['IC01'][1]))\n FULL_PATH_C03 = buildFullPathName(currentPath, nameWithOuputExtension(NAMES_INDEX['IC03'][1]))\n FULL_PATH_C04 = buildFullPathName(currentPath, nameWithOuputExtension(NAMES_INDEX['IC04'][1]))\n FULL_PATH_C05 = buildFullPathName(currentPath, nameWithOuputExtension(NAMES_INDEX['IC05'][1]))\n FULL_PATH_C09 = buildFullPathName(currentPath, nameWithOuputExtension(NAMES_INDEX['IC09'][1]))\n FULL_PATH_C13 = buildFullPathName(currentPath, nameWithOuputExtension(NAMES_INDEX['IC13'][1]))\n\n\n #-----------------OTHERS----------------------\n self.addParameter(\n QgsProcessingParameterFeatureSource(\n self.STUDY_AREA_GRID,\n self.tr(TEXT_GRID_INPUT),\n [QgsProcessing.TypeVectorPolygon],\n '', OPTIONAL_GRID_INPUT\n )\n )\n\n\n self.addParameter(\n QgsProcessingParameterFeatureSource(\n self.BLOCKS,\n self.tr('Manzanas'),\n [QgsProcessing.TypeVectorPolygon],\n optional = True,\n defaultValue=\"\"\n )\n )\n\n self.addParameter(\n QgsProcessingParameterField(\n self.DPA_MAN,\n self.tr('DPA Manzanas'),\n 'dpa_manzan', 'BLOCKS',\n optional = True\n )\n ) \n\n self.addParameter(\n QgsProcessingParameterField(\n self.FIELD_POPULATION,\n self.tr('Población'),\n 'poblacion', 'BLOCKS',\n optional = True\n )\n ) \n\n self.addParameter(\n QgsProcessingParameterField(\n self.FIELD_HOUSING,\n self.tr('Viviendas'),\n 'viviendas', 'BLOCKS',\n optional = True\n )\n ) \n\n #-----------------C01----------------------\n self.addParameter(\n QgsProcessingParameterFeatureSource(\n self.ROADS,\n self.tr('Viario público'),\n [QgsProcessing.TypeVectorPolygon],\n optional = True,\n defaultValue=\"\"\n )\n )\n\n self.addParameter(\n QgsProcessingParameterFeatureSource(\n self.WALK_ROAD,\n self.tr('Viario público peatonal'),\n [QgsProcessing.TypeVectorPolygon],\n optional = True,\n defaultValue=\"\"\n )\n ) \n #-----------------C03----------------------\n self.addParameter(\n QgsProcessingParameterFeatureSource(\n self.ROADS_LINES,\n self.tr('Vías públicas'),\n [QgsProcessing.TypeVectorLine],\n optional = True,\n defaultValue=\"\"\n )\n )\n #-----------------C04----------------------\n self.addParameter(\n QgsProcessingParameterFeatureSource(\n self.ROADS,\n self.tr('Red vial'),\n [QgsProcessing.TypeVectorLine],\n optional = True,\n defaultValue = ''\n )\n ) \n\n self.addParameter(\n QgsProcessingParameterEnum(\n self.DISTANCE_OPTIONS,\n self.tr('Tipo de distancia'),\n options=['ISOCRONA','RADIAL'], \n allowMultiple=False, \n defaultValue=1)\n ) \n\n\n self.addParameter(\n QgsProcessingParameterFeatureSource(\n self.BUSSTOP,\n self.tr('Paradas de bus'),\n [QgsProcessing.TypeVectorPoint],\n optional = True,\n defaultValue=\"\"\n )\n )\n\n self.addParameter(\n QgsProcessingParameterFeatureSource(\n self.TRAMSTOP,\n self.tr('Tranvía'),\n [QgsProcessing.TypeVectorPoint],\n optional = True,\n defaultValue=\"\"\n )\n )\n\n self.addParameter(\n QgsProcessingParameterFeatureSource(\n self.BIKESTOP,\n self.tr('Bici pública'),\n [QgsProcessing.TypeVectorPoint],\n optional = True,\n defaultValue=\"\"\n )\n )\n\n self.addParameter(\n QgsProcessingParameterFeatureSource(\n self.BIKEWAY,\n self.tr('Ciclovía'),\n [QgsProcessing.TypeVectorLine],\n optional = True,\n defaultValue=\"\"\n )\n )\n\n self.addParameter(\n QgsProcessingParameterFeatureSource(\n self.CROSSWALK,\n self.tr('Caminos peatonales'),\n [QgsProcessing.TypeVectorLine],\n optional = True,\n defaultValue=\"\"\n )\n ) \n #-----------------C05----------------------\n self.addParameter(\n QgsProcessingParameterFeatureSource(\n self.PARKING,\n self.tr('Puestos de parqueo'),\n [QgsProcessing.TypeVectorPoint],\n optional = True,\n defaultValue=\"\"\n )\n ) \n\n self.addParameter(\n QgsProcessingParameterNumber(\n self.AREA_PER_PARKING,\n self.tr('Área de cada parqueadero'),\n QgsProcessingParameterNumber.Integer,\n 10, False, 1, 99999999\n )\n ) \n #-----------------C13----------------------\n self.addParameter(\n QgsProcessingParameterFeatureSource(\n self.SEWERAGE,\n self.tr('Cobertura alcantarillado)'),\n [QgsProcessing.TypeVectorAnyGeometry],\n optional = True,\n defaultValue=\"\"\n )\n )\n\n self.addParameter(\n QgsProcessingParameterFile(\n self.CENSO_HOGAR,\n self.tr('Censo hogar'),\n extension='csv',\n defaultValue=\"\",\n optional = True\n )\n ) \n\n self.addParameter(\n QgsProcessingParameterFile(\n self.CENSO_VIVIENDA,\n self.tr('Censo vivienda'),\n extension='csv',\n defaultValue='',\n optional = True\n )\n ) \n\n #-----------------OUTPUTS----------------------\n\n self.addParameter(\n QgsProcessingParameterFeatureSink(\n self.OUTPUT_C01,\n self.tr('C01 Reparto del viario público peatonal'),\n QgsProcessing.TypeVectorAnyGeometry,\n str(FULL_PATH_C01)\n )\n )\n\n self.addParameter(\n QgsProcessingParameterFeatureSink(\n self.OUTPUT_C03,\n self.tr('C03 Vías públicas por habitante'),\n QgsProcessing.TypeVectorAnyGeometry,\n str(FULL_PATH_C03)\n )\n ) \n\n self.addParameter(\n QgsProcessingParameterFeatureSink(\n self.OUTPUT_C04,\n self.tr('C04 Proximidad a redes de transporte alternativo'),\n QgsProcessing.TypeVectorAnyGeometry,\n str(FULL_PATH_C04)\n )\n ) \n\n self.addParameter(\n QgsProcessingParameterFeatureSink(\n self.OUTPUT_C05,\n self.tr('C05 Espacio público ocupado por vehículos parqueados'),\n QgsProcessing.TypeVectorAnyGeometry,\n str(FULL_PATH_C05)\n )\n ) \n\n self.addParameter(\n QgsProcessingParameterFeatureSink(\n self.OUTPUT_C09,\n self.tr('C09 Consumo de energía eléctrica en la vivienda'),\n QgsProcessing.TypeVectorAnyGeometry,\n str(FULL_PATH_C09)\n )\n ) \n\n self.addParameter(\n QgsProcessingParameterFeatureSink(\n self.OUTPUT_C13,\n self.tr('C13 Cobertura del servicio de alcantarillado'),\n QgsProcessing.TypeVectorAnyGeometry,\n str(FULL_PATH_C13)\n )\n ) \n\n \n\n def processAlgorithm(self, params, context, feedback):\n steps = 0\n totalStpes = 6\n outputs = {}\n results = {}\n feedback = QgsProcessingMultiStepFeedback(totalStpes, feedback)\n\n isValid = lambda x: False if x is None else True\n\n isBlocks = isValid(params['BLOCKS']) \n isFieldPopulation = isValid(params['FIELD_POPULATION'])\n isFieldHousing = isValid(params['FIELD_HOUSING'])\n isStudyArea = isValid(params['STUDY_AREA_GRID']) \n\n isRoads = isValid(params['ROADS']) \n isWalkRoad = isValid(params['WALK_ROAD']) \n\n\n\n if isRoads and isWalkRoad:\n # C01 Reparto del viario público peatonal\n steps = steps+1\n feedback.setCurrentStep(steps) \n if feedback.isCanceled():\n return {}\n alg_params = {\n 'ROADS': params['ROADS'],\n 'STUDY_AREA_GRID': params['STUDY_AREA_GRID'],\n 'WALK_ROAD': params['WALK_ROAD'],\n 'OUTPUT': params['OUTPUT_C01']\n }\n outputs['C01RepartoDelViarioPblicoPeatonal'] = processing.run('SISURBANO:C01 Reparto del viario público peatonal', alg_params, context=context, feedback=feedback, is_child_algorithm=True)\n results['OUTPUT_C01'] = outputs['C01RepartoDelViarioPblicoPeatonal']['OUTPUT'] \n\n\n isRoadsLines = isValid(params['ROADS_LINES']) \n\n if isBlocks and isFieldPopulation and isRoadsLines:\n # C03 Vías públicas por habitante\n steps = steps+1\n feedback.setCurrentStep(steps) \n if feedback.isCanceled():\n return {} \n alg_params = {\n 'BLOCKS': params['BLOCKS'],\n 'FIELD_POPULATION': params['FIELD_POPULATION'],\n 'ROADS_LINES': params['ROADS_LINES'],\n 'STUDY_AREA_GRID': params['STUDY_AREA_GRID'],\n 'OUTPUT': params['OUTPUT_C03']\n }\n outputs['C03VasPblicasPorHabitante'] = processing.run('SISURBANO:C03 Vías públicas por habitante', alg_params, context=context, feedback=feedback, is_child_algorithm=True)\n results['OUTPUT_C03'] = outputs['C03VasPblicasPorHabitante']['OUTPUT'] \n\n\n isBikeStop = isValid(params['BIKESTOP'])\n isBikeWay = isValid(params['BIKEWAY'])\n isBusStop = isValid(params['BUSSTOP'])\n isCrossWalk = isValid(params['CROSSWALK'])\n isDistanceOptions = isValid(params['DISTANCE_OPTIONS'])\n isTramStop = isValid(params['TRAMSTOP'])\n\n if (isBikeStop and isBikeWay and isBlocks and isBusStop and isCrossWalk and isRoads\n and isDistanceOptions and isFieldPopulation and isTramStop):\n # C04 Proximidad a redes de transporte alternativo\n steps = steps+1\n feedback.setCurrentStep(steps) \n if feedback.isCanceled():\n return {} \n alg_params = {\n 'BIKESTOP': params['BIKESTOP'],\n 'BIKEWAY': params['BIKEWAY'],\n 'BLOCKS': params['BLOCKS'],\n 'BUSSTOP': params['BUSSTOP'],\n 'CROSSWALK': params['CROSSWALK'],\n 'ROADS': params['ROADS'],\n 'DISTANCE_OPTIONS': params['DISTANCE_OPTIONS'], \n 'FIELD_POPULATE_HOUSING': params['FIELD_POPULATION'],\n 'STUDY_AREA_GRID': params['STUDY_AREA_GRID'],\n 'TRAMSTOP': params['TRAMSTOP'],\n 'OUTPUT': params['OUTPUT_C04']\n }\n outputs['C04ProximidadARedesDeTransporteAlternativo'] = processing.run('SISURBANO:C04 Proximidad a redes de transporte alternativo', alg_params, context=context, feedback=feedback, is_child_algorithm=True)\n results['OUTPUT_C04'] = outputs['C04ProximidadARedesDeTransporteAlternativo']['OUTPUT'] \n \n\n isAreaPerParking = isValid(params['AREA_PER_PARKING'])\n isParking = isValid(params['PARKING'])\n\n if isAreaPerParking and isParking and isRoads:\n # C05 Espacio público ocupado por vehículos parqueados\n steps = steps+1\n feedback.setCurrentStep(steps) \n if feedback.isCanceled():\n return {} \n alg_params = {\n 'AREA_PER_PARKING': params['AREA_PER_PARKING'],\n 'PARKING': params['PARKING'],\n 'ROADS': params['ROADS'],\n 'STUDY_AREA_GRID': params['STUDY_AREA_GRID'],\n 'OUTPUT': params['OUTPUT_C05']\n }\n outputs['C05EspacioPblicoOcupadoPorVehculosParqueados'] = processing.run('SISURBANO:C05 Espacio público ocupado por vehículos parqueados', alg_params, context=context, feedback=feedback, is_child_algorithm=True)\n results['OUTPUT_C05'] = outputs['C05EspacioPblicoOcupadoPorVehculosParqueados']['OUTPUT']\n\n \n\n\n isCensoVivienda = isValid(params['CENSO_VIVIENDA'])\n isCensoHogar = isValid(params['CENSO_HOGAR'])\n isDpaMan = isValid(params['DPA_MAN'])\n\n if isCensoHogar and isCensoVivienda and isDpaMan:\n # C09 Consumo de energía eléctrica en la vivienda\n steps = steps+1\n feedback.setCurrentStep(steps) \n if feedback.isCanceled():\n return {} \n alg_params = {\n 'BLOCKS': params['BLOCKS'],\n 'CENSO_HOGAR': params['CENSO_HOGAR'],\n 'CENSO_VIVIENDA':params['CENSO_VIVIENDA'],\n 'DPA_MAN': params['DPA_MAN'],\n 'STUDY_AREA_GRID': params['STUDY_AREA_GRID'],\n 'OUTPUT': params['OUTPUT_C09'],\n }\n outputs['C09ConsumoDeEnergaElctricaEnLaVivienda'] = processing.run('SISURBANO:C09 Consumo de energía eléctrica en la vivienda', alg_params, context=context, feedback=feedback, is_child_algorithm=True)\n results['OUTPUT_C09'] = outputs['C09ConsumoDeEnergaElctricaEnLaVivienda']['OUTPUT']\n\n\n isSewerage = isValid(params['SEWERAGE'])\n\n if isBlocks and isFieldHousing and isSewerage:\n # C13 Cobertura del servicio de alcantarillado\n steps = steps+1\n feedback.setCurrentStep(steps) \n if feedback.isCanceled():\n return {} \n alg_params = {\n 'BLOCKS': params['BLOCKS'],\n 'FIELD_HOUSING': params['FIELD_HOUSING'],\n 'SEWERAGE': params['SEWERAGE'],\n 'STUDY_AREA_GRID': params['STUDY_AREA_GRID'],\n 'OUTPUT': params['OUTPUT_C13']\n }\n outputs['C13CoberturaDelSistemaDeServicioDeAlcantarillado'] = processing.run('SISURBANO:C13 Cobertura del servicio de alcantarillado', alg_params, context=context, feedback=feedback, is_child_algorithm=True)\n results['OUTPUT_C13'] = outputs['C13CoberturaDelSistemaDeServicioDeAlcantarillado']['OUTPUT']\n\n\n return results\n\n\n def icon(self):\n return QIcon(os.path.join(pluginPath, 'make-hexa_logo.png'))\n\n def name(self):\n \"\"\"\n Returns the algorithm name, used for identifying the algorithm. This\n string should be fixed for the algorithm, and must not be localised.\n The name should be unique within each provider. Names should contain\n lowercase alphanumeric characters only and no spaces or other\n formatting characters.\n \"\"\"\n return 'C00 Todos los indicadores C'\n\n def displayName(self):\n \"\"\"\n Returns the translated algorithm name, which should be used for any\n user-visible display of the algorithm name.\n \"\"\"\n return self.tr(self.name())\n\n def group(self):\n \"\"\"\n Returns the name of the group this algorithm belongs to. This string\n should be localised.\n \"\"\"\n return self.tr(self.groupId())\n\n def groupId(self):\n \"\"\"\n Returns the unique ID of the group this algorithm belongs to. This\n string should be fixed for the algorithm, and must not be localised.\n The group id should be unique within each provider. Group id should\n contain lowercase alphanumeric characters only and no spaces or other\n formatting characters.\n \"\"\"\n return 'C Movilidad urbana'\n\n def tr(self, string):\n return QCoreApplication.translate('Processing', string)\n\n def createInstance(self):\n return IC00WrapC()\n\n def shortHelpString(self):\n return \"Descripción:
\"\\\n \"Calcula todos los indicadores de Moviidad urbana
\"","repo_name":"fastuller88/sisurbano","sub_path":"algs/IC00WrapC.py","file_name":"IC00WrapC.py","file_ext":"py","file_size_in_byte":19385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"38365271554","text":"import warnings\nfrom datetime import datetime\nfrom itertools import groupby\nfrom typing import Union, Sequence, Dict\n\nimport pandas as pd\nfrom qf_lib.common.enums.expiration_date_field import ExpirationDateField\n\nfrom qf_lib.common.enums.frequency import Frequency\nfrom qf_lib.common.enums.price_field import PriceField\nfrom qf_lib.common.enums.quandl_db_type import QuandlDBType\nfrom qf_lib.common.tickers.tickers import QuandlTicker, Ticker\nfrom qf_lib.common.utils.dateutils.date_to_string import date_to_str\nfrom qf_lib.common.utils.logging.qf_parent_logger import qf_logger\nfrom qf_lib.common.utils.miscellaneous.to_list_conversion import convert_to_list\nfrom qf_lib.containers.dataframe.qf_dataframe import QFDataFrame\nfrom qf_lib.containers.futures.future_tickers.future_ticker import FutureTicker\nfrom qf_lib.containers.qf_data_array import QFDataArray\nfrom qf_lib.containers.series.qf_series import QFSeries\nfrom qf_lib.data_providers.helpers import tickers_dict_to_data_array, \\\n normalize_data_array, get_fields_from_tickers_data_dict\nfrom qf_lib.data_providers.data_provider import DataProvider\nfrom qf_lib.settings import Settings\n\ntry:\n import quandl\n is_quandl_installed = True\nexcept ImportError:\n is_quandl_installed = False\n warnings.warn(\"No quandl installed. If you would like to use QuandlDataProvider first install the quandl library.\")\n\n\nclass QuandlDataProvider(DataProvider):\n \"\"\"\n Class providing the Quandl data.\n The table database: WIKI/PRICES offers stock prices, dividends and splits for 3000 US publicly-traded companies.\n This database is updated at 9:15 PM EST every weekday.\n \"\"\"\n\n def __init__(self, settings: Settings):\n super().__init__()\n self.logger = qf_logger.getChild(self.__class__.__name__)\n\n try:\n self.key = settings.quandl_key\n quandl.ApiConfig.api_key = self.key\n except AttributeError:\n self.logger.warning(\"No quandl_key parameter found in Settings. If you want to use QuandlDataProvider, add \"\n \"quandl_key in the settings json file.\")\n\n def get_price(self, tickers: Union[QuandlTicker, Sequence[QuandlTicker]],\n fields: Union[PriceField, Sequence[PriceField]], start_date: datetime, end_date: datetime = None,\n frequency: Frequency = Frequency.DAILY, **kwargs):\n start_date = self._adjust_start_date(start_date, frequency)\n return self._get_history(\n convert_to_prices_types=True, tickers=tickers, fields=fields, start_date=start_date, end_date=end_date)\n\n def get_history(\n self, tickers: Union[QuandlTicker, Sequence[QuandlTicker]], fields: Union[None, str, Sequence[str]] = None,\n start_date: datetime = None, end_date: datetime = None, **kwargs):\n return self._get_history(\n convert_to_prices_types=False, tickers=tickers, fields=fields, start_date=start_date, end_date=end_date)\n\n def _get_history(\n self, convert_to_prices_types: bool, tickers: Union[QuandlTicker, Sequence[QuandlTicker]],\n fields: Union[None, str, Sequence[str], PriceField, Sequence[PriceField]] = None,\n start_date: datetime = None, end_date: datetime = None) -> \\\n Union[QFSeries, QFDataFrame, QFDataArray]:\n \"\"\"\n NOTE: Only use one Quandl Database at the time.\n Do not mix multiple databases in one query - this is the natural limitation coming from the fact that column\n names (fields) are different across databases.\n \"\"\"\n tickers, got_single_ticker = convert_to_list(tickers, QuandlTicker)\n got_single_date = start_date is not None and (start_date == end_date)\n\n if fields is not None:\n fields, got_single_field = convert_to_list(fields, (PriceField, str))\n else:\n got_single_field = False # all existing fields will be present in the result\n\n result_dict = {}\n for db_name, ticker_group in groupby(tickers, lambda t: t.database_name):\n ticker_group = list(ticker_group)\n\n partial_result_dict = self._get_result_for_single_database(\n convert_to_prices_types, ticker_group, fields, start_date, end_date)\n\n result_dict.update(partial_result_dict)\n\n if fields is None:\n fields = get_fields_from_tickers_data_dict(result_dict)\n\n result_data_array = tickers_dict_to_data_array(result_dict, tickers, fields)\n\n normalized_result = normalize_data_array(\n result_data_array, tickers, fields, got_single_date, got_single_ticker, got_single_field,\n use_prices_types=convert_to_prices_types)\n\n return normalized_result\n\n def _get_result_for_single_database(self, convert_to_prices_types, ticker_group, fields, start_date, end_date):\n first_ticker = ticker_group[0] # type: QuandlTicker\n db_name = first_ticker.database_name\n db_type = first_ticker.database_type\n\n if convert_to_prices_types:\n fields_as_strings = self._map_fields_to_str(fields, db_name, db_type)\n else:\n fields_as_strings = fields\n\n if db_type == QuandlDBType.Table:\n partial_result_dict = self._get_history_from_table(\n ticker_group, fields_as_strings, start_date, end_date)\n elif db_type == QuandlDBType.Timeseries:\n partial_result_dict = self._get_history_from_timeseries(\n ticker_group, fields_as_strings, start_date, end_date)\n else:\n raise LookupError(\"Quandl Database type: {} is not supported.\".format(db_type))\n\n if convert_to_prices_types:\n str_to_field = self._str_to_price_field_map(db_name, db_type)\n for ticker_data_df in partial_result_dict.values():\n price_field_columns = [str_to_field[field_str] for field_str in ticker_data_df.columns]\n ticker_data_df.columns = price_field_columns\n\n return partial_result_dict\n\n def _get_fields_from_result(self, result_dict):\n fields = set()\n for dates_fields_values in result_dict.values():\n fields.update(dates_fields_values.fields.values)\n\n fields = list(fields)\n return fields\n\n def supported_ticker_types(self):\n return {QuandlTicker}\n\n def _map_fields_to_str(self, fields: Sequence[PriceField], database_name: str, database_type: QuandlDBType):\n field_to_str = self._price_field_to_str_map(database_name, database_type)\n fields_as_strings = [field_to_str[field] for field in fields]\n return fields_as_strings\n\n def _str_to_price_field_map(self, database_name: str, database_type: QuandlDBType):\n field_to_str = self._price_field_to_str_map(database_name, database_type)\n str_to_field = {field_str: field for field, field_str in field_to_str.items()}\n\n return str_to_field\n\n def _price_field_to_str_map(self, database_name: str, database_type: QuandlDBType) -> Dict[PriceField, str]:\n if database_type == QuandlDBType.Table and database_name == 'WIKI/PRICES':\n price_field_dict = {\n PriceField.Open: 'adj_open',\n PriceField.High: 'adj_high',\n PriceField.Low: 'adj_low',\n PriceField.Close: 'adj_close',\n PriceField.Volume: 'adj_volume'\n }\n elif database_name == 'WIKI':\n price_field_dict = {\n PriceField.Open: 'Adj. Open',\n PriceField.High: 'Adj. High',\n PriceField.Low: 'Adj. Low',\n PriceField.Close: 'Adj. Close',\n PriceField.Volume: 'Adj. Volume'\n }\n elif database_name == 'WSE':\n price_field_dict = {\n PriceField.Open: 'Open',\n PriceField.High: 'High',\n PriceField.Low: 'Low',\n PriceField.Close: 'Close',\n PriceField.Volume: 'Volume'\n }\n elif database_name == 'CHRIS':\n # database of continuous futures - only Previous Settlement available\n price_field_dict = {\n PriceField.Close: 'Previous Settlement',\n }\n elif database_name in ['ICE', 'CME', 'EUREX']:\n # mapping for individual futures contracts\n price_field_dict = {\n PriceField.Open: 'Open',\n PriceField.High: 'High',\n PriceField.Low: 'Low',\n PriceField.Close: 'Settle',\n PriceField.Volume: 'Volume'\n }\n else:\n raise LookupError(\n \"Quandl Database: {} is not supported. PriceField -> string mapping is required.\".format(database_name)\n )\n return price_field_dict\n\n def _get_history_from_table(self, tickers_of_single_db: Sequence[QuandlTicker], fields: Sequence[str],\n start_date: datetime, end_date: datetime) -> Dict[QuandlTicker, pd.DataFrame]:\n # Possibly this method is not generic enough, but I couldn't find another table db to test it.\n field_options = {}\n if fields is not None:\n columns = ['ticker', 'date'] + list(fields)\n field_options['qopts'] = {'columns': columns}\n\n db_name = tickers_of_single_db[0].database_name\n result_dict = {}\n\n tickers_str = [t.as_string() for t in tickers_of_single_db]\n df = quandl.get_table(db_name, ticker=tickers_str, paginate=True, **field_options)\n # at this point we have a large DataFrame with rows corresponding to different tickers\n # we group it by ticker\n ticker_grouping = df.groupby('ticker')\n for ticker_str, ticker_df in ticker_grouping:\n ticker = QuandlTicker(ticker=ticker_str, database_name=db_name, database_type=QuandlDBType.Table)\n dates_fields_values_df = self._format_single_ticker_table(ticker_df, start_date, end_date)\n result_dict[ticker] = dates_fields_values_df\n\n return result_dict\n\n def _get_history_from_timeseries(\n self, tickers: Sequence[QuandlTicker], fields: Sequence[str], start_date: datetime, end_date: datetime):\n \"\"\"\n NOTE: Only use one Quandl Database at the time. Do not mix multiple databases.\n \"\"\"\n tickers = list(tickers) # allows iterating the sequence more then once\n tickers_map = {t.as_string(): t for t in tickers}\n\n kwargs = {}\n if start_date is not None:\n kwargs['start_date'] = date_to_str(start_date)\n if end_date is not None:\n kwargs['end_date'] = date_to_str(end_date)\n\n data = quandl.get(list(tickers_map.keys()), **kwargs) # type: pd.DataFrame\n\n def extract_ticker_name(column_name):\n ticker_str, _ = column_name.split(' - ')\n ticker = tickers_map[ticker_str]\n return ticker\n\n ticker_grouping = data.groupby(extract_ticker_name, axis=1)\n ticker_to_df = {} # type: Dict[str, pd.DataFrame] # string -> DataFrame[dates, fields]\n for ticker, ticker_data_df in ticker_grouping:\n tickers_and_fields = (column_name.split(' - ') for column_name in ticker_data_df.columns)\n field_names = [field for (ticker, field) in tickers_and_fields]\n ticker_data_df.columns = field_names\n\n if fields is not None:\n # select only required fields\n ticker_data_df = self._select_only_required_fields(ticker, ticker_data_df, fields)\n\n # if there was no data for the given ticker, skip the ticker\n if ticker_data_df is None:\n continue\n\n ticker_to_df[ticker] = ticker_data_df\n\n return ticker_to_df\n\n def _select_only_required_fields(self, ticker, ticker_data, fields):\n requested_fields_set = set(fields)\n got_fields_set = set(ticker_data.columns)\n missing_fields = requested_fields_set - got_fields_set\n\n if missing_fields:\n missing_columns = [ticker.field_to_column_name(field) for field in missing_fields]\n self.logger.warning(\"Columns {} have not been found in the Quandl response\".format(missing_columns))\n\n fields_to_select = requested_fields_set.intersection(got_fields_set)\n\n # if there are no fields which should be selected, return None\n if not fields_to_select:\n result = None\n else:\n result = ticker_data.loc[:, fields_to_select]\n\n return result\n\n @staticmethod\n def _format_single_ticker_table(table: pd.DataFrame, start_date: datetime, end_date: datetime) -> pd.DataFrame:\n # create index from column and remove redundant info\n table.set_index(keys='date', inplace=True)\n table = table.drop('ticker', axis=1) # type: pd.DataFrame\n table = table.sort_index()\n\n # cut the dates if necessary\n table = table.loc[start_date:end_date]\n\n return table\n\n def get_futures_chain_tickers(self, tickers: Union[FutureTicker, Sequence[FutureTicker]],\n expiration_date_fields: Union[ExpirationDateField, Sequence[ExpirationDateField]]) \\\n -> Dict[FutureTicker, Union[QFSeries, QFDataFrame]]:\n raise NotImplementedError(\"Downloading Future Chain Tickers in QuandlDataProvider is not supported yet\")\n\n def expiration_date_field_str_map(self, ticker: Ticker = None) -> Dict[ExpirationDateField, str]:\n pass\n","repo_name":"quarkfin/qf-lib","sub_path":"qf_lib/data_providers/quandl/quandl_data_provider.py","file_name":"quandl_data_provider.py","file_ext":"py","file_size_in_byte":13521,"program_lang":"python","lang":"en","doc_type":"code","stars":396,"dataset":"github-code","pt":"77"} +{"seq_id":"75071611449","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 12 11:54:12 2022\n\n@author: janpe\n\"\"\"\n\nimport pytheus.theseus as th\nfrom collections import Counter\nimport itertools\nimport numpy as np\nfrom itertools import combinations, product\nfrom itertools import combinations_with_replacement\nfrom pytheus.custom_loss.assembly_index import assembly_index, top_n_assembly\nimport logging\n\nlog = logging.getLogger(__name__)\n\n\ndef brutal_covers_heralding_sps(cnfg, graph):\n # this function finds heralding edgecovers for a bipartite graph\n in_verts = cnfg[\"single_emitters\"]\n out_verts = cnfg[\"out_nodes\"] + cnfg[\"anc_detectors\"]\n\n avail_colors = th.edgeBleach(graph.edges)\n\n sep_edges = []\n for node in in_verts:\n group = [edge for edge in list(avail_colors.keys()) if node in edge[:2]]\n sep_edges.append(group)\n tmp_raw_covers = list(product(*sep_edges))\n\n raw_covers = []\n for cover in tmp_raw_covers:\n counter = Counter(list(itertools.chain(*cover)))\n keep = True\n\n if cnfg['number_resolving']:\n for vert in cnfg[\"anc_detectors\"]:\n if counter[vert] != 1:\n keep = False\n else:\n for vert in cnfg[\"anc_detectors\"]:\n if counter[vert] == 0:\n keep = False\n # if all conditions are met, use edgecover for norm\n if keep:\n raw_covers.append(cover)\n\n painted_covers = []\n for cover in raw_covers:\n for coloring in itertools.product(*[avail_colors[edge] for edge in cover]):\n color_cover = [edge + color for edge, color in zip(cover, coloring)]\n painted_covers.append(sorted(color_cover))\n return [[tuple(ed) for ed in graph] for graph in painted_covers]\n\n\ndef brutal_covers(cnfg, graph):\n # this function is sometimes used instead of findEdgecovers, should be much slower in general, but faster at\n # applying topological constraints atm\n\n non_output_verts = [vert for vert in cnfg[\"verts\"] if vert not in cnfg[\"out_nodes\"]]\n # minimum number of edges that can cover non output vertices\n min_edges = len(non_output_verts) // 2\n # maximum number of edges, perfect matching order of whole graph\n max_edges = len(cnfg[\"verts\"]) // 2\n orders = list(range(min_edges, max_edges + 1))\n\n avail_colors = th.edgeBleach(graph.edges)\n tmp_raw_covers = []\n for num_edges in orders:\n tmp_raw_covers += combinations_with_replacement(list(avail_colors.keys()), num_edges)\n\n raw_covers = []\n ii = 0\n for cover in tmp_raw_covers:\n ii += 1\n keep = True\n counter = Counter(list(itertools.chain(*cover)))\n\n # check inputs and single emitters\n for vert in cnfg[\"in_nodes\"] + cnfg[\"single_emitters\"]:\n # if any are covered more than once, don't keep edge cover\n if counter[vert] != 1:\n keep = False\n\n if cnfg['number_resolving']:\n for vert in cnfg[\"anc_detectors\"]:\n if counter[vert] != 1:\n keep = False\n else:\n for vert in cnfg[\"anc_detectors\"]:\n if counter[vert] == 0:\n keep = False\n\n # # if in maximum order, we select for events where the correct total number of photons go into output paths\n # if len(cover) == max_edges:\n # sum = 0\n # for vert in cnfg[\"out_nodes\"]:\n # sum += counter[vert]\n # if sum != len(cnfg[\"out_nodes\"]):\n # keep = False\n\n # if all conditions are met, use edgecover for norm\n if keep:\n raw_covers.append(cover)\n painted_covers = []\n for cover in raw_covers:\n for coloring in itertools.product(*[avail_colors[edge] for edge in cover]):\n color_cover = [edge + color for edge, color in zip(cover, coloring)]\n painted_covers.append(sorted(color_cover))\n return [[tuple(ed) for ed in graph] for graph in np.unique(painted_covers, axis=0)]\n\n\ndef heralded_covers(cnfg, graph):\n # calls findEdgecovers and applies topological constraints\n\n non_output_verts = [vert for vert in cnfg[\"verts\"] if vert not in cnfg[\"out_nodes\"]]\n # minimum number of edges that can cover non output vertices\n min_edges = len(non_output_verts) // 2\n # maximum number of edges, perfect matching order of whole graph\n max_edges = len(cnfg[\"verts\"]) // 2\n orders = list(range(min_edges, max_edges + 1))\n try:\n if cnfg[\"novac\"]:\n orders = [max_edges]\n except KeyError:\n pass\n # find edge suitable edge covers for all possible numbers of edges\n tmp_edgecovers = []\n for num_edges in orders:\n tmp_edgecovers += th.findEdgeCovers(graph.edges, nodes_left=non_output_verts, edges_left=num_edges)\n # select for edgecovers that fulfill conditions\n edgecovers = []\n for cover in tmp_edgecovers:\n keep = True\n counter = Counter(list(itertools.chain(*th.edgeBleach(cover).keys())))\n\n # check inputs and single emitters\n for vert in cnfg[\"in_nodes\"] + cnfg[\"single_emitters\"]:\n # if any are covered more than once, don't keep edge cover\n if counter[vert] != 1:\n keep = False\n\n if cnfg['number_resolving']:\n for vert in cnfg[\"anc_detectors\"]:\n if counter[vert] != 1:\n keep = False\n else:\n for vert in cnfg[\"anc_detectors\"]:\n if counter[vert] == 0:\n keep = False\n\n # if in maximum order, we select for events where the correct total number of photons go into output paths\n if len(cover) == max_edges:\n sum = 0\n for vert in cnfg[\"out_nodes\"]:\n sum += counter[vert]\n if sum != len(cnfg[\"out_nodes\"]):\n keep = False\n\n # if all conditions are met, use edgecover for norm\n if keep:\n edgecovers.append(cover)\n return edgecovers\n\n\ndef count_rate(graph, target_state, cnfg):\n # can be used for state-creation/measurements/gates, post-selected/heralded\n\n # set up target equation\n target = target_state.targetEquation(state_catalog=graph.state_catalog, imaginary=cnfg[\"imaginary\"])\n # get variable names\n variables = th.stringEdges(graph.edges, imaginary=cnfg[\"imaginary\"])\n\n # non-heralded, post-selection case\n if not cnfg[\"heralding_out\"]:\n # only looking at perfect matchings\n graph.getNorm()\n norm = graph.norm\n # heralded case, more complicated selection rules\n else:\n if not cnfg[\"brutal_covers\"]:\n edgecovers = heralded_covers(cnfg, graph)\n elif cnfg[\"bipartite\"]:\n edgecovers = brutal_covers_heralding_sps(cnfg, graph)\n else:\n edgecovers = brutal_covers(cnfg, graph)\n cat = th.stateCatalog(edgecovers)\n norm = th.writeNorm(cat, imaginary=cnfg[\"imaginary\"])\n lambdaloss = \"\".join([\"1-\", target, \"/(1+\", norm, \")\"])\n func, lossstring = th.buildLossString(lambdaloss, variables)\n print('count rate done', flush=True)\n return func\n\n\ndef fidelity(graph, target_state, cnfg):\n # can be used for state-creation/measurements/gates, post-selected/heralded\n\n # set up target equation\n target = target_state.targetEquation(state_catalog=graph.state_catalog, imaginary=cnfg[\"imaginary\"])\n # get variable names\n variables = th.stringEdges(graph.edges, imaginary=cnfg[\"imaginary\"])\n\n # non-heralded, post-selection case\n if not cnfg[\"heralding_out\"]:\n # only looking at perfect matchings\n graph.getNorm()\n norm = graph.norm\n # heralded case, more complicated selection rules\n else:\n if not cnfg[\"brutal_covers\"]:\n edgecovers = heralded_covers(cnfg, graph)\n elif cnfg[\"bipartite\"]:\n edgecovers = brutal_covers_heralding_sps(cnfg, graph)\n else:\n edgecovers = brutal_covers(cnfg, graph)\n cat = th.stateCatalog(edgecovers)\n norm = th.writeNorm(cat, imaginary=cnfg[\"imaginary\"])\n lambdaloss = \"\".join([\"1-\", target, \"/(0+\", norm, \")\"])\n func, lossstring = th.buildLossString(lambdaloss, variables)\n print('fidelity done', flush=True)\n return func\n\n\n\"\"\"\nNumber states in Fock basis\n\"\"\"\n\n\ndef fock_fidelity(graph, target_state, num_anc, amplitudes, imaginary=False): # num_anc_pre\n\n # original ket is in the form: [((0,m),(1,n),(2,k1),(3,k2)...]; \n # here the m, n, k1, k2 are the number of particles instead of dimensions\n\n # make the ket in the correct form \n # [((0,0),(0,0)...,(1,0),(1,0),... (2,0),(2,0),...,(3,0),(3,0),...]\n # m times (0,0); n times (1,0); k1 times (2,0); k2 times (3,0), etc.\n # target_kets_temp = target_state.kets \n # target_kets=[]\n # accum = [sum([[(i,0)]*max(0,n) for i,n in k ],[]) for k in target_kets_temp]\n # for ii in accum:\n # target_kets.append(tuple(ii)) \n\n # all_verts= range(graph.num_nodes)#np.unique(list(itertools.chain(*th.edgeBleach(graph.edges).keys())))\n # anc_each_num=[int(i) for i in num_anc_pre]\n # state_each_num=[int(i) for i in target_state_str[0]] # all terms have the same photon number\n\n total_particle_num = len(target_state.kets[0])\n # total_particle_num=sum(state_each_num)+num_anc #sum(anc_each_num)\n\n # anc_position=all_verts[len(all_verts)-num_anc:]\n # anc_kets=[]\n # for jj in anc_position:\n # anc_kets.append((jj,0))\n\n anc_nodes = list(range(graph.num_nodes - num_anc, graph.num_nodes))\n\n edgecover_target = list(itertools.combinations_with_replacement(graph.edges, int(total_particle_num / 2)))\n cat = th.stateCatalog(edgecover_target)\n\n if len(anc_nodes) > 0:\n for ket in list(cat.keys()):\n shopping = Counter(ket)\n if all(shopping[(ii, 0)] == 1 for ii in anc_nodes):\n pass\n else:\n del cat[ket]\n\n # this cause a problem in the optimizer as it actually does not use len(useful_deges)\n # useful_edges = sorted(set(sum(sum(cat.values(),[]), ())))\n # variables = th.stringEdges(useful_edges)\n\n variables = th.stringEdges(graph.edges, imaginary=imaginary)\n\n target = th.targetEquation(target_state.kets, amplitudes=amplitudes, state_catalog=cat)\n norm = th.writeNorm(cat)\n\n # epsilon = 1e-10\n epsilon = 0\n lambdaloss = f'1-({target})/({epsilon} + {norm})'\n # lambdaloss=\"\".join([\"1-\", target, \"/(0+\", norm, \")\"])\n\n func, lossstring = th.buildLossString(lambdaloss, variables)\n return func\n\n\ndef fock_countrate(graph, target_state, num_anc, amplitudes, imaginary=False): # num_anc_pre\n\n total_particle_num = len(target_state.kets[0])\n\n anc_nodes = list(range(graph.num_nodes - num_anc, graph.num_nodes))\n\n edgecover_target = list(itertools.combinations_with_replacement(graph.edges, int(total_particle_num / 2)))\n cat = th.stateCatalog(edgecover_target)\n\n if len(anc_nodes) > 0:\n for ket in list(cat.keys()):\n shopping = Counter(ket)\n if all(shopping[(ii, 0)] == 1 for ii in anc_nodes):\n pass\n else:\n del cat[ket]\n\n # this cause a problem in the optimizer as it actually does not use len(useful_deges)\n # useful_edges = sorted(set(sum(sum(cat.values(),[]), ())))\n # variables = th.stringEdges(useful_edges)\n\n variables = th.stringEdges(graph.edges, imaginary=imaginary)\n\n target = th.targetEquation(target_state.kets, amplitudes=amplitudes, state_catalog=cat)\n norm = th.writeNorm(cat)\n\n # epsilon = 1e-10\n epsilon = 1\n lambdaloss = f'1-({target})/({epsilon} + {norm})'\n # lambdaloss=\"\".join([\"1-\", target, \"/(1+\", norm, \")\"])\n\n func, lossstring = th.buildLossString(lambdaloss, variables)\n return func\n\n\ndef make_lossString_entanglement(graph, sys_dict: dict, imaginary=False,\n var_factor=0):\n \"\"\"\n get the loss functions of a graph for the concurrence:\n C( |Psi> ) = √( 2 * ( 1 - TR_M( ) ) ) \n where TR_M is partial trace (in subsystem M)\n and return is sum over all possible bi-partition\n\n Parameters\n ----------\n edge_list : list\n list of all edges \n sys_dict : dict\n that stores essential information about the quantuum system (see hf.get_sysdict)\n\n Returns\n -------\n func : function as object\n loss function in concurrence as lambda object of current graph.\n lossstring : String\n loss function as string\n\n \"\"\"\n\n cat = graph.state_catalog\n target = th.entanglement_fast(cat, sys_dict, var_factor)\n # norm = th.Norm.fromDictionary(cat, real=sys_dict['real'])\n variables = th.stringEdges(graph.edges, imaginary=imaginary)\n\n lambdaloss = \"\".join([\"\", target])\n func, lossstring = th.buildLossString(lambdaloss, variables)\n\n return func\n\n\ndef sum_of_weights(inputgraph, cnfg):\n # test function for an arbitrary loss function (cnfg[\"loss_func\"] = \"lff\", cnfg[\"lff_name\"] = \"sum_of_weights\")\n return sum(np.abs(inputgraph.weights))\n\n\ndef loss_from_function(graph, cnfg=[]):\n # takes a graph and returns a function of a parameter vector\n def func(vector):\n inputgraph = graph\n for ii, edge in enumerate(graph.edges):\n inputgraph[edge] = vector[ii]\n # get function (defined in this module)\n function = globals()[cnfg[\"lff_name\"]]\n return function(inputgraph, cnfg)\n\n return func\n\n\n# optimizer optimizes first function in list\n# at each optimization step, all functions in list are checked if they satisfy the thresholds\nloss_dic = {'ent': [make_lossString_entanglement],\n 'fid': [fidelity, count_rate],\n 'cr': [count_rate, fidelity],\n 'lff': [loss_from_function],\n 'fockfid': [fock_fidelity, fock_countrate],\n 'fockcr': [fock_countrate, fock_fidelity]\n }\n","repo_name":"artificial-scientist-lab/PyTheus","sub_path":"pytheus/lossfunctions.py","file_name":"lossfunctions.py","file_ext":"py","file_size_in_byte":13902,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"77"} +{"seq_id":"73146662330","text":"\"\"\"\n User: Liujianhan\n Time: 23:51\n tracking time: python -m cProfile cryptarithmetic.py\n \"\"\"\nimport itertools\nimport time\n\n__author__ = 'liujianhan'\nimport re\n\ntmp = str.maketrans('ABC', '123')\nform = 'A+B == C'\ns = form.translate(tmp)\neval(s)\n\nexamples = \"\"\"TWO + TWO == FOUR\nA**2 + B**2 == C**2\nA**2 + BE**2 == BY**2\nX / X == X\nA**N + B**N == C**N and N > 1\nATOM**0.5 == A + TO + M\nGLITTERS is not GOLD\nONE < TWO and FOUR < FIVE\nONE < TWO < THREE\nRAMN == R**3 + RM**3 == N**3 + RX**3\nsum(range(AA)) == BB\nsum(range(POP)) == BOBO\nODD + ODD == EVEN\nPLUTO not in set([PLANETS])\"\"\".splitlines()\n\n\ndef timed_call(fn, *args):\n start = time.perf_counter_ns()\n result = fn(*args)\n end = time.perf_counter_ns()\n tot = (end - start) / 10 ** 9\n return tot, result\n\n\ndef valid(f):\n \"\"\"Formula f is valid if it has no numbers with leading zero and evals true.\"\"\"\n try:\n return not re.findall(r'\\b0[0-9]', f) and eval(f) is True\n except ArithmeticError:\n return False\n\n\ndef fill_in(formula):\n \"\"\"Generate all possible fillings-in of letters in formula with digits.\"\"\"\n letters = ''.join(set(re.findall(r'[A-Z]', formula)))\n for digits in itertools.permutations('1234567890', len(letters)):\n table = str.maketrans(letters, ''.join(digits))\n yield formula.translate(table)\n\n\ndef solve(formula):\n \"\"\"Given a formula like 'ODD + ODD == EVEN', fill in digits to solve it.\n Input formula is a string; output is a digit-filled-in string or None.\"\"\"\n for each in fill_in(formula):\n if valid(each):\n return each\n # return all possible results print or yield\n # yield each\n # print(each)\n\n\ndef compile_word(word):\n \"\"\"Compile a word of uppercase letters as numeric digits.\n E.g., compile_word('YOU') => '(1*U+10*O+100*Y)'\n Non-uppercase words unchanged: compile_word('+') => '+'\"\"\"\n\n # solution 1\n # result = []\n # length = len(word) - 1\n # if word.isupper():\n # for i, ch in enumerate(word):\n # num = 10 ** (length - i)\n # terms = '*'.join([str(num), ch])\n # result.append(terms)\n # result.reverse()\n # return '(' + '+'.join(result) + ')'\n\n # solution 2\n if word.isupper():\n terms = [f\"{10 ** i}*{d}\" for (i, d) in enumerate(word[::-1])]\n return '(' + '+'.join(terms) + ')'\n else:\n return word\n\n\ndef compile_formula(formula, verbose=False):\n \"\"\"Compile formula into a function. Also return letters found, as a str,\n in same order as parms of function.\n e.g:'YOU == ME**2' returns (lambda Y, M, E, U, O: (U+10*O+100*Y) == (E+10*M)**2), 'YMEUO'\"\"\"\n letters = ''.join(set(re.findall(r'[A-Z]', formula)))\n parms = ', '.join(letters)\n tokens = map(compile_word, re.split('([A-Z]+)', formula))\n body = ''.join(tokens)\n f = f\"lambda {parms}: {body}\"\n if verbose:\n print(f)\n return eval(f), letters\n\n\ndef faster_solve(formula):\n \"\"\"Given a formula lik 'ODD + ODD == EVEN', fill in digits to solve it.\n Input formula is a string; output is a digit-fill-in string or None.\n This version precompiles the formula; only one eval per formula.\"\"\"\n f, letters = compile_formula(formula)\n for digits in itertools.permutations(tuple(range(10)), len(letters)):\n try:\n if f(*digits) is True:\n table = str.maketrans(letters, ''.join(map(str, digits)))\n return formula.translate(table)\n except ArithmeticError:\n return False\n\n\ndef test():\n t0 = time.perf_counter_ns()\n for example in examples:\n print(12 * ' ', example)\n timing, result = timed_call(solve, example)\n # when solve function is generator, use following print clause.\n # print(f\"{timing:7.5f} sec: {list(result)}\")\n print(f\"{timing:7.5f} sec: {result}\")\n print('-' * 40)\n print(f\"{((time.perf_counter_ns() - t0) / 10 ** 9):6.4f} seconds total.\")\n\n\ndef test_fast():\n t0 = time.perf_counter_ns()\n for example in examples:\n print(12 * ' ', example)\n timing, result = timed_call(faster_solve, example)\n # when solve function is generator, use following print clause.\n # print(f\"{timing:7.5f} sec: {list(result)}\")\n print(f\"{timing:7.5f} sec: {result}\")\n print('-' * 40)\n print(f\"{((time.perf_counter_ns() - t0) / 10 ** 9):6.4f} seconds total.\")\n\n\nif __name__ == '__main__':\n test() # 0.6 seconds\n # with precompile of eval function, 10 times faster.\n test_fast() # 0.0664 seconds\n","repo_name":"jh-lau/NLP","sub_path":"Design_of_Computer_Program_cs212_Udacity/lesson_2/lesson_6_zebra_puzzle/cryptarithmetic.py","file_name":"cryptarithmetic.py","file_ext":"py","file_size_in_byte":4556,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"} +{"seq_id":"6151052925","text":"import os\nimport typing as t\nfrom collections import OrderedDict\nfrom operator import itemgetter\nfrom pprint import pformat\n\nimport click\nfrom natsort import natsorted\nfrom sanic import Sanic\nfrom sanic.config import Config\n\nfrom sanic_redis_rpc.utils import parse_redis_dsn\n\nDEFAULT_REDIS_CONNECTION_STRING = 'redis://localhost:6379'\nENV_REDIS_PREFIX = 'REDIS_'\n\n\ndef read_redis_config_from_env(env: t.Dict[str, str]) -> t.Dict[str, t.Dict[str, t.Any]]:\n res = OrderedDict()\n redis_env_vars_mapping = {k: v for k, v in env.items() if k.startswith(ENV_REDIS_PREFIX)}\n _sorted_iter = enumerate(natsorted(redis_env_vars_mapping.items(), key=itemgetter(0)))\n\n for i, (rkey, conn_str) in _sorted_iter:\n parsed = parse_redis_dsn(conn_str)\n parsed['id'] = i\n parsed['env_variable'] = rkey\n if not parsed['name']:\n parsed['name'] = 'redis_%s' % i\n\n if not parsed['display_name']:\n parsed['display_name'] = 'Redis instance %s' % i\n\n if parsed['name'] in res:\n raise ValueError(f'Duplicate name `{parsed[\"name\"]}` in `{redis_env_vars_mapping}`')\n\n res[parsed['name']] = parsed\n\n return res\n\n\ndef display_config(config: Config):\n for k, v in config.redis_connections_options.items():\n click.echo(click.style(\n 'Parsed env variable `%s`:' % v['env_variable'],\n fg='yellow'\n ))\n click.echo(click.style(\n pformat(v, compact=True, width=click.get_terminal_size()[0]),\n fg='blue',\n ))\n\n\ndef configure(app: Sanic, env: t.Optional[t.Dict[str, str]] = None, verbose: bool = True) -> Sanic:\n env = env or os.environ\n env.setdefault(ENV_REDIS_PREFIX + '0', DEFAULT_REDIS_CONNECTION_STRING)\n\n app.config.redis_connections_options = read_redis_config_from_env(env)\n\n verbose and display_config(app.config)\n return app\n","repo_name":"night-crawler/sanic-redis-rpc","sub_path":"sanic_redis_rpc/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"40361830019","text":"# -*- coding: utf-8 -*-\nfrom threading import Thread\nfrom time import time\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt5 import NavigationToolbar2QT as NavigationToolbar\nimport matplotlib.pyplot as plt\nfrom tools import get_rate, time_to_formal\nfrom flow_monitor import Monitor\n\n\nclass Ui_Form(object):\n def setupUi(self, Form):\n Form.setWindowTitle(\"流量监测系统\")\n Form.resize(950, 630)\n self.horizontalLayoutWidget = QtWidgets.QWidget(Form)\n self.horizontalLayoutWidget.setGeometry(QtCore.QRect(10, 10, 530, 30))\n self.horizontalLayout = QtWidgets.QHBoxLayout(\n self.horizontalLayoutWidget)\n self.horizontalLayout.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout.setSpacing(10)\n Form.setFixedSize(Form.width(), Form.height())\n self.monitor = Monitor(self)\n \"\"\"主字体\"\"\"\n font = QtGui.QFont()\n font.setFamily(\"Lucida Sans Typewriter\")\n font.setPointSize(10)\n \"\"\"应用选择框\"\"\"\n self.comboBox = QtWidgets.QComboBox(self.horizontalLayoutWidget)\n self.comboBox.setFont(font)\n self.horizontalLayout.addWidget(self.comboBox)\n \"\"\"流量预警线设置\"\"\"\n self.warn_line = QtWidgets.QLineEdit(self.horizontalLayoutWidget)\n self.warn_line.setText(\"1024\")\n self.horizontalLayout.addWidget(self.warn_line)\n self.label = QtWidgets.QLabel(self.horizontalLayoutWidget)\n self.label.setText(\"kb/s\")\n self.horizontalLayout.addWidget(self.label)\n self.start_button = QtWidgets.QPushButton(self.horizontalLayoutWidget)\n self.start_button.setText(\"开���监测\")\n self.start_button.clicked.connect(self.start)\n self.horizontalLayout.addWidget(self.start_button)\n\n self.stop_button = QtWidgets.QPushButton(self.horizontalLayoutWidget)\n self.stop_button.setText(\"停止监测\")\n self.stop_button.clicked.connect(self.stop)\n self.horizontalLayout.addWidget(self.stop_button)\n self.stop_button.setEnabled(False)\n\n self.update_button = QtWidgets.QPushButton(self.horizontalLayoutWidget)\n self.update_button.setText(\"更新列表\")\n self.horizontalLayout.addWidget(self.update_button)\n self.horizontalLayout.setStretch(0, 2)\n self.horizontalLayout.setStretch(1, 1)\n self.horizontalLayout.setStretch(2, 1)\n self.horizontalLayout.setStretch(3, 1)\n self.horizontalLayout.setStretch(4, 1)\n\n self.APPList_label = QtWidgets.QLabel(Form)\n self.APPList_label.setText(\"进程连接列表\")\n self.APPList_label.setStyleSheet(\"font-size: 20px; font-family: 宋体\")\n self.APPList_label.setGeometry(QtCore.QRect(680, 10, 150, 30))\n \"\"\"应用树列表\"\"\"\n self.App_Tree = QtWidgets.QTreeWidget(Form)\n self.App_Tree.header().setVisible(False)\n self.App_Tree.setFont(font)\n self.App_Tree.setStyleSheet(\"QTreeView::item{margin:2px;}\")\n self.App_Tree.setGeometry(QtCore.QRect(560, 40, 380, 580))\n\n self.update_button.clicked.connect(self.refresh_process)\n\n self.verticalLayoutWidget = QtWidgets.QWidget(Form)\n self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 60, 530, 570))\n self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)\n self.verticalLayout.setContentsMargins(0, 0, 0, 0)\n\n self.conList = QtWidgets.QListWidget(self.verticalLayoutWidget)\n self.conList.setFont(font)\n self.conList.setStyleSheet(\"QListView::item{margin:2px;}\")\n self.conList.setMinimumSize(421, 200)\n self.verticalLayout.addWidget(self.conList)\n\n self.figure = plt.figure(figsize=(6, 3))\n self.upload_plot = self.figure.add_subplot(1, 1, 1)\n self.upload_plot.set_xlabel(\"Time (s)\")\n self.upload_plot.set_ylabel(\"Speed (kB/s)\")\n self.figure.tight_layout()\n self.canvas = FigureCanvas(self.figure)\n self.toolbar = NavigationToolbar(self.canvas,\n self.verticalLayoutWidget)\n self.toolbar.hide()\n self.verticalLayout.addWidget(self.toolbar)\n self.verticalLayout.addWidget(self.canvas)\n QtCore.QMetaObject.connectSlotsByName(Form)\n self.comboBox.addItems(self.monitor.getProcessList())\n self.show_process_tree()\n self.timer = QtCore.QTimer(Form)\n self.timer.timeout.connect(self.conList.scrollToBottom)\n\n def show_process_tree(self):\n \"\"\"\n 添加节点\n \"\"\"\n self.App_Tree.clear()\n process_name, process_conn = self.monitor.getProcessConnections()\n for name in process_name:\n item1 = QtWidgets.QTreeWidgetItem(self.App_Tree)\n item1.setText(0, name)\n for connections in process_conn[name]:\n item1_1 = QtWidgets.QTreeWidgetItem(item1)\n item1_1.setText(0, connections)\n\n def alert(self, info):\n \"\"\"\n 警告信息\n \"\"\"\n alert_font = QtGui.QFont()\n alert_font.setFamily(\"Lucida Sans Typewriter\")\n alert_font.setPointSize(14)\n now = time_to_formal(time())\n item = QtWidgets.QListWidgetItem(\"%s\\n%s\" % (now, info), self.conList)\n item.setForeground(QtGui.QColor('red'))\n item.setFont(alert_font)\n\n def refresh_process(self):\n \"\"\"\n 刷新进程列表\n \"\"\"\n self.comboBox.clear()\n self.comboBox.addItems(self.monitor.getProcessList())\n self.show_process_tree()\n\n def setSpeed(self):\n \"\"\"\n 设置速度图\n \"\"\"\n upload = []\n download = []\n speed = int(self.warn_line.text())\n # 警告线\n alert = [speed for _ in range(60)]\n while not self.monitor.start_flag.is_set():\n info = get_rate(None)\n plt.cla()\n self.upload_plot.set_xlabel(\"Time (s)\")\n self.upload_plot.set_ylabel(\"Speed (kB/s)\")\n info[1] >>= 10\n info[0] >>= 10\n upload.append(info[1])\n download.append(info[0])\n if len(upload) >= 60:\n upload.pop(0)\n download.pop(0)\n self.upload_plot.plot(\n alert, 'red', linewidth='2', label=\"Warning\")\n self.upload_plot.legend(loc='upper right')\n self.upload_plot.plot(\n upload, 'darkorange', linewidth='1', label=\"Upload\")\n self.upload_plot.legend(loc='upper right')\n self.upload_plot.plot(\n download, 'blue', linewidth='1', label=\"Download\")\n self.upload_plot.legend(loc='upper right')\n self.canvas.draw()\n # 流量警告\n # 当速度大于设定值时流量警告\n if info[1] > speed or info[0] > speed:\n self.alert(\"警告: 流量已超过预警线 %dkB/s!\" % speed)\n\n def start(self):\n \"\"\"\n 开始检测\n \"\"\"\n if self.monitor.start_flag.is_set():\n self.start_button.setEnabled(False)\n self.stop_button.setEnabled(True)\n self.comboBox.setEnabled(False)\n self.warn_line.setEnabled(False)\n self.monitor.start(self.comboBox.currentText())\n Thread(target=self.setSpeed, daemon=True).start()\n self.timer.start(1000)\n\n def stop(self):\n \"\"\"\n 停止检测\n \"\"\"\n if not self.monitor.start_flag.is_set():\n self.monitor.stop()\n self.timer.stop()\n self.start_button.setEnabled(True)\n self.stop_button.setEnabled(False)\n self.comboBox.setEnabled(True)\n self.warn_line.setEnabled(True)\n\n\ndef start_monitor():\n \"\"\"\n 调用监测系统\n \"\"\"\n app = QtWidgets.QApplication([])\n widget = QtWidgets.QWidget()\n ui = Ui_Form()\n ui.setupUi(widget)\n widget.show()\n app.exec()\n\n\nif __name__ == \"__main__\":\n start_monitor()\n","repo_name":"zhanghuanhao/WireWhale","sub_path":"monitor_system.py","file_name":"monitor_system.py","file_ext":"py","file_size_in_byte":8085,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"77"} +{"seq_id":"1399786513","text":"__author__ = 'indiquant'\n\n\nimport urllib2\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nfrom enum import Enum\nimport pandas as pd\nimport logging\nlogging.basicConfig(format='%(levelname)s %(asctime)s:%(message)s', level=logging.DEBUG)\n\n\ndef get_options_nse(undl):\n\n try:\n undltype = _undltypes[undl]\n\n except KeyError:\n undltype = 'stock'\n\n df = None\n\n for exp in _nse_options_expiries:\n pg = get_option_page(undl, exp, undltype)\n sp = BeautifulSoup(pg, 'lxml')\n t, s = get_live(sp.body)\n opts = parse_options_body(sp.body)\n\n if df is None:\n df = get_sql_df(undl, t, s, exp, opts, undltype)\n\n else:\n df = df.append(get_sql_df(undl, t, s, exp, opts, undltype))\n\n return df\n\n\ndef load_options_nse(undl, path, sep):\n df = get_options_nse(undl)\n df.to_csv(path, index=False, sep=sep)\n\n\n_nse_options_expiries = [\n '2016-10-27',\n '2016-11-24',\n '2016-12-29',\n '2017-03-30'\n]\n\n\n_undltypes = {\n 'NIFTY': 'index'\n}\n\n\n_months = {'JAN': 1,\n 'FEB': 2,\n 'MAR': 3,\n 'APR': 4,\n 'MAY': 5,\n 'JUN': 6,\n 'JUL': 7,\n 'AUG': 8,\n 'SEP': 9,\n 'OCT': 10,\n 'NOV': 11,\n 'DEC': 12}\n\n\nclass EnumNseOptionTable(Enum):\n c_chart = 1\n c_oi = 2\n c_chng_oi = 3\n c_volume = 4\n c_iv = 5\n c_lastpx = 6\n c_chng = 7\n c_bidqty = 8\n c_bidpx = 9\n c_askpx = 10\n c_askqty = 11\n k = 12\n p_bidqty = 13\n p_bidpx = 14\n p_askpx = 15\n p_askqty = 16\n p_chng = 17\n p_lastpx = 18\n p_iv = 19\n p_volume = 20\n p_chng_oi = 21\n p_oi = 22\n p_chart = 23\n\n\nclass EnumOptionTable(Enum):\n undl = 1\n undl_type = 2\n spot = 3\n opt_type = 4\n exc_type = 5\n expiry = 6\n strike = 7\n recdate = 8\n rectime = 9\n bidpx = 10\n bidqty = 11\n askpx = 12\n askqty = 13\n lastpx = 14\n volume = 15\n\n\ndef month_number(mmm):\n \"\"\"\n :type mmm: basestring\n \"\"\"\n return _months[mmm.upper()]\n\n\ndef yyyymmdd(d):\n \"\"\"\n :type d: datetime\n \"\"\"\n return int(d.strftime('%Y%m%d'))\n\n\ndef hhmmss(d):\n \"\"\"\n :type d: datetime\n \"\"\"\n return int(d.strftime('%H%M%S'))\n\n\nget_text = lambda x: x.getText()\n\n\nfuture_site = 'http://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuoteFO.jsp?' \\\n + 'underlying=<symbol>&instrument=<imnt_type>'\noption_site = 'https://www.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?' \\\n + 'segmentLink=17&instrument={instrument}&symbol={symbol}&date={expiry}'\n\n\nfut_imnt_type = {'stock': 'FUTSTK', 'index': 'FUTIDX'}\nopt_instrument_type = {'stock': 'OPTSTK', 'index': 'OPTIDX'}\n\n\ndef get_option_page(symbol, exp='-', undltype='index'):\n \"\"\"\n :type exp: basestring\n \"\"\"\n\n if exp == '-':\n site = option_site.format(symbol=symbol, instrument=opt_instrument_type[undltype], expiry='-')\n\n else:\n site = option_site.format(symbol=symbol, instrument=opt_instrument_type[undltype],\n expiry=datetime.strptime(exp, '%Y-%m-%d').strftime('%d%b%Y').upper())\n\n try:\n\n logging.debug(\"Getting data from:\" + site)\n\n hdr = {'User-Agent': 'Web-Scraping',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',\n 'Accept-Encoding': 'none',\n 'Accept-Language': 'en-US,en;q=0.8',\n 'Connection': 'keep-alive'}\n\n req = urllib2.Request(site, headers=hdr)\n\n page = urllib2.urlopen(req).read()\n\n return page\n\n except:\n logging.debug(\"Check the site: \" + str(site))\n raise\n\n\ndef get_time(opt):\n \"\"\"\n :type opt: BeautifulSoup\n \"\"\"\n children = opt.find_all('span')\n\n for ch in children:\n\n txt = ch.text.replace(',', '').lower()\n\n if txt[:5] == 'as on':\n _, _, mth, dd, yyyy, hhmmss, _ = txt.strip().split(' ')\n\n hh, mm, ss = hhmmss.split(\":\")\n\n return datetime(int(yyyy), month_number(mth), int(dd), int(hh), int(mm), int(ss))\n\n return None\n\n\ndef get_live(opt):\n \"\"\"\n :type opt: BeautifulSoup\n \"\"\"\n children = opt.find_all('span')\n\n t, s = None, None\n\n for ch in children:\n\n txt = ch.text.replace(',', '').lower()\n\n if txt.split(' ')[:2] == ['as', 'on']:\n _, _, mth, dd, yyyy, hms, _ = txt.strip().split(' ')\n\n hh, mm, ss = hms.split(\":\")\n\n t = datetime(int(yyyy), month_number(mth), int(dd), int(hh), int(mm), int(ss))\n\n elif txt.split(':')[0] in ('underlying stock', 'underlying index'):\n\n s = float(txt.split(':')[1].strip(' ').split(' ')[1])\n\n return t, s\n\n\ndef get_expiries(body):\n \"\"\"\n :type body: BeautifulSoup\n \"\"\"\n\n _ex = body.find_all('select', {'id': 'date', 'name': 'date'})\n\n ex = []\n\n for ch in _ex:\n\n for _e in ch:\n try:\n ex.append(datetime.strptime(_e.text, '%d%b%Y').date())\n\n except ValueError:\n pass\n\n except AttributeError:\n pass\n\n return ex\n\n\ndef parse_options_body(opt_body):\n\n opt_tbl = opt_body.find('table', {'id': 'octable'})\n\n cols = []\n rows = []\n\n for r in opt_tbl.find_all('tr'):\n\n if r.text.find('CALLS') >= 0 and r.text.find('PUTS') >= 0:\n pass\n\n else:\n\n drow = r.find_all('td')\n\n if not drow:\n head = r.find_all('th')\n for col in head:\n cols.append(str(col.contents[0]))\n\n else:\n _r = ()\n for d in drow:\n _r += (process_cell(d),)\n\n rows.append(_r)\n\n return rows\n\n\ndef get_sql_df(undl, tm, spot, exp, optrows, undltype='index'):\n\n d = [(EnumOptionTable.undl.name,\n EnumOptionTable.undl_type.name,\n EnumOptionTable.spot.name,\n EnumOptionTable.opt_type.name,\n EnumOptionTable.exc_type.name,\n EnumOptionTable.expiry.name,\n EnumOptionTable.strike.name,\n EnumOptionTable.recdate.name,\n EnumOptionTable.rectime.name,\n EnumOptionTable.bidpx.name,\n EnumOptionTable.bidqty.name,\n EnumOptionTable.askpx.name,\n EnumOptionTable.askqty.name,\n EnumOptionTable.lastpx.name,\n EnumOptionTable.volume.name)]\n\n for r in optrows:\n try:\n c_row = (undl,\n undltype,\n spot,\n 'C',\n 'E',\n yyyymmdd(datetime.strptime(exp, '%Y-%m-%d')),\n r[EnumNseOptionTable.k.value - 1],\n yyyymmdd(tm),\n hhmmss(tm),\n r[EnumNseOptionTable.c_bidpx.value - 1],\n r[EnumNseOptionTable.c_bidqty.value - 1],\n r[EnumNseOptionTable.c_askpx.value - 1],\n r[EnumNseOptionTable.c_askqty.value - 1],\n r[EnumNseOptionTable.c_lastpx.value - 1],\n r[EnumNseOptionTable.c_volume.value - 1])\n \n p_row = (undl,\n undltype,\n spot,\n 'P',\n 'E',\n yyyymmdd(datetime.strptime(exp, '%Y-%m-%d')),\n r[EnumNseOptionTable.k.value - 1],\n yyyymmdd(tm),\n hhmmss(tm),\n r[EnumNseOptionTable.p_bidpx.value - 1],\n r[EnumNseOptionTable.p_bidqty.value - 1],\n r[EnumNseOptionTable.p_askpx.value - 1],\n r[EnumNseOptionTable.p_askqty.value - 1],\n r[EnumNseOptionTable.p_lastpx.value - 1],\n r[EnumNseOptionTable.p_volume.value - 1])\n \n d.append(c_row)\n d.append(p_row)\n \n except:\n pass\n \n return pd.DataFrame(d[1:], columns=d[0])\n\n\ndef process_cell(d):\n\n try:\n\n if d.a:\n if d.a.b:\n if d.a.b.contents[0].strip() == u'-':\n return None\n\n else:\n return float(d.a.b.contents[0].strip().replace(',', ''))\n\n else:\n if d.a.contents[0].strip() == u'-':\n return None\n\n else:\n return float(d.a.contents[0].strip().replace(',', ''))\n\n else:\n if d.contents[0].strip() == '-':\n return None\n\n else:\n return float(d.contents[0].strip().replace(',', ''))\n\n except TypeError:\n return None\n\n except IndexError:\n return None\n ","repo_name":"indiquant/findl","sub_path":"findl/weblib/nse.py","file_name":"nse.py","file_ext":"py","file_size_in_byte":8877,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"5174082589","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 22 00:16:58 2022\n\n@author: andrea\n\"\"\"\nfrom psf_generator import PSF_simulator\nfrom numpy import pi\nfrom magicgui import magicgui\nimport napari\nfrom napari.layers import Image, Points, Labels\n\num = 1.0\nmm = 1000 * um\ndeg = pi/180\n\n\n@magicgui(auto_call=True)\ndef set_values(NA:float = 0.7,\n wavelength:float = 0.5320*um,\n n:float = 1.00,\n Nxy:int = 127,\n Nz:int = 5,\n dxy:float = 0.05 * um,\n dz:float = 0.4 * um\n ):\n gen.NA = NA # Numerical aperture\n gen.n = n # refractive index at the object\n gen.wavelength = wavelength\n gen.Nxy = Nxy\n gen.Nz = Nz\n gen.dr = dxy\n gen.dz = dz\n \n print(gen.NA)\n\n \n@magicgui(call_button=\"Add slab\") \ndef add_slab(n1:float = 1.51, # refractive index of the slab\n thickness:float = 170 * um, # slab thickness\n alpha:float = 0 * deg # angle of the slab relative to the y axis) \n )->Image:\n set_values() \n gen.generate_kspace()\n gen.add_slab_scalar(n1, thickness, alpha)\n gen.generate_pupil()\n gen.generate_3D_PSF()\n print(gen.write_name())\n return Image(gen.PSF3D,\n name=gen.write_name(),\n colormap='viridis')\n \n \n@magicgui(call_button=\"Generate PSF\") \ndef generate_psf()->Image:\n set_values() \n gen.generate_kspace()\n gen.generate_pupil()\n gen.generate_3D_PSF()\n # Show results \n # gen.print_values()\n # gen.show_pupil()\n # gen.plot_phase()\n # gen.show_PSF_projections(aspect_ratio=1,\n # mode='sum') \n gen.plot_psf_profile()\n \n print(gen.write_name())\n return Image(gen.PSF3D,\n name=gen.write_name(),\n colormap='viridis')\n \nviewer = napari.Viewer()\ngen = PSF_simulator() \n\nviewer.window.add_dock_widget((set_values, generate_psf), name = 'PSF generators',\n area='right')\nviewer.window.add_dock_widget(add_slab, name = 'Abberrations',\n area='right')\n\nnapari.run() ","repo_name":"andreabassi78/Napari_Applications","sub_path":"PSF_simulator/old/napari_psf_simulator.py","file_name":"napari_psf_simulator.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"1594332692","text":"from art import logo, vs\nfrom game_data import data\nimport replit\nimport random\n\n# define variable\ncompare_name_a = ''\ncompare_name_b = ''\ncompare_description_a = ''\ncompare_description_b = ''\ncompare_follower_a = ''\ncompare_follower_b = ''\ncompare_country_a = ''\ncompare_country_b = ''\nscore = 0\ncontinue_game = True\nfirst_comparison = True\n\n# define a function to get data Compare_A and Compare_B from game_data.data{}\n# check the result and if this is the right guess\n# calculate score. if correct then \"score += 1\"\ndef compare(user_guess, user_score, follower_a, follower_b, continue_game):\n # compare the follower count\n if follower_a > follower_b:\n answer = 'a'\n elif follower_b > follower_a:\n answer = 'b'\n\n # clear screen\n # print the logo and the score\n replit.clear()\n print(logo)\n # compare the answer and the guess\n if answer == user_guess:\n user_score += 1\n print(f\"You're right! Current score: {user_score}.\")\n else:\n print(f\"Sorry, that's wrong. Final score: {user_score}\")\n continue_game = False\n\n return user_score, continue_game\n\n\n\n\n# define a function to randomly choose A and B from data\ndef random_choose():\n name = ''\n description = ''\n country = ''\n followers = ''\n data_set = random.choice(\n data) #return a randomly picked dictionary from data[]\n # print (data_set) # data_set{} is a dictionary type\n # print(data_set.values())\n # print(data_set.keys())\n for index in data_set:\n #******* \"i\" is the key, print key and value out from the dictionary *******\n # for i in d:\n # print i, d[i]\n if index == 'name':\n name = data_set[index]\n if index == 'description':\n description = data_set[index]\n if index == 'country':\n country = data_set[index]\n if index == 'follower_count':\n followers = data_set[index]\n return name, description, country, followers\n\n\n\n# program start:\n\nprint(logo)\nwhile continue_game == True:\n # if this is the first comparision, then randomly choose Compare_A\n # if not, then replace Compare_A with Compare_B\n # print the name and info. e.g.: Compare A: Shakira, a Musician, from Colombia.\n if first_comparison == True:\n compare_name_a, compare_description_a, compare_country_a, compare_follower_a = random_choose(\n )\n first_comparison = False\n else:\n compare_name_a, compare_description_a, compare_country_a, compare_follower_a = compare_name_b, compare_description_b, compare_country_b, compare_follower_b\n print(\n f\"Compare A: {compare_name_a}, a {compare_description_a}, from {compare_country_a}. {compare_follower_a}\"\n )\n\n print(vs)\n # print the name and info. e.g.: Against B: UEFA Champions League, a Club football competition, from Europe\n # check if the compare_name_a is the same as compare_name_b, if yes, then random_choose again.\n compare_name_b = compare_name_a\n while compare_name_b == compare_name_a:\n compare_name_b, compare_description_b, compare_country_b, compare_follower_b = random_choose(\n )\n print(\n f\"Against B: {compare_name_b}, {compare_description_b}, from {compare_country_b}. {compare_follower_b}\"\n )\n\n # ask user to guess who has more followers\n guess = input(f\"Who has more followers? Type 'A' or 'B': \").lower()\n\n # compare Compare_A and Compare_B\n # if wrong, then end the game, print out the final score.\n # if right, print the current score.\n # use a loop to start over the game.(no need to clear the screen)\n # Continue the game from \"Compare A: Neymar, a Footballer, from Brasil.\" and print vs string\n\n score, continue_game = compare(user_guess = guess, user_score = score, follower_a = compare_follower_a, follower_b = compare_follower_b, continue_game = continue_game)\n","repo_name":"abicraf/100-Days-of-Code-The-Complete-Python-Pro-Bootcamp-for-2023","sub_path":"Day13_HigherLowerGame/Day13_HigherLowerGame.py","file_name":"Day13_HigherLowerGame.py","file_ext":"py","file_size_in_byte":3887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"48118479986","text":"\"\"\"\n\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nimport bluepyopt as bpop\nimport bluepyopt.ephys as ephys\nimport bluepyopt.ephys_pyNN as epyn\n\nimport logging\nlogging.basicConfig(filename='population_pyNN.log', filemode='w', level=logging.DEBUG)\n\nPLOT_FIGURES = True\nPOP_SIZE = 10\nN_GEN = 10\n\n# patch the bpop.optimisations module\n\ndef evaluate_fitnesses(toolbox, individuals):\n # individuals is a list of lists, each list containing the parameters for one individual\n return toolbox.evaluate(individuals)\n\nbpop.optimisations.evaluate_fitnesses = evaluate_fitnesses\n\n\n\nparameters = {'tau_refrac': [0.1, 10.0], 'a': [0.0, 50.0], 'tau_m': [1.0, 50.0],\n 'cm': [0.1, 10.0], 'delta_T': [0.1, 10.0], 'v_thresh': [-70.0, -41.0],\n 'b': [0.0, 1.0], 'v_reset': [-80.0, -50.0], 'tau_w': [10.0, 1000.0],\n 'v_rest': [-80.0, -50.0]}\n\nparameter_objects = [ephys.parameters.ArrayParameter(name=name, bounds=bounds, frozen=False)\n for name, bounds in parameters.items()]\n\n\nsimple_population = epyn.models.PyNNPopulationModel(name='simple_population',\n size=POP_SIZE,\n celltype='EIF_cond_exp_isfa_ista',\n params=parameter_objects,\n initial_values={'v': -70.0, 'w': 0.0})\n\nsweep_protocols = []\nfor protocol_name, amplitude in [('step1', 0.4), ('step2', 2.0)]:\n stim = epyn.stimuli.PyNNSquarePulse(\n step_amplitude=amplitude,\n step_delay=100,\n step_duration=50,\n total_duration=200)\n rec = epyn.recordings.PyNNRecording(\n name='%s.v' % protocol_name,\n variable='v')\n protocol = ephys.protocols.SweepProtocol(protocol_name, [stim], [rec])\n sweep_protocols.append(protocol)\ntwostep_protocol = ephys.protocols.SequenceProtocol('twostep', protocols=sweep_protocols)\n\n\nsimulator = epyn.simulators.PyNNSimulator('nest')\n\ndefault_params = {'tau_refrac': np.random.normal(2.0, 0.4, size=POP_SIZE),\n 'a': np.random.normal(4.0, 1.0, size=POP_SIZE),\n 'tau_m': np.random.normal(10.0, 1.0, size=POP_SIZE),\n 'cm': np.random.normal(0.5, 0.1, size=POP_SIZE),\n 'delta_T': np.random.normal(2.0, 0.4, size=POP_SIZE),\n 'v_thresh': -np.random.normal(50.0, 1.0, size=POP_SIZE),\n 'b': np.random.normal(0.1, 0.01, size=POP_SIZE),\n 'v_reset': np.random.normal(-70.0, 1.0, size=POP_SIZE),\n 'tau_w': np.random.normal(100.0, 20.0, size=POP_SIZE),\n 'v_rest': np.random.normal(-70.0, 2.0, size=POP_SIZE)}\n\nresponses = twostep_protocol.run(cell_model=simple_population,\n param_values=default_params,\n sim=simulator)\n\n\ndef plot_responses(responses, channels):\n plt.subplot(2,1,1)\n for channel in channels:\n plt.plot(responses['step1.v'][channel]['time'], responses['step1.v'][channel]['voltage'], label='step1')\n plt.legend()\n plt.subplot(2,1,2)\n for channel in channels:\n plt.plot(responses['step2.v'][channel]['time'], responses['step2.v'][channel]['voltage'], label='step2')\n plt.legend()\n plt.tight_layout()\n\nif PLOT_FIGURES:\n plot_responses(responses, [0, 3])\n plt.savefig(\"population_pyNN.png\")\n\n\n###\nimport efel\n\ndef features(time, voltage, stim_limits, feature_names):\n start, end = stim_limits\n traces = [{'T': time, 'V': voltage, 'stim_start': [start], 'stim_end': [end]}]\n return efel.getFeatureValues(traces, feature_names)\n\nprint(features(responses['step1.v'][0]['time'],\n responses['step1.v'][0]['voltage'],\n (100.0, 150.0),\n ['Spikecount', 'voltage_base']))\nprint(features(responses['step2.v'][0]['time'],\n responses['step2.v'][0]['voltage'],\n (100.0, 150.0),\n ['Spikecount', 'voltage_base']))\n###\n\n\n\nefel_feature_means = {'step1': {'Spikecount': 1}, 'step2': {'Spikecount': 5}}\n\nobjectives = []\n\nfor protocol in sweep_protocols:\n stim_start = protocol.stimuli[0].step_delay\n stim_end = stim_start + protocol.stimuli[0].step_duration\n for efel_feature_name, mean in efel_feature_means[protocol.name].iteritems():\n feature_name = '%s.%s' % (protocol.name, efel_feature_name)\n feature = ephys.efeatures.eFELFeature(\n feature_name,\n efel_feature_name=efel_feature_name,\n recording_names={'': '%s.v' % protocol.name},\n stim_start=stim_start,\n stim_end=stim_end,\n exp_mean=mean,\n exp_std=0.05 * mean)\n objective = ephys.objectives.SingletonObjective(\n feature_name,\n feature)\n objectives.append(objective)\n\nscore_calc = ephys.objectivescalculators.ObjectivesCalculator(objectives)\n\n\npop_evaluator = epyn.evaluators.PopulationEvaluator(\n cell_model=simple_population,\n param_names=[p.name for p in parameter_objects],\n fitness_protocols={twostep_protocol.name: twostep_protocol},\n fitness_calculator=score_calc,\n isolate_protocols=False,\n sim=simulator)\n\nprint(pop_evaluator.evaluate_with_dicts(default_params))\n\n\n# ==========\n\noptimisation = bpop.optimisations.DEAPOptimisation(\n evaluator=pop_evaluator,\n offspring_size=POP_SIZE)\n\nfinal_pop, hall_of_fame, logs, hist = optimisation.run(max_ngen=N_GEN)\n\n#print('Final population: ', final_pop)\n\nbest_ind = hall_of_fame[0]\nprint('Best individual: ', best_ind)\nprint('Fitness values: ', best_ind.fitness.values)\n\nbest_ind_dict = pop_evaluator.param_dict(best_ind)\nprint(pop_evaluator.evaluate_with_dicts(best_ind_dict))\n\nif PLOT_FIGURES:\n plt.clf()\n plot_responses(twostep_protocol.run(cell_model=simple_population, param_values=best_ind_dict, sim=simulator),\n channels=[0])\n plt.savefig(\"population_pyNN_best.png\")\n\n\ngen_numbers = logs.select('gen')\nmin_fitness = logs.select('min')\nmax_fitness = logs.select('max')\nfor gen, fitness in zip(gen_numbers, min_fitness):\n print(gen, fitness)\nif PLOT_FIGURES:\n plt.clf()\n plt.plot(gen_numbers, min_fitness, label='min fitness')\n plt.xlabel('generation #')\n plt.ylabel('score (# std)')\n plt.legend()\n plt.xlim(min(gen_numbers) - 1, max(gen_numbers) + 1)\n plt.ylim(0.9*min(min_fitness), 1.1 * max(min_fitness))\n plt.savefig(\"population_pyNN_fitness.png\")\n\n","repo_name":"apdavison/simplification","sub_path":"population_pyNN.py","file_name":"population_pyNN.py","file_ext":"py","file_size_in_byte":6674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"17710881267","text":"import cartopy.crs as ccrs\nimport cartopy.feature as cfeature\nfrom cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mticker\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport numpy as np\nimport seaborn as sb\nfrom tqdm import tqdm\nimport xarray as xr\n\nfrom gogoesgone import processing as pr\nfrom gogoesgone import zarr_access as za\n\nhour = 17\nyear = 2020\ndayofyear = 24\nchannel = 13\nproduct = \"ABI-L2-CMIPF\" #'ABI-L1b-RadF'\nsatellite = \"goes16\" #'goes17'\n\n\ndef main():\n gs = za.generate_globsearch_string(year, dayofyear, hour)\n flist = za.generate_url_list(gs)\n m = za.get_mapper_from_mzz(flist)\n\n img = pr.Image(m)\n extent = (-62, -48, 10, 20)\n\n subset = img.subset_region_from_latlon_extents(extent, unit=\"degree\")\n\n sb.set_context(\"paper\")\n\n for t in tqdm(subset.t):\n fig = plt.figure(figsize=(8, 5))\n\n ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())\n\n im = subset.CMI.sel(t=t).plot(\n ax=ax,\n x=\"lon\",\n y=\"lat\",\n cmap=\"cubehelix_r\",\n add_colorbar=False,\n vmin=280,\n vmax=300,\n )\n subset.CMI.sel(t=t).plot.contour(\n ax=ax,\n x=\"lon\",\n y=\"lat\",\n cmap=\"Reds\",\n add_colorbar=False,\n levels=[\n 290,\n ],\n linewidths=0.5,\n )\n ax.set_extent(extent, crs=ccrs.PlateCarree())\n ax.coastlines(resolution=\"10m\", color=\"black\", linewidth=0.5)\n\n time_str = str(t.values).rsplit(\":\", 1)[0].replace(\":\", \"h\")\n plt.title(time_str)\n plt.colorbar(im, orientation=\"horizontal\")\n\n gl = ax.gridlines(\n ccrs.PlateCarree(),\n linewidth=1,\n color=\"w\",\n alpha=0.5,\n linestyle=\":\",\n draw_labels=True,\n )\n gl.top_labels = False\n gl.right_labels = False\n gl.xlines = True\n gl.ylines = True\n gl.xlocator = mticker.FixedLocator(np.arange(-180, 180, 2.5))\n gl.ylocator = mticker.FixedLocator(np.arange(-90, 90, 2.5))\n gl.xformatter = LONGITUDE_FORMATTER\n gl.yformatter = LATITUDE_FORMATTER\n gl.xlabel_style = {\"color\": \"grey\"}\n gl.ylabel_style = {\"color\": \"grey\"}\n plt.savefig(\n f\"notebooks/Plots/{satellite}_{product}_{channel}_{time_str}_{extent}.png\",\n dpi=300,\n )\n plt.close()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Geet-George/gogoesgone","sub_path":"scripts/plot_eurec4a.py","file_name":"plot_eurec4a.py","file_ext":"py","file_size_in_byte":2570,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"} +{"seq_id":"36489878982","text":"from django.contrib.auth import get_user_model\nfrom rest_framework import serializers\n\nfrom apps.address.api.serializers import AddressSerializer\nfrom apps.cook.models import (\n Cook,\n KitchenPremises,\n MenuCategory,\n MenuItem,\n MenuSubItem,\n FSCCatalogue,\n FSCCatalogueImage, CookOrderDetails\n)\n\nfrom apps.order.models import OrderMenuSubItem, Order, OrderMenuItem\nfrom apps.order.api.service import get_user_default_address\n\nUser = get_user_model()\n\n\nclass KitchenPremisesSerializer(serializers.ModelSerializer):\n cook_id = serializers.CharField(source='cook.cook_id', max_length=14, allow_null=True, read_only=True)\n kitchen_premises = serializers.FileField(required=False)\n\n class Meta:\n model = KitchenPremises\n fields = ('document_id', 'kitchen_premises', 'cook', 'cook_id')\n\n\nclass CookSerializer(serializers.ModelSerializer):\n image = serializers.FileField(required=False)\n dob = serializers.DateField(required=True)\n country_id = serializers.IntegerField(required=True)\n cook_name = serializers.CharField(source='user.username', allow_null=True, read_only=True)\n email = serializers.CharField(source='user.email', allow_null=True, read_only=True)\n address = serializers.SerializerMethodField()\n\n class Meta:\n model = Cook\n fields = (\n 'id', 'cook_id', 'user_id', 'image', 'dob', 'country_id', 'work_permit', 'govt_cert', 'cook_name',\n 'email', 'address', 'insurance_cert', 'medical_clearance', 'food_cert', 'kitchen_premises', 'status', 'total_review',\n 'avg_star_rating'\n )\n depth = 1\n read_only_fields = ('cook_id', 'user_id', 'status')\n\n def get_address(self, obj):\n address = get_user_default_address(user_id=obj.user_id)\n return address.address_id\n\n\nclass CookFSCDataSerializer(serializers.ModelSerializer):\n class Meta:\n model = Cook\n fields = ('medical_clearance', 'food_cert', 'kitchen_premises')\n depth = 1\n\n\nclass MenuCategorySerializer(serializers.ModelSerializer):\n class Meta:\n model = MenuCategory\n fields = ('id', 'category_name', 'category_icon')\n\n def validate(self, attrs):\n print(attrs.get(\"category_icon\"))\n return super().validate(attrs)\n\n\nclass SubMenuItemSerializer(serializers.ModelSerializer):\n class Meta:\n model = MenuSubItem\n fields = (\n 'id', 'title', 'price', 'prepare_time', 'total_calories', 'nutrition_info',\n 'cultural_facts', 'commercial_info', 'menu_item'\n )\n extra_kwargs = {\n \"title\": {\"required\": False},\n }\n\n\nclass SubMenuItemSerializerAV(serializers.ModelSerializer):\n\n class Meta:\n model = MenuSubItem\n fields = \"__all__\"\n\n\nclass Base64ImageField(serializers.ImageField):\n \"\"\"\n A Django REST framework field for handling image-uploads through raw post data.\n It uses base64 for encoding and decoding the contents of the file.\n\n Heavily based on\n https://github.com/tomchristie/django-rest-framework/pull/1268\n\n Updated for Django REST framework 3.\n \"\"\"\n\n def to_internal_value(self, data):\n from django.core.files.base import ContentFile\n import base64\n import six\n import uuid\n\n # Check if this is a base64 string\n if isinstance(data, six.string_types):\n # Check if the base64 string is in the \"data:\" format\n if 'data:' in data and ';base64,' in data:\n # Break out the header from the base64 content\n header, data = data.split(';base64,')\n\n # Try to decode the file. Return validation error if it fails.\n try:\n decoded_file = base64.b64decode(data)\n except TypeError:\n self.fail('invalid_image')\n\n # Generate file name:\n file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough.\n # Get the file name extension:\n file_extension = self.get_file_extension(file_name, decoded_file)\n\n complete_file_name = \"%s.%s\" % (file_name, file_extension,)\n\n data = ContentFile(decoded_file, name=complete_file_name)\n\n return super(Base64ImageField, self).to_internal_value(data)\n\n def get_file_extension(self, file_name, decoded_file):\n import imghdr\n\n extension = imghdr.what(file_name, decoded_file)\n extension = \"jpg\" if extension == \"jpeg\" else extension\n\n return extension\n\n\nclass MenuItemSerializerAV(serializers.ModelSerializer):\n # menu_sub_items = SubMenuItemSerializerAV(read_only=True)\n class Meta:\n model = MenuItem\n fields = '__all__'\n\n\nclass MenuItemSerializer(serializers.ModelSerializer):\n menu_sub_items = SubMenuItemSerializer(many=True)\n # Data URI Type\n item_img = Base64ImageField(\n max_length=None, use_url=True, required=False\n )\n cook_id = serializers.CharField(source='cook.cook_id', allow_null=True, read_only=True)\n cook_name = serializers.CharField(source='cook.user.username', allow_null=True, read_only=True)\n category_name = serializers.CharField(source='category.category_name', allow_null=True, read_only=True)\n category_id = serializers.PrimaryKeyRelatedField(source='category', queryset=MenuCategory.objects.all())\n size = serializers.ListSerializer(child=serializers.DictField(), default=list)\n\n class Meta:\n model = MenuItem\n fields = (\n 'id', 'item_number', 'title', 'item_img', 'category_id', 'category_name', 'cook_id', 'cook_name',\n 'size',\n 'warning', 'prepare_time', 'item_type', 'nutrition_info', 'cultural_facts', 'commercial_info',\n 'status', 'created_at', 'updated_at', 'menu_sub_items'\n )\n read_only_fields = ('item_number', 'cook', 'created_at', 'updated_at',)\n extra_kwargs = {\n \"title\": {\"required\": False},\n \"size\": {\"required\": True},\n \"warning\": {\"required\": True},\n \"item_type\": {\"required\": True},\n \"nutrition_info\": {\"required\": True},\n \"cultural_facts\": {\"required\": True},\n \"commercial_info\": {\"required\": True}\n }\n\n def create(self, validated_data):\n request = self.context['request']\n menu_sub_items = validated_data.pop('menu_sub_items', [])\n menu_item = MenuItem.objects.create(**validated_data, cook=request.user.cook)\n if menu_sub_items:\n msi = []\n for item in menu_sub_items:\n msi.append(MenuSubItem(menu_item=menu_item, **item))\n MenuSubItem.objects.bulk_create(msi)\n return menu_item\n\n def sub_item_instance(self, item_id):\n try:\n return MenuSubItem.objects.get(id=item_id)\n except Exception as e:\n return None\n\n def update(self, instance, validated_data):\n menu_sub_items_data = validated_data.pop('menu_sub_items', [])\n\n super(MenuItemSerializer, self).update(instance=instance, validated_data=validated_data)\n\n if menu_sub_items_data:\n create_sub_item_list = []\n for sub_item in menu_sub_items_data:\n if \"id\" in sub_item.keys():\n sub_item_id = sub_item.get('id')\n menu_sub_item = self.sub_item_instance(sub_item_id)\n if menu_sub_item:\n for (key, value) in sub_item.items():\n setattr(menu_sub_item, key, value)\n menu_sub_item.save()\n else:\n create_sub_item_list.append(MenuSubItem(menu_item=instance, **sub_item))\n if create_sub_item_list:\n MenuSubItem.objects.bulk_create(create_sub_item_list)\n print(instance)\n return instance\n\n\nclass TopDishesSerializer(MenuItemSerializer):\n total_like = serializers.SerializerMethodField()\n total_dislike = serializers.SerializerMethodField()\n\n class Meta(MenuItemSerializer.Meta):\n fields = MenuItemSerializer.Meta.fields + ('total_like', 'total_dislike')\n\n def get_total_like(self, obj):\n return 0\n\n def get_total_dislike(self, obj):\n return 0\n\n\nclass TopCookSerializer(CookSerializer):\n total_star = serializers.SerializerMethodField()\n total_review = serializers.SerializerMethodField()\n menu_items = serializers.SerializerMethodField()\n\n class Meta(CookSerializer.Meta):\n model = Cook\n fields = CookSerializer.Meta.fields + ('total_star', 'total_review', 'menu_items')\n\n def get_total_star(self, obj):\n return obj.avg_star_rating\n\n def get_total_review(self, obj):\n return obj.total_review\n\n def get_menu_items(self, obj):\n return MenuItemSerializer(obj.cook_menu_item.all(), many=True).data\n\n\nclass FSCCatalogueImageSerializer(serializers.ModelSerializer):\n image = serializers.ImageField(required=False)\n\n class Meta:\n model = FSCCatalogueImage\n fields = ('id', 'image', 'fsc_catalogue', 'cook', 'status', 'feedback')\n\n\nclass FSCCatalogueSerializer(serializers.ModelSerializer):\n description = serializers.SerializerMethodField()\n images = serializers.SerializerMethodField()\n\n class Meta:\n model = FSCCatalogue\n fields = ('id', 'name', 'quantity', 'fsc_type', 'description', 'images', 'status')\n read_only_fields = ('created_at', 'updated_at', 'status',)\n\n def get_description(self, obj):\n return 'Description'\n\n def get_images(self, obj):\n return FSCCatalogueImageSerializer(obj.fsc_catalogue_images.all(), many=True).data\n\n\nclass CookOrderSerializer(serializers.ModelSerializer):\n\n order_id = serializers.CharField()\n status = serializers.CharField()\n cook_instruction = serializers.CharField()\n customer_name = serializers.CharField(source='customer.user.username')\n customer_default_address = AddressSerializer(source='customer_address', read_only=True)\n cook_default_address = AddressSerializer(source='cook_address', read_only=True)\n order_detail = serializers.SerializerMethodField()\n\n class Meta:\n model = Order\n fields = (\n \"order_id\", \"status\", \"cook_instruction\", \"customer_name\", \"customer_default_address\",\"cook_default_address\", \"order_detail\",\n 'is_future_order', 'order_date', 'is_cook_agree'\n )\n\n @staticmethod\n def get_order_detail(obj):\n from apps.order.api.serializers import CookOrderMenuItemSerializer\n order_menu_item = CookOrderMenuItemSerializer(OrderMenuItem.objects.filter(order=obj), many=True).data\n return order_menu_item\n\n @staticmethod\n def get_address(obj):\n return AddressSerializer(obj.address).data\n\n\nclass CookFutureOrderSerializer(serializers.ModelSerializer):\n # order = serializers.CharField()\n # order_id = serializers.CharField()\n # status = serializers.CharField()\n # cook_instruction = serializers.CharField()\n customer_name = serializers.CharField(source='customer.user.username')\n address = serializers.SerializerMethodField()\n order_detail = serializers.SerializerMethodField()\n\n class Meta:\n model = Order\n fields = (\n \"id\", \"order_id\", \"status\", \"cook_instruction\", \"customer_name\", \"address\", \"order_detail\",\n 'is_future_order', 'order_date', 'is_cook_agree'\n )\n\n @staticmethod\n def get_order_detail(obj):\n from apps.order.api.serializers import CookOrderMenuItemSerializer\n order_menu_item = CookOrderMenuItemSerializer(OrderMenuItem.objects.filter(order=obj), many=True).data\n return order_menu_item\n\n @staticmethod\n def get_address(obj):\n return AddressSerializer(obj.address).data\n\n\nclass CookOrderDetailSerializer(serializers.ModelSerializer):\n class Meta:\n model = CookOrderDetails\n fields = ('cook_order_id', 'order_id', 'cook_id', 'eta', 'reason')\n\n\nclass ModifyOrderSerializer(serializers.ModelSerializer):\n order_id = serializers.CharField()\n status = serializers.CharField()\n cook_instruction = serializers.CharField()\n customer_name = serializers.CharField(source='customer.user.username')\n address = serializers.SerializerMethodField()\n order_detail = serializers.SerializerMethodField()\n\n class Meta:\n model = Order\n fields = (\n \"order_id\", \"status\", \"cook_instruction\", \"customer_name\", \"address\", \"order_detail\"\n )\n","repo_name":"nirmalthummar/cangurhu_python","sub_path":"apps/cook/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":12487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"36082591420","text":"import os\n\nfrom setuptools import setup\n\ndef long_description():\n os.system('pandoc --from=markdown --to=rst --output=README.rst README.md')\n readme_fn = os.path.join(os.path.dirname(__file__), 'README.rst')\n if os.path.exists(readme_fn):\n with open(readme_fn) as f:\n return f.read()\n else:\n return 'not available'\n\nsetup(\n name='ledtop',\n version='1.1.1',\n description=\"Like htop (CPU and memory usage), but for your case LEDs.\",\n long_description=long_description(),\n author='Derek Anderson',\n author_email='public@kered.org',\n url='https://github.com/keredson/ledtop',\n packages=[],\n py_modules=['ledtop'],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n ],\n install_requires=['psutil','darp','toml','openrgb-python','appdirs'],\n)\n\n","repo_name":"keredson/ledtop","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"} +{"seq_id":"21255133813","text":"import csv\nimport ipaddress\nimport logging.handlers\nimport sys\nimport argparse\n\n\ntry:\n import vat.vectra as vectra\n import requests\nexcept Exception as error:\n print('\\nMissing import requirements: {}\\n'.format(str(error)))\n sys.exit(0)\n\nLOG = logging.getLogger(__name__)\n\nINVALID_CHARS = ['~', '#', '$', '^', '+', '=', '<', '>', '?', ';']\nSUB_CHAR = '_'\nERRORS = list()\n\n# Suppress Detect certificate warning\nrequests.packages.urllib3.disable_warnings()\n\n\ndef print_errors(errors):\n print('The following {} errors were encountered:'.format(len(errors)))\n for err in errors:\n print('{}'.format(err))\n\n\ndef ip_subnet(subnet_string):\n \"\"\"\n Called with string that represents an IP subnet with CIDR or netmask in dotted decimal format\n\n Validates string represents valid subnet and removes host bits\n Returns string representation of subnet in CIDR format\n :param subnet_string: string representing subnet in CIDR w.x.y.z/n or netmask w.x.y.z/aa.bb.cc.dd format\n :return: returns string representation of subnet in CIDR format\n \"\"\"\n global ERRORS\n try:\n ipaddress.IPv4Network(subnet_string)\n except (ipaddress.AddressValueError, ipaddress.NetmaskValueError) as sub_error:\n LOG.info('Subnet {} format error, {}'.format(subnet_string, sub_error))\n ERRORS.append('Subnet {} format error, {}'.format(subnet_string, sub_error))\n return\n except ValueError as sub_error:\n ERRORS.append('Subnet {} has host bits, removing. {}'.format(subnet_string, sub_error))\n LOG.info('{}, removing host bits'.format(sub_error))\n subnet = ipaddress.IPv4Network(subnet_string, strict=False)\n return str(subnet)\n\n\ndef sub_bad_chars(string, sub=SUB_CHAR):\n \"\"\"\n Substitute unsupported characters in string representing group\n\n :param string: original string\n :param sub: substitution character, default defined in SUB_CHAR\n :return: returns the original string with any illegal characters substituted\n \"\"\"\n for bad_char in INVALID_CHARS:\n string = string.replace(bad_char, sub)\n return string\n\n\ndef group_exists(group_name, brain):\n \"\"\"\n Determines if group exists\n\n Called with initialized vectra client and name of group\n :param group_name: group name\n :param brain: initialized Vectra Client object\n :return: True if group exists, False otherwise\n \"\"\"\n group_iterator = brain.get_all_groups(name=group_name)\n for item in group_iterator:\n if item.json()['count'] > 0:\n for group in item.json()['results']:\n if group['name'] == group_name:\n return {'name': group['name'], 'id': group['id']}\n return False\n\n\ndef group_exists2(group_name, group_list):\n \"\"\"\n Determines if group exists in supplied group_list\n :param group_name: group name\n :param group_list: list of group dictionaries\n :return: The group dict if group exists, False otherwise\n \"\"\"\n if len(group_list) > 0:\n for group in group_list:\n if group['name'].lower() == group_name.lower():\n return group\n return False\n\n\ndef get_all_groups(brain):\n \"\"\"\n Retrieves all groups and returns a list of group dictionaries\n\n Called with initialized vectra client\n :param brain: initialized Vectra Client object\n :return: list of group dictionaries\n \"\"\"\n group_list = list()\n group_iterator = brain.get_all_groups()\n for page in group_iterator:\n if page.json()['count'] > 0:\n for group in page.json()['results']:\n group_list.append(group)\n return group_list\n\n\ndef create_group(name, subnet, brain, descr=''):\n \"\"\"\n Creates group and adds supplied subnet, and description if supplied\n\n :param name: group name\n :param subnet: CIDR subnet string\n :param brain: initialized Vectra Client object\n :param descr: group description, optional\n \"\"\"\n try:\n if bool(descr):\n brain.create_group(name=name, description=descr, type='ip', members=list(subnet))\n else:\n brain.create_group(name=name, type='ip', members=list(subnet))\n except Exception as error:\n LOG.error('create_group exception: {}'.format(str(error)))\n global ERRORS\n ERRORS.append('Create group exception {}, {}, {}'.format(name, list(subnet), str(error)))\n\n\ndef update_group(grp_id, subnet, brain, auth=False, descr=''):\n \"\"\"\n Updates existing group with supplied subnet, and description if supplied\n :param grp_id: group ID\n :param subnet: CIDR subnet string\n :param brain: initialized Vectra Client object\n :param auth: boolean representing authoritative update (True is Append=False)\n :param descr: group description, optional\n \"\"\"\n if bool(descr):\n brain.update_group(group_id=grp_id, description=descr, members=subnet, append=not auth)\n else:\n brain.update_group(group_id=grp_id, members=subnet, append=not auth)\n\n\ndef obtain_args():\n parser = argparse.ArgumentParser(description='Supplied with name of CSV input file, creates or updates IP groups '\n 'with supplied subnet information. \\nCSV file format: '\n 'group_name,subnet,description\\n\\n'\n 'Subnet can be supplied in CIDR notation e.g. \\n'\n 'group name,10.1.1.0/24,some description\\n\\n'\n 'or as subnet and netmask separate by a comma (,) e.g.\\n'\n 'group name,10.1.1.1.0,255.255.255.0,some description',\n prefix_chars='--', formatter_class=argparse.RawTextHelpFormatter,\n epilog='')\n parser.add_argument('brain', type=str, help='Hostname or IP of Congito Detect brain')\n parser.add_argument('token', type=str, help='API token to access Cognito Detect')\n parser.add_argument('file', type=str, help='Name of csv input file')\n parser.add_argument('-a', '--authoritative', action='store_true',\n help='Data contained in CSV is authoritative. Group '\n 'information will be overwritten where necessary.')\n parser.add_argument('-d', '--dryrun', action='store_true', help='Do dry run, no updates to Cognito')\n parser.add_argument('--sub_char', default=False, type=str, help='Override default invalid character '\n 'substitution in group names and '\n 'description. Default is _\\n'\n 'May not be one of the following characters\\n'\n '{}'.format(str(INVALID_CHARS)))\n parser.add_argument('--verbose', default=False, action='store_true', help='Verbose logging')\n\n return parser.parse_args()\n\n\ndef process_group_info(gd, g, s, d):\n \"\"\"\n Supplied with a dictionary of groups, group name, subnet list, and description, returns dictionary with new\n elements added\n :param gd: Dictionary of groups\n :param g: group name\n :param s: list of subnets\n :param d: description\n :return: dictionary of groups with new elements added\n \"\"\"\n if g not in gd.keys():\n gd = {**gd, **{g: {'subnets': [s], 'desc': d}}}\n return gd\n else:\n gd[g]['subnets'] += [s]\n gd[g]['desc'] = d\n return gd\n\n\ndef process_group_info2(gd, g, s, d):\n \"\"\"\n Supplied with a dictionary of groups, group name, subnet list, and description, returns dictionary with new\n elements added\n :param gd: Dictionary of groups\n :param g: group name\n :param s: list of subnets\n :param d: description\n :return: dictionary of groups with new elements added\n \"\"\"\n if g.lower() not in [k.lower() for k in gd.keys()]:\n gd = {**gd, **{g: {'subnets': [s], 'desc': d}}}\n return gd\n else:\n for i in gd.keys():\n if g.lower() == i.lower():\n gd[i]['subnets'] += [s]\n gd[i]['desc'] = d\n return gd\n\n\ndef group_missing_values(new_group, existing_group):\n \"\"\"\n Supplied with a dictionary of the csv group and existing group, determines if values contained in csv group are\n missing from the existing group\n :param new_group: dictionary of group from csv\n :param existing_group: dictionary of existing group\n :return: bool, [list of missing values]\n \"\"\"\n if sorted(new_group['subnets']) == sorted(existing_group['members']):\n # Group contents the same, update not needed, no update value\n return False, None\n elif (list(set(new_group['subnets']) - set(existing_group['members'])) and\n list(set(existing_group['members']) - set(new_group['subnets']))):\n # The group in Cognito has subnets missing and additional compared to CSV\n return 2, list(set(new_group['subnets']) - set(existing_group['members']))\n elif list(set(new_group['subnets']) - set(existing_group['members'])):\n # The group in Cognito has subnets missing compared to CSV\n return 1, list(set(new_group['subnets']) - set(existing_group['members']))\n elif list(set(existing_group['members']) - set(new_group['subnets'])):\n # The group in Cognito has additional subnets compared to CSV\n return -1, list(set(existing_group['members']) - set(new_group['subnets']))\n else:\n return False, None\n\n\ndef det_bom(infile):\n with open(infile, \"rb\") as file:\n beginning = file.read(4)\n # The order of these if-statements is important\n # otherwise UTF32 LE may be detected as UTF16 LE as well\n if beginning == b'\\x00\\x00\\xfe\\xff':\n return \"utf-32-be\"\n elif beginning == b'\\xff\\xfe\\x00\\x00':\n return \"utf-32-le\"\n elif beginning[0:3] == b'\\xef\\xbb\\xbf':\n return \"utf-8-sig\"\n elif beginning[0:2] == b'\\xff\\xfe':\n return \"utf-16-le\"\n elif beginning[0:2] == b'\\xfe\\xff':\n return \"utf-16-le\"\n else:\n return 'utf-8'\n\n\ndef main():\n \"\"\"\n Supplied with valid CSV file containing 3 or 4 columns of data, iterates over rows and creates or updates groups\n\n Supports CSV files with following format examples with or without header row\n group 1,192.168.1.0/255.255.255.0,group1 description\n group 2,10.1.1.0/24,group2 description\n \"\"\"\n args = obtain_args()\n\n global ERRORS\n\n sub_char = args.sub_char if args.sub_char else SUB_CHAR\n\n log_level = logging.DEBUG if args.verbose else logging.INFO\n logging.basicConfig(level=log_level, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n if len(sys.argv) == 1:\n print('Run python3 ip_group.py -h for help.')\n sys.exit()\n\n file = args.file\n\n with open(file, newline='', encoding=det_bom(file)) as csvfile:\n # Iterate through the CSV building a dictionary of groups\n reader = csv.reader(csvfile)\n csv_groups_dict = dict()\n counter = 0\n for row in reader:\n counter += 1\n sys.stdout.write(f\"\\rProcessing line: {str(counter)} \")\n sys.stdout.flush()\n\n if len(row) < 3 or len(row) > 4:\n LOG.debug('Invalid number of columns in row, skipping')\n ERRORS.append('Invalid number of columns in row {}'.format(row))\n continue\n if len(row) == 4:\n LOG.debug('Number of rows 4: {}'.format(len(row)))\n\n subnet = ip_subnet('{}/{}'.format(row[1], row[2]))\n description = sub_bad_chars(row[3], sub_char)\n\n elif len(row) == 3:\n LOG.debug('Number of rows 3: {}'.format(len(row)))\n\n subnet = ip_subnet(row[1])\n description = sub_bad_chars(row[2], sub_char)\n\n # Replace unsupported characters and remove leading and trailing spaces\n group_name = sub_bad_chars(row[0], sub_char).strip()\n\n if subnet is not None:\n # group_dict = {'group1': {'subnets': [1, 2, 3], 'desc': 'group1 description'},\n # 'group2': {'subnets': [3, 4, 5], 'desc': 'group2 description'}}\n if not group_name.isprintable():\n ERRORS.append('Non-printable characters in group name: {}'.format(group_name))\n LOG.debug('Non-printable characters in group [{}]'.format(group_name))\n\n elif not description.isprintable():\n ERRORS.append('Non-printable characters in group {} description: {}'.format(group_name, description))\n LOG.debug('Non-printable characters in description [{}]'.format(description))\n\n else:\n csv_groups_dict = process_group_info2(csv_groups_dict, group_name, subnet, description)\n else:\n LOG.debug('Invalid subnet, skipping')\n\n # Obtain list of existing groups from Cognito\n LOG.info('\\nRetrieving groups from https://{}'.format(args.brain))\n vc = vectra.VectraClientV2_1(url='https://' + args.brain, token=args.token, verify=False)\n existing_groups = get_all_groups(vc)\n LOG.info('\\nRetrieved {} groups'.format(len(existing_groups)))\n\n # Loop through dictionaries constructed from CSV\n groups_create = dict()\n groups_update = dict()\n groups_update_overwrite = dict()\n LOG.info('Preprocessing groups.')\n for group in csv_groups_dict.keys():\n group_exists_results = group_exists2(group, existing_groups)\n LOG.debug('Checking if group [{}] exists.'.format(group))\n LOG.debug('{}'.format(csv_groups_dict[group]))\n LOG.debug('Group_exists_results: {}'.format(group_exists_results))\n if bool(group_exists_results):\n update_needed, update_value = group_missing_values(csv_groups_dict[group], group_exists_results)\n if update_needed == 1:\n LOG.debug('1:Group exists, update needed, add. id:{}, group:{}, subnets:{}'.format(\n group_exists_results['id'],\n group,\n update_value\n )\n )\n groups_update = {**groups_update,\n **{group: {\n 'id': group_exists_results['id'],\n 'subnets': update_value['subnets']\n }}\n }\n elif update_needed == -1:\n # Group in Detect contains subnets CSV does not\n if args.authoritative:\n LOG.debug('-1:Group exists and has extra subnets. id:{}, group:{}, subnets:{}'.format(\n group_exists_results['id'],\n group,\n update_value\n )\n )\n groups_update_overwrite = {**groups_update, **{group: {\n 'id': group_exists_results['id'],\n 'subnets': csv_groups_dict[group]['subnets'],\n 'desc': csv_groups_dict[group]['desc']}}}\n elif update_needed == 2 and args.authoritative:\n # Group in Detect contains subnets CSV does not and is missing subnets from CSV\n if args.authoritative:\n LOG.debug('2a:Group exists and has extra subnets and missing. id:{}, group:{}, subnets:{}'.format(\n group_exists_results['id'],\n group,\n update_value\n )\n )\n groups_update_overwrite = {**groups_update, **{group: {\n 'id': group_exists_results['id'],\n 'subnets': csv_groups_dict[group]['subnets'],\n 'desc': csv_groups_dict[group]['desc']}}}\n elif update_needed == 2 and not args.authoritative:\n # Group in Detect contains subnets CSV does not and is missing subnets from CSV, not authoritative\n # so update needed\n LOG.debug('2b:Group exists and has extra subnets and missing. id:{}, group:{}, subnets:{}'.format(\n group_exists_results['id'],\n group,\n update_value\n )\n )\n groups_update = {**groups_update,\n **{group: {\n 'id': group_exists_results['id'],\n 'subnets': update_value}}\n }\n else:\n # Group does not exist, creating\n LOG.debug('Group does not exist. group:{}, subnets:{}, description:{}'.format(\n group,\n csv_groups_dict[group].get('subnets'),\n csv_groups_dict[group].get('desc')\n )\n )\n groups_create = {**groups_create,\n **{group: {\n 'subnets': csv_groups_dict[group].get('subnets'),\n 'desc': csv_groups_dict[group].get('desc')}}\n }\n LOG.debug('update:{}'.format(groups_update))\n LOG.debug('create:{}'.format(groups_create))\n LOG.debug('overwrite:{}'.format(groups_update_overwrite))\n # Iterate over each dictionary that contains data\n if not args.dryrun:\n if groups_update:\n LOG.info(\"Staring update of groups.\")\n for group_name in groups_update.keys():\n LOG.info('Updating group: [{}] with id: {} to include subnets: {}'.format(\n group_name,\n groups_update[group_name]['id'],\n groups_update[group_name]['subnets']\n ))\n update_group(groups_update[group_name]['id'], groups_update[group_name]['subnets'], vc)\n\n if groups_create:\n LOG.info(\"Starting creation of new groups.\")\n\n for group_name in groups_create.keys():\n LOG.info('Creating new group with name: [{}], subnets: {}, description: {}'.format(\n group_name,\n groups_create[group_name]['subnets'],\n groups_create[group_name]['desc']\n ))\n create_group(group_name, groups_create[group_name]['subnets'], vc, groups_create[group_name]['desc'])\n\n if groups_update_overwrite and args.authoritative:\n LOG.info(\"Starting update of groups, overwriting subnets from CSV.\")\n for group_name in groups_update_overwrite.keys():\n LOG.info('Overwriting group: [{}] with id: {} subnets: {}'.format(\n group_name,\n groups_update_overwrite[group_name]['id'],\n groups_update_overwrite[group_name]['subnets']\n ))\n # Pass False to mark as authoritative\n update_group(groups_update_overwrite[group_name]['id'],\n groups_update_overwrite[group_name]['subnets'],\n vc, auth=True)\n\n print_errors(ERRORS)\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"vectranetworks/csv-to-ip-group","sub_path":"ip_group.py","file_name":"ip_group.py","file_ext":"py","file_size_in_byte":20089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"12762852346","text":"from servers import BroadcastServer\nimport multiprocessing\nimport time\nimport datetime\n\n\ndef main():\n start = datetime.datetime.now()\n udp_server = BroadcastServer(15555, 12222)\n process = multiprocessing.Process(target=udp_server.run_server)\n try:\n process.start()\n\n while True:\n time.sleep(1)\n except KeyboardInterrupt:\n udp_server.stop()\n print(datetime.datetime.now() - start)\n process.join()\n\nif __name__ == '__main__':\n main()\n","repo_name":"Bialri/YASH","sub_path":"hub/src/registration/run_broadcast_server.py","file_name":"run_broadcast_server.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"13890653673","text":"import cv2 as cv\r\nimport numpy as np\r\n\r\n# It will show all the events in opencv\r\n# events = [i for i in dir(cv) if 'EVENT' in i]\r\n# print(events)\r\n\r\ndef click_event(event, x, y, flag, param):\r\n if event == cv.EVENT_LBUTTONDOWN:\r\n blue = img[x, y, 0]\r\n green = img[x, y, 1]\r\n red = img[x, y, 2]\r\n cv.circle(img, (x, y), 3, (0, 0, 255), -1)\r\n myColorImg = np.zeros((512, 512, 3), np.uint8)\r\n myColorImg[:] = [blue, green, red]\r\n cv.imshow('Color', myColorImg)\r\n\r\n # cv.circle(img, (x, y), 3, (255, 255, 0), -1)\r\n # points.append((x, y))\r\n # if len(points) >= 2:\r\n # cv.line(img, points[-1], points[-2], (255, 0, 0), 1)\r\n\r\n\r\n# Black Image\r\n# img = np.zeros([520, 520, 3], np.uint8)\r\n\r\nimg = cv.imread('images/lena.jpg', 1)\r\ncv.imshow('Image', img)\r\n\r\npoints = []\r\n\r\ncv.setMouseCallback('Image', click_event)\r\n\r\ncv.waitKey(0)\r\ncv.destroyAllWindows()\r\n","repo_name":"JamiKazmi/ImageProcessingOpenCV-Python","sub_path":"6_more_mouse_events.py","file_name":"6_more_mouse_events.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"7708891055","text":"from LoadObjBlender.objloader import OBJ\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\nfrom OpenGL.GLUT import *\nimport math\nimport time\nfrom PIL import Image\n\nangleJanela, anglePorta, angleVent, mouseSens, mouseVel, ang_x, ang_y = 0.0, 0.0, 0.0, 0.001, 0.1, 0.3, 1.3\nantigo_x, antigo_y, fAspect, rotX, rotY, obsZ, medida = 710, 519, 1.6, 0, -2, 2, 7\ncx, cy, cz, fx, fy, fz, ux, uy, uz = 0.3*medida, 1.3*medida, 3.2*medida, 0.98, 0.16, -0.05, 0, 1, 0\nobjTeclado, objMonitorOn = '', ''\nisDay = True\nturnOnPc = []\nturnSwitch = []\nturnLampPc = False\nturnLampRoof = []\ntexture_board, texture_fan, texture_floor = 0, 0, 0\n\ndef square(A, B, C, D):\n glBegin(GL_POLYGON)\n glVertex3fv(A)\n glVertex3fv(B)\n glVertex3fv(C)\n glVertex3fv(D)\n glEnd()\n\ndef cubo(v0, v1, v2, v3, v4, v5, v6, v7, colorR, colorG, colorB):\n glPushMatrix()\n glColor3f(colorR, colorG, colorB)\n square(v0, v1, v2, v3)\n\n glColor3f(colorR, colorG, colorB)\n square(v4, v5, v6, v7)\n\n glColor3f(colorR, colorG, colorB)\n square(v0, v4, v7, v3)\n\n glColor3f(colorR, colorG, colorB)\n square(v1, v5, v6, v2)\n\n glColor3f(colorR, colorG, colorB)\n square(v3, v2, v6, v7)\n\n glColor3f(colorR, colorG, colorB)\n square(v0, v1, v5, v4)\n glPopMatrix()\n\ndef modelar_objeto( x_max, x_min, y_max, y_min, z_max, z_min, colorR, colorG, colorB):\n global medida\n objeto = [\n [x_min*medida, y_max*medida, z_min*medida],\n [x_min*medida, y_max*medida, z_max*medida],\n [x_max*medida, y_max*medida, z_max*medida],\n [x_max*medida, y_max*medida, z_min*medida],\n [x_min*medida, y_min*medida, z_min*medida],\n [x_min*medida, y_min*medida, z_max*medida],\n [x_max*medida, y_min*medida, z_max*medida],\n [x_max*medida, y_min*medida, z_min*medida],\n ]\n \n cubo(objeto[0], objeto[1], objeto[2], objeto[3], objeto[4], objeto[5], objeto[6], objeto[7], colorR, colorG, colorB)\n\ndef keyboard(ch, x, y):\n global cx, cy, cz, fx, fy, fz, ux, uy, uz, anglePorta, angleVent, turnOnPc, angleJanela, isDay, turnLampPc\n ch = ch.decode(\"utf-8\")\n\n if ch == 'r':\n cx, cy, cz, fx, fy, fz, ux, uy, uz = 0.3*medida, 1.3*medida, 3.2*medida, 0.98, 0.16, -0.05, 0, 1, 0\n elif ch == 'a':\n cz -= 2\n elif ch == 'd':\n cz += 2\n elif ch == 'w':\n cx += 2\n elif ch == 's':\n cx -= 2\n elif ch == 'y':\n cy += 2\n elif ch == 'Y':\n cy -= 2\n elif ch == 'o':\n if (anglePorta + 3 <= 90):\n anglePorta += 3\n elif ch == 'c':\n if (anglePorta - 3 >= 0):\n anglePorta -= 3\n elif ch == 'j':\n if (angleJanela+2 <= 90):\n angleJanela += 2\n elif ch == 'J':\n if (angleJanela-2 >= 0):\n angleJanela -= 2\n elif ch == 't':\n isDay = not isDay\n elif ch == 'e':\n turnLampPc = not turnLampPc\n elif ch == 'q':\n turnLampRoof[0]['state'] = not turnLampRoof[0]['state']\n\n\n glutPostRedisplay()\n\ndef montar_monitores():\n global turnOnPc\n # base dos monitores do lado direito\n x_max, x_min, y_max, y_min, z_max, z_min = 6.5, 6.35, 0.815, 0.8001, 4.235, 3.985\n while(x_min > 0):\n z_max, z_min = 4.235, 3.985\n while(z_max < 6.4):\n glPushMatrix()\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0, 0, 0)\n glPopMatrix()\n z_max+=0.9\n z_min+= 0.9\n x_max-=1.71\n x_min-= 1.71\n\n # parte 2 da base dos monitores lado direito\n x_max, x_min, y_max, y_min, z_max, z_min = 6.48, 6.45, 1.115, 0.815, 4.135,4.085\n while(x_min > 0):\n z_max, z_min = 4.135, 4.085\n while(z_max < 6.4):\n glPushMatrix()\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.2, 0.2, 0.2)\n glPopMatrix()\n z_max+=0.9\n z_min+= 0.9\n x_max-=1.71\n x_min-= 1.71\n \n # monitores do lado direito\n x_max, x_min, y_max, y_min, z_max, z_min = 6.455, 6.445, 1.165, 0.915, 4.4, 3.82\n while(x_min > 0):\n z_max, z_min = 4.4, 3.82\n while(z_max < 6.4):\n glPushMatrix()\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0, 0, 0)\n glPopMatrix()\n z_max+=0.9\n z_min+= 0.9\n x_max-=1.71\n x_min-= 1.71\n \n # gabinetes do lado direito\n x_max, x_min, y_max, y_min = 6.75, 6.25, 1.2, 0.8001\n while(x_min > 0):\n z_max, z_min = 4.58, 4.43\n while(z_max < 6.4):\n glPushMatrix()\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.1, 0.1, 0.1)\n glPopMatrix()\n z_max+=0.9\n z_min+= 0.9\n x_max-=1.71\n x_min-= 1.71\n \n # # botão power do lado direito\n x_max, x_min, y_max, y_min = 6.25001, 6.245, 0.91, 0.9\n\n while(x_min > 0):\n z_max, z_min = 4.51, 4.49\n while(z_max < 6.4):\n glPushMatrix()\n turnOnPc.append({'x_max': x_max, 'x_min': (x_min), 'y_max': y_max, 'y_min': y_min, 'z_max': z_max, 'z_min': z_min, 'state': False})\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.35, 0.35, 0.35)\n glPopMatrix()\n z_max+=0.9\n z_min+= 0.9\n x_max-=1.71\n x_min-= 1.71\n \n # base dos monitores do lado esquerdo\n x_max, x_min, y_max, y_min = 6.5, 6.35, 0.815, 0.8001\n while(x_min > 0):\n z_max, z_min = 2.415, 2.165\n while(z_min > 0):\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0, 0, 0)\n z_max-=0.9\n z_min-= 0.9\n x_max-=1.71\n x_min-= 1.71\n \n # parte 2 da base dos monitores lado esquerdo\n x_max, x_min, y_max, y_min = 6.48, 6.45, 1.115, 0.815\n while(x_min > 0):\n z_max, z_min = 2.315, 2.265\n while(z_max > 0):\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.2, 0.2, 0.2)\n z_max-=0.9\n z_min-= 0.9\n x_max-=1.71\n x_min-= 1.71\n \n # monitores do lado esquerdo\n x_max, x_min, y_max, y_min = 6.455, 6.445, 1.165, 0.915\n while(x_min > 0):\n z_max, z_min = 2.58, 2\n while(z_max > 0):\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0, 0, 0)\n z_max-=0.9\n z_min-= 0.9\n x_max-=1.71\n x_min-= 1.71\n \n # gabinetes do lado esquerdo\n x_max, x_min, y_max, y_min, z_max, z_min = 6.75, 6.25, 1.2, 0.8001, 4.58, 4.43\n while(x_min > 0):\n z_max, z_min = 1.95, 1.82\n while(z_max > 0):\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.1, 0.1, 0.1)\n z_max-=0.9\n z_min-= 0.9\n x_max-=1.71\n x_min-= 1.71\n \n # botão power do lado esquerdo\n x_max, x_min, y_max, y_min = 6.25001, 6.245, 0.91, 0.9\n while(x_min > 0):\n z_max, z_min = 1.9, 1.88\n while(z_max > 0):\n turnOnPc.append({'x_max': x_max, 'x_min': (x_min), 'y_max': y_max, 'y_min': y_min, 'z_max': z_max, 'z_min': z_min, 'state': False})\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.35, 0.35, 0.35)\n z_max-=0.9\n z_min-= 0.9\n x_max-=1.71\n x_min-= 1.71\n\ndef montar_mesas():\n # mesas do lado direito\n x_max, x_min, y_max, y_min, z_max, z_min = 6.85, 6, 0.8, 0.76, 6.4, 3.71\n while(x_min > 0):\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.85, 0.85, 0.85)\n x_max-=1.71\n x_min-= 1.71\n \n # divisórias da mesa do lado direito\n y_max, y_min, x_max, x_min = 1.3, 0, 6.86, 5.99\n while(x_min > 0):\n z_max, z_min = 3.74, 3.7\n while(z_max < 6.4):\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.78, 0.78, 0.78)\n z_max+=0.9\n z_min+= 0.9\n x_max-=1.71\n x_min-= 1.71\n \n # fundo da mesa do laso direito\n x_max, x_min, y_max, y_min, z_max, z_min = 6.85, 6.8, 0.8, 0, 6.4, 3.71\n while(x_min > 0):\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.85, 0.85, 0.85)\n x_max-=1.71\n x_min-= 1.71\n \n # mesas do lado esquerdo\n x_max, x_min, y_max, y_min, z_max, z_min = 6.85, 6, 0.8, 0.76, 2.69, 0\n while(x_min > 0):\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.85, 0.85, 0.85)\n x_max-=1.71\n x_min-= 1.71\n \n # divisórias da mesa do lado esquerdo\n y_max, y_min, x_max, x_min = 1.3, 0, 6.86, 5.99\n while(x_min > 0):\n z_max, z_min = 2.7, 2.66\n while(z_min > 0):\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.78, 0.78, 0.78)\n z_max-=0.9\n z_min-= 0.9\n x_max-=1.71\n x_min-= 1.71\n \n # fundo da mesa do lado esquerdo\n x_max, x_min, y_max, y_min, z_max, z_min = 6.85, 6.8, 0.8, 0, 2.69, 0\n while(x_min > 0):\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.85, 0.85, 0.85)\n x_max-=1.71\n x_min-= 1.71\n \n # mesa do professor\n x_max, x_min, y_max, y_min, z_max, z_min = 7.35, 6.85, 0.8, 0.76, 1.75, 0.95\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.85, 0.85, 0.85)\n\ndef montar_paredes():\n #piso\n x_max, x_min, y_max, y_min, z_max, z_min = 8.15, -0.15, 0, -0.15, 6.55, -0.15\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.5, 0.5, 0.5)\n glPushMatrix()\n glTranslatef(8*medida, -8.1495*medida, 0)\n glRotatef(90, 0, 0, 1)\n montar_textura(x_max, x_min, y_max, y_min+8.3, z_max, z_min, texture_floor)\n glPopMatrix()\n\n #teto\n x_max, x_min, y_max, y_min, z_max, z_min = 8.15, -0.15, 3.15, 3, 6.55, -0.15\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.5, 0.5, 0.5)\n\n # parede direita inferior\n x_max, x_min, y_max, y_min, z_max, z_min = 7, -0.15, 2.5, 0, 6.55, 6.4\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.75, 0.75, 0.75)\n\n # pilastra parede direita\n x_max, x_min, y_max, y_min, z_max, z_min = 5.8, 5.5, 3, 0, 6.55, 6.35\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.75, 0.75, 0.75)\n\n # parede direita, lado esquerdo\n x_max, x_min, y_max, y_min, z_max, z_min = 6.85, 6.8, 3, 2.5, 6.55, 6.4\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.75, 0.75, 0.75)\n\n # parede direita, lado direito\n x_max, x_min, y_max, y_min, z_max, z_min = 0.5, 0, 3, 2.5, 6.55, 6.4\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.75, 0.75, 0.75)\n\n #parede menor a direita, lado da porta\n x_max, x_min, y_max, y_min, z_max, z_min = 7, 6.85, 3, 0, 6.55, 5.55\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.75, 0.75, 0.75)\n\n #parede esquerda inferior\n x_max, x_min, y_max, y_min, z_max, z_min = 8.15, -0.15, 1.25, 0, 0, -0.15\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.75, 0.75, 0.75)\n\n # parede esquerda superior\n x_max, x_min, y_max, y_min, z_max, z_min = 8.15, -0.15, 3, 2.95, 0, -0.15\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.75, 0.75, 0.75)\n\n # parede esquerda, lateral esquerda\n x_max, x_min, y_max, y_min, z_max, z_min = 0.5, -0.15, 2.95, 1.25, 0, -0.15\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.75, 0.75, 0.75)\n\n # parede esquerda, lateral direita\n x_max, x_min, y_max, y_min, z_max, z_min = 8.15, 7.8, 2.95, 1.25, 0, -0.15\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.75, 0.75, 0.75)\n\n # pilastra parede esquerda\n x_max, x_min, y_max, y_min, z_max, z_min = 5.8, 5.5, 3, 0, 0.05, -0.15\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.75, 0.75, 0.75)\n\n #parede do fundo\n x_max, x_min, y_max, y_min, z_max, z_min = 0, -0.15, 3, 0, 6.55, -0.15\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.75, 0.75, 0.75)\n\n #parede da frente, no quadro\n x_max, x_min, y_max, y_min, z_max, z_min = 8.15, 8, 3, 0, 6.55, -0.15\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.75, 0.75, 0.75)\n\ndef montar_textura(x_max, x_min, y_max, y_min, z_max, z_min, texture ):\n glEnable(GL_TEXTURE_2D)\n glBindTexture(GL_TEXTURE_2D, texture)\n \n glColor3f(1, 1, 1)\n \n if(x_min == 0):\n glBegin(GL_QUADS)\n glTexCoord2f(0, 0)\n glVertex3f(x_max*medida, y_max*medida, z_max*medida)\n glTexCoord2f(1, 0)\n glVertex3f(x_max*medida, y_max*medida, z_min*medida)\n glTexCoord2f(1, 1)\n glVertex3f(x_max*medida, y_min*medida, z_min*medida)\n glTexCoord2f(0, 1)\n glVertex3f(x_max*medida, y_min*medida, z_max*medida)\n glEnd()\n else:\n glBegin(GL_QUADS)\n glTexCoord2f(0, 0)\n glVertex3f(x_max*medida, y_max*medida, z_max*medida)\n glTexCoord2f(1, 0)\n glVertex3f(x_max*medida, y_max*medida, z_min*medida)\n glTexCoord2f(1, 1)\n glVertex3f(x_max*medida, y_min*medida, z_min*medida)\n glTexCoord2f(0, 1)\n glVertex3f(x_max*medida, y_min*medida, z_max*medida)\n glEnd()\n \n\n glDisable(GL_TEXTURE_2D)\n\ndef montar_quadro():\n global texture_board\n x_max, x_min, y_max, y_min, z_max, z_min = 8, 7.98, 2.44, 0.71, 4, 1.55\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.87, 0.87, 0.87)\n montar_textura(7.97995, 0, y_max, y_min, z_max, z_min, texture_board)\n \n\ndef montar_estruturas_da_porta():\n #estrutura da porta solta da parede\n x_max, x_min, y_max, y_min, z_max, z_min = 7.18, 7.16, 3, 0, 5.6, 5.55\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.4, 0.4, 0.4)\n\n #estrutura da porta encostado na parede\n x_max, x_min, y_max, y_min, z_max, z_min = 8, 7.98, 3, 0, 5.6, 5.55\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.4, 0.4, 0.4)\n\n #estrutura da porta superior da porta\n x_max, x_min, y_max, y_min, z_max, z_min = 8, 7, 2.22, 2.2, 5.6, 5.55\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.4, 0.4, 0.4)\n\n #estrutura da porta superior encostado no teto\n x_max, x_min, y_max, y_min, z_max, z_min = 8, 7, 3, 2.98, 5.6, 5.55\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.4, 0.4, 0.4)\n\n #estrutura da porta encostado na parede direita\n x_max, x_min, y_max, y_min, z_max, z_min = 7.02, 7, 3, 0, 5.6, 5.55\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.4, 0.4, 0.4)\n\ndef montar_porta():\n #porta branca x -> 7.975 # z -> 5,585\n x_max, x_min, y_max, y_min, z_max, z_min = 0, -0.590, 2.195, 0.005, 0, -0.02\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.8, 0.8, 0.8)\n\n #porta azul\n x_max, x_min, y_max, y_min, z_max, z_min = -0.590, -0.79, 2.195, 0.005, 0, -0.02\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.07, 0.3, 0.56)\n\n #ferro do trinco da porta\n x_max, x_min, y_max, y_min, z_max, z_min = -0.750, -0.76, 1.155, 1.145, 0.03, -0.05\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.43, 0.5, 0.57)\n\n #trinco da porta, por fora da sala\n x_max, x_min, y_max, y_min, z_max, z_min = -0.69, -0.76, 1.155, 1.145, 0.03, 0.02\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.43, 0.5, 0.57)\n\n #trinco da porta, por dentro da sala\n x_max, x_min, y_max, y_min, z_max, z_min = -0.69, -0.76, 1.155, 1.145, -0.05, -0.06\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.43, 0.5, 0.57)\n\ndef circulo_B(raio, x_center, y_center, z_center, colorR, colorG, colorB):\n num_segments = 50\n theta = 2.0 * 3.1415926 / num_segments\n glColor3f(colorR, colorG, colorB)\n glBegin(GL_TRIANGLE_FAN)\n glVertex3f(x_center*medida, y_center*medida, z_center*medida)\n for i in range(num_segments):\n y = raio * math.sin(i * theta)\n z = raio * math.cos(i * theta)\n glVertex3f(x_center*medida, y + y_center*medida, z + z_center*medida)\n glEnd()\n\ndef escrever_no_quadro():\n # L\n x_max, x_min, y_max, y_min, z_max, z_min = 7.98, 7.9795, 1.8, 1.25, 2.15, 2.1\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0, 0, 0)\n\n x_max, x_min, y_max, y_min, z_max, z_min = 7.98, 7.9795, 1.3, 1.25, 2.35, 2.1\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0, 0, 0)\n\n # A\n x_max, x_min, y_max, y_min, z_max, z_min = 7.98, 7.9795, 1.8, 1.25, 2.7, 2.65\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0, 0, 0)\n\n x_max, x_min, y_max, y_min, z_max, z_min = 7.98, 7.9795, 1.8, 1.25, 2.45, 2.4\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0, 0, 0)\n\n x_max, x_min, y_max, y_min, z_max, z_min = 7.98, 7.9795, 1.8, 1.75, 2.7, 2.4\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0, 0, 0)\n\n x_max, x_min, y_max, y_min, z_max, z_min = 7.98, 7.9795, 1.6, 1.55, 2.7, 2.4\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0, 0, 0)\n\n # B\n circulo_B(medida*0.15, 7.9799, 1.67, 2.8, 0, 0, 0)\n circulo_B((medida*0.15)-0.2, 7.97985, 1.67, 2.8, 0.87, 0.87, 0.87)\n circulo_B(medida*0.16, 7.9799, 1.4, 2.8, 0, 0, 0)\n circulo_B((medida*0.15)-0.2, 7.97985, 1.4, 2.8, 0.87, 0.87, 0.87)\n\n x_max, x_min, y_max, y_min, z_max, z_min = 7.98, 7.9797, 1.8, 1.25, 2.8, 2.75\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0, 0, 0)\n\n x_max, x_min, y_max, y_min, z_max, z_min = 7.98, 7.9797, 1.85, 1.25, 2.75, 2.6\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.87, 0.87, 0.87)\n\n # 2\n x_max, x_min, y_max, y_min, z_max, z_min = 7.98, 7.9795, 1.5, 1.25, 3.15, 3.1\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0, 0, 0)\n\n x_max, x_min, y_max, y_min, z_max, z_min = 7.98, 7.9795, 1.8, 1.5, 3.3, 3.25\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0, 0, 0)\n\n x_max, x_min, y_max, y_min, z_max, z_min = 7.98, 7.9795, 1.8, 1.75, 3.3, 3.1\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0, 0, 0)\n\n x_max, x_min, y_max, y_min, z_max, z_min = 7.98, 7.9795, 1.525, 1.4725, 3.3, 3.1\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0, 0, 0)\n\n x_max, x_min, y_max, y_min, z_max, z_min = 7.98, 7.9795, 1.3, 1.25, 3.3, 3.1\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0, 0, 0)\n\ndef montar_bases_dos_ventiladores():\n #ventilador 1\n x_max, x_min, y_max, y_min, z_max, z_min = 5.05, 4.95, 3, 2.97, 3.25, 3.15\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.54, 0.27, 0.07)\n\n x_max, x_min, y_max, y_min, z_max, z_min = 5.01, 4.99, 3, 2.85, 3.21, 3.19\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.54, 0.27, 0.07)\n\n glPushMatrix()\n glTranslatef(5*medida, 2.85*medida, 3.2*medida)\n glColor3f(0.54, 0.27, 0.07)\n glutSolidSphere(0.15, 50, 50)\n glPopMatrix()\n\n #ventilador 2\n x_max, x_min, y_max, y_min, z_max, z_min = 2.05, 1.95, 3, 2.97, 3.25, 3.15\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.54, 0.27, 0.07)\n\n x_max, x_min, y_max, y_min, z_max, z_min = 2.01, 1.99, 3, 2.85, 3.21, 3.19\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.54, 0.27, 0.07)\n\n glPushMatrix()\n glTranslatef(2*medida, 2.85*medida, 3.2*medida)\n glColor3f(0.54, 0.27, 0.07)\n glutSolidSphere(0.15, 50, 50)\n glPopMatrix()\n\n\ndef montar_ventilador():\n global texture_fan\n #ventilador 1\n x_max, x_min, y_max, y_min, z_max, z_min = -0.5, 0.5, 0, 0, 0.05, -0.05\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0,0,0)\n glPushMatrix()\n glRotatef(-90, 0, 0, 1)\n montar_textura(x_max+0.51, x_min, y_max+0.5, y_min-0.5, z_max, z_min, texture_fan)\n glPopMatrix()\n\n x_max, x_min, y_max, y_min, z_max, z_min = 0.05, -0.05, 0, 0,-0.5, 0.5\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0,0,0)\n glPushMatrix()\n glTranslatef(0, 0.045*medida, 0)\n glRotatef(-90, 0, 0, 1)\n montar_textura(x_max, x_min, y_max+0.05, y_min-0.05, z_max, z_min, texture_fan)\n glPopMatrix()\n\n\ndef montar_teclado():\n # lado lideiro\n x, y, z = 6.2, 0.81, 4.05\n for linha in range(4):\n for coluna in range(3):\n glPushMatrix()\n glColor(1, 1, 1)\n glTranslatef(x*medida, y*medida, z*medida)\n glScale(0.4, 0.55, 0.35)\n glRotatef(-90, 0, 1, 0)\n glCallList(objTeclado.gl_list)\n glPopMatrix()\n z+=0.9\n x-=1.71\n z = 4.05\n\n # lado esquerdo\n x, y, z = 6.2, 0.81, 2.25\n for linha in range(4):\n for coluna in range(3):\n glPushMatrix()\n glTranslatef(x*medida, y*medida, z*medida)\n glScale(0.4, 0.55, 0.4)\n glRotatef(-90, 0, 1, 0)\n glCallList(objTeclado.gl_list)\n glPopMatrix()\n z-=0.9\n x-=1.71\n z = 2.25\n\ndef montar_janela_lado_direito():\n global medida\n\n vertices = [\n [7.98, 7.18, 3, 2.22, 5.5575],\n [7.16, 7.02, 3, 2.22, 5.5575],\n [7.16, 7.02, 2.2, 0, 5.5575],\n ]\n\n for janela in vertices:\n glBegin(GL_QUADS)\n glColor4f(0.75,0.75,0.75, 0.5) \n glVertex3f(janela[0] * medida, janela[3] * medida, janela[4] * medida)\n glVertex3f(janela[0] * medida, janela[2] * medida, janela[4] * medida)\n glVertex3f(janela[1] * medida, janela[2] * medida, janela[4] * medida)\n glVertex3f(janela[1] * medida, janela[3] * medida, janela[4] * medida)\n glEnd()\n \n x_center, y_center, z_center = 6.05, 2.75, 6.475\n for i in range(2):\n glPushMatrix()\n glTranslatef(x_center*medida, y_center*medida, z_center*medida)\n glRotatef(angleJanela, 0, 1, 0)\n montar_janela_de_movimento(0.5, 0.5)\n glPopMatrix()\n x_center+=0.5\n\n x_center, y_center, z_center = 0.75, 2.75, 6.475\n for i in range(10):\n glPushMatrix()\n glTranslatef(x_center*medida, y_center*medida, z_center*medida)\n glRotatef(angleJanela, 0, 1, 0)\n montar_janela_de_movimento(0.5, 0.5)\n glPopMatrix()\n x_center+=0.5\n \ndef ligar_monitor():\n global turnOnPc\n for pc in turnOnPc:\n if(pc['state'] and pc['z_max'] < 3.2):\n # lado esquerdo\n glPushMatrix()\n glColor3f(1, 1, 1)\n glTranslatef((pc['x_min']+0.2)*medida, (pc['y_max']+0.13) *medida, (pc['z_min']+0.41) *medida)\n glScale(0.37, 0.84, 0.54)\n glRotatef(90, 0, 1, 0)\n glRotatef(-90, 1, 0, 0)\n glCallList(objMonitorOn.gl_list)\n glPopMatrix()\n elif(pc['state'] and pc['z_max'] > 3.2):\n # lado direito\n glPushMatrix()\n glColor3f(1, 1, 1)\n glTranslatef((pc['x_min']+0.2)*medida, (pc['y_max']+0.13) *medida, (pc['z_min']-0.38) *medida)\n glScale(0.37, 0.84, 0.54)\n glRotatef(90, 0, 1, 0)\n glRotatef(-90, 1, 0, 0)\n glCallList(objMonitorOn.gl_list)\n glPopMatrix()\n\ndef ligar_pc():\n global turnOnPc\n\n for pc in turnOnPc:\n if(pc['state']):\n glPushMatrix()\n modelar_objeto(pc['x_max'], pc['x_min'], pc['y_max'], pc['y_min'], pc['z_max'], pc['z_min'], 0, 1, 0)\n glPopMatrix()\n\ndef setup_lamp():\n x_max, x_min, y_max, y_min, z_max, z_min = 7.99, 7.985, 1.445, 1.425, 5.02, 4.98\n turnLampRoof.append({'x_max': x_max, 'x_min': x_min, 'y_max': y_max, 'y_min': y_min, 'z_max': z_max, 'z_min': z_min, 'state': False})\n\ndef montar_tomada():\n global turnSwitch, turnLamp\n x_max, x_min, y_max, y_min, z_max, z_min = 8, 7.99, 1.55, 1.35, 5.03, 4.97\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.93,0.90,0.66)\n\n x_max, x_min, y_max, y_min, z_max, z_min = 7.99, 7.985, 1.485, 1.465, 5.02, 4.98\n turnSwitch.append({'x_max': x_max, 'x_min': x_min, 'y_max': y_max, 'y_min': y_min, 'z_max': z_max, 'z_min': z_min, 'state': False})\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.87,0.72,0.52)\n\n x_max, x_min, y_max, y_min, z_max, z_min = 7.99, 7.985, 1.445, 1.425, 5.02, 4.98\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.87,0.72,0.52)\n\ndef loop():\n global angleVent, turnSwitch\n\n if turnSwitch[0]['state']:\n angleVent += 15\n if(angleVent >= 360):\n angleVent = 0\n \n if isDay:\n glClearColor(0.73, 0.95, 0.97, 1)\n glLightModelfv(GL_LIGHT_MODEL_AMBIENT, [0.5, 0.5, 0.5, 1])\n glLightfv(GL_LIGHT0, GL_DIFFUSE, [0, 0, 0, 1])\n else:\n glClearColor(0, 0, 0.1, 1)\n glLightModelfv(GL_LIGHT_MODEL_AMBIENT, [0.15, 0.15, 0.15, 1])\n glLightfv(GL_LIGHT0, GL_DIFFUSE, [0, 0, 0, 1])\n glutPostRedisplay()\n\ndef montar_janela_de_movimento(tam_x, tam_y):\n global medida\n glPushMatrix()\n glEnable(GL_BLEND)\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)\n x_max, x_min, y_max, y_min, z_max, z_min = -0.035 + (tam_x/2), 0.035 - (tam_x/2), -0.035 + (tam_y/2), 0.035 - (tam_y/2), 0.005, -0.005\n glBegin(GL_QUADS)\n glColor4f(0.75,0.75,0.75, 0.5) \n glVertex3f(x_max * medida, y_min * medida, 0 * medida)\n glVertex3f(x_max * medida, y_max * medida, 0 * medida)\n glVertex3f(x_min * medida, y_max * medida, 0 * medida)\n glVertex3f(x_min * medida, y_min * medida, 0 * medida)\n glEnd()\n glPopMatrix()\n\n # parte esquerda da janela\n x_max, x_min, y_max, y_min, z_max, z_min = 0.035 - (tam_x/2), 0.005 - (tam_x/2), (tam_y/2), -(tam_y/2), 0.005, -0.005\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0,0,0)\n\n # parte direita da janela\n x_max, x_min, y_max, y_min, z_max, z_min = -0.005 + (tam_x/2), -0.035 + (tam_x/2), (tam_y/2), -(tam_y/2), 0.005, -0.005\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0,0,0)\n\n # parte de cima da janela\n x_max, x_min, y_max, y_min, z_max, z_min = -0.035 + (tam_x/2), 0.035 - (tam_x/2), (tam_y/2), -0.035 + (tam_y/2), 0.005, -0.005\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0,0,0)\n\n # parte de baixo da janela\n x_max, x_min, y_max, y_min, z_max, z_min = -0.035 + (tam_x/2), 0.035 - (tam_x/2), 0.035 - (tam_y/2), -(tam_y/2), 0.005, -0.005\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0,0,0)\n\ndef habilitar_spot():\n if turnLampPc:\n glEnable(GL_LIGHT1)\n luz(6.34, 1.45, 4.125, GL_LIGHT1, 90, 0.2)\n\n glEnable(GL_LIGHT2)\n luz(6.34, 1.45, 5.025, GL_LIGHT2, 90 , 0.2)\n \n glEnable(GL_LIGHT3)\n luz(6.34, 1.45, 5.925, GL_LIGHT3, 90, 0.2)\n\n glEnable(GL_LIGHT4)\n luz(6.34, 1.45, 2.305, GL_LIGHT4, 90, 0.2)\n\n glEnable(GL_LIGHT5)\n luz(6.34, 1.45, 1.405, GL_LIGHT5, 90, 0.2)\n \n glEnable(GL_LIGHT6)\n luz(6.34, 1.45, 0.505, GL_LIGHT6, 90, 0.2)\n \n if turnLampRoof[0]['state']:\n glEnable(GL_LIGHT7)\n luz(2.5, 3, 3.2, GL_LIGHT7, 180, 0.005)\n if not isDay:\n glLightfv(GL_LIGHT7, GL_AMBIENT, [0.25, 0.25, 0.25, 1])\n else:\n glLightfv(GL_LIGHT7, GL_AMBIENT, [0.05, 0.05, 0.05, 1])\n \n\ndef desabilitar_spot():\n if not turnLampPc:\n glDisable(GL_LIGHT1)\n glDisable(GL_LIGHT2)\n glDisable(GL_LIGHT3)\n glDisable(GL_LIGHT4)\n glDisable(GL_LIGHT5)\n glDisable(GL_LIGHT6)\n if not turnLampRoof[0]['state']:\n glDisable(GL_LIGHT7)\n\ndef montar_lampadas(colorR, colorG, colorB):\n x, y, z = 5, 2.95, 4.8\n for lado_direiro in range(3):\n # apoio da lampada\n x_max, x_min, y_max, y_min, z_max, z_min = x, x-0.1, 3, 2.88, z+0.1, z-0.05\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0,0,0)\n\n x_max, x_min, y_max, y_min, z_max, z_min = x+1.1, x+1, 3, 2.88, z+0.1, z-0.05\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0,0,0)\n\n for par in range(2):\n glPushMatrix()\n glTranslatef(x*medida, y*medida, z*medida) # Define a posição do cilindro\n glRotatef(90, 0, 1, 0) # Rotaciona o cilindro\n glColor3f(colorR, colorG, colorB) # Define a cor do cilindro\n quad = gluNewQuadric() # Cria um novo objeto quadric\n gluQuadricDrawStyle(quad, GLU_FILL) # Define o estilo de desenho\n gluCylinder(quad, 0.15, 0.15, 1*medida, 32, 32) # Desenha o cilindro\n glPopMatrix()\n z+=0.05\n \n x-=2\n z = 4.8\n\n x, y, z = 5, 2.95, 1.6\n for lado_esquerdo in range(3):\n # apoio da lampada\n x_max, x_min, y_max, y_min, z_max, z_min = x, x-0.1, 3, 2.88, z+0.1, z-0.05\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0,0,0)\n\n x_max, x_min, y_max, y_min, z_max, z_min = x+1.1, x+1, 3, 2.88, z+0.1, z-0.05\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0,0,0)\n\n for par in range(2):\n glPushMatrix()\n glTranslatef(x*medida, y*medida, z*medida) # Define a posição do cilindro\n glRotatef(90, 0, 1, 0) # Rotaciona o cilindro\n glColor3f(colorR, colorG, colorB) # Define a cor do cilindro\n quad = gluNewQuadric() # Cria um novo objeto quadric\n gluQuadricDrawStyle(quad, GLU_FILL) # Define o estilo de desenho\n gluCylinder(quad, 0.15, 0.15, 1*medida, 32, 32) # Desenha o cilindro\n glPopMatrix()\n z+=0.05\n \n x-=2\n z = 1.6\n\n\ndef luz(x, y, z, type_luz, angle, clarity):\n glLightfv(type_luz, GL_POSITION, [x * medida, y*medida, z*medida, 1])\n glLightfv(type_luz, GL_SPOT_DIRECTION, [0.0, -1.0, 0.0])\n glLightfv(type_luz, GL_DIFFUSE, [1, 1, 1, 1])\n glLightfv(type_luz, GL_SPECULAR, [0.5, 0.5, 0.5, 1])\n glLightf(type_luz, GL_SPOT_CUTOFF, angle)\n glLightf(type_luz, GL_SPOT_EXPONENT, 1)\n \n glLightf(type_luz, GL_CONSTANT_ATTENUATION, 1)\n glLightf(type_luz, GL_LINEAR_ATTENUATION, 0.01)\n glLightf(type_luz, GL_QUADRATIC_ATTENUATION, clarity)\n\ndef montar_luminaria(r, g, b):\n # lado direito\n x_max, x_min, y_max, y_min, z_max, z_min = 6.58, 6.56, 1.515, 0.815, 4.135,4.115\n while(z_max < 6.4):\n glPushMatrix()\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.2, 0.2, 0.2)\n glPopMatrix()\n z_max+=0.9\n z_min+= 0.9\n \n x_max, x_min, y_max, y_min, z_max, z_min = 6.58, 6.35, 1.53, 1.515, 4.135,4.115\n while(z_max < 6.4):\n glPushMatrix()\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.2, 0.2, 0.2)\n glPopMatrix()\n z_max+=0.9\n z_min+= 0.9\n\n x_max, x_min, y_max, y_min, z_max, z_min = 6.35, 6.33, 1.53, 1.45, 4.135,4.115\n while(z_max < 6.4):\n glPushMatrix()\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.2, 0.2, 0.2)\n glPopMatrix()\n z_max+=0.9\n z_min+= 0.9\n \n x_max, x_min, y_max, y_min, z_max, z_min = 6.37, 6.31, 1.48, 1.42, 4.155,4.095\n while(z_max < 6.4):\n glPushMatrix()\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.2, 0.2, 0.2)\n glPopMatrix()\n glPushMatrix()\n glTranslatef(((x_max+x_min)/2)*medida, y_min*medida, ((z_max+z_min)/2)*medida)\n glColor3f(r, g, b)\n glutSolidSphere(0.15, 50, 50)\n glPopMatrix()\n z_max+=0.9\n z_min+= 0.9\n\n # lado esquerdo\n x_max, x_min, y_max, y_min, z_max, z_min = 6.58, 6.56, 1.515, 0.815, 2.315, 2.295\n while(z_max > 0):\n glPushMatrix()\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.2, 0.2, 0.2)\n glPopMatrix()\n z_max-=0.9\n z_min-= 0.9\n \n x_max, x_min, y_max, y_min, z_max, z_min = 6.58, 6.35, 1.53, 1.515, 2.315, 2.295\n while(z_max > 0):\n glPushMatrix()\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.2, 0.2, 0.2)\n glPopMatrix()\n z_max-=0.9\n z_min-= 0.9\n\n x_max, x_min, y_max, y_min, z_max, z_min = 6.35, 6.33, 1.53, 1.45, 2.315, 2.295\n while(z_max > 0):\n glPushMatrix()\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.2, 0.2, 0.2)\n glPopMatrix()\n z_max-=0.9\n z_min-= 0.9\n \n x_max, x_min, y_max, y_min, z_max, z_min = 6.37, 6.31, 1.48, 1.42, 2.335, 2.275\n while(z_max > 0):\n glPushMatrix()\n modelar_objeto(x_max, x_min, y_max, y_min, z_max, z_min, 0.2, 0.2, 0.2)\n glPopMatrix()\n glPushMatrix()\n glTranslatef(((x_max+x_min)/2)*medida, y_min*medida, ((z_max+z_min)/2)*medida)\n glColor3f(r, g, b)\n glutSolidSphere(0.15, 50, 50)\n glPopMatrix()\n z_max-=0.9\n z_min-= 0.9\n\ndef load_texture(filename):\n image = Image.open(filename)\n width, height = image.size\n image_data = image.tobytes()\n\n texture_id = glGenTextures(1)\n glBindTexture(GL_TEXTURE_2D, texture_id)\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image_data)\n\n return texture_id\n\ndef Draw():\n setup_lamp()\n global medida, cx, cy, cz, fx, fy, fz, ux, uy, uz, anglePorta, angleVent, objTeclado, turnLamp\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n\n glMaterialfv(GL_FRONT, GL_AMBIENT, [1.0, 1.0, 1.0, 1.0])\n glMaterialfv(GL_FRONT, GL_DIFFUSE, [1.0, 1.0, 1.0, 1.0])\n glMaterialfv(GL_FRONT, GL_SPECULAR, [0.1, 0.1, 0.1, 1])\n glMaterialfv(GL_FRONT, GL_SHININESS, 10.0)\n\n glMatrixMode(GL_MODELVIEW)\n glLoadIdentity()\n gluLookAt(cx, cy, cz, cx + fx, cy + fy, cz + fz, ux, uy, uz)\n\n glPushMatrix()\n ligar_monitor()\n glPopMatrix()\n\n glPushMatrix()\n montar_teclado()\n glPopMatrix()\n\n\n glPushMatrix()\n if not turnLampPc:\n montar_luminaria(0.4, 0.4, 0.4)\n else:\n montar_luminaria(1, 1, 1)\n \n if turnLampRoof[0]['state']:\n montar_lampadas(1, 1, 1)\n else:\n montar_lampadas(0.3, 0.3, 0.3)\n habilitar_spot()\n desabilitar_spot()\n glPopMatrix()\n\n glPushMatrix()\n montar_tomada()\n glPopMatrix()\n\n glPushMatrix()\n ligar_pc()\n glPopMatrix()\n\n glPushMatrix()\n montar_paredes()\n montar_mesas()\n montar_monitores()\n montar_quadro()\n montar_estruturas_da_porta()\n glPopMatrix()\n \n glPushMatrix()\n glEnable(GL_BLEND)\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)\n montar_janela_lado_direito()\n glPopMatrix()\n\n glPushMatrix()\n x_center, y_center, z_center = 0.75, 2.1, -0.075\n for i in range(10):\n glPushMatrix()\n glTranslatef(x_center*medida, y_center*medida, z_center*medida)\n glRotatef(angleJanela, 0, 1, 0)\n montar_janela_de_movimento(0.5, 1.7)\n glPopMatrix()\n x_center+=0.5\n\n x_center, y_center, z_center = 6.05, 2.1, -0.075\n for i in range(4):\n glPushMatrix()\n glTranslatef(x_center*medida, y_center*medida, z_center*medida)\n glRotatef(angleJanela, 0, 1, 0)\n montar_janela_de_movimento(0.5, 1.7)\n glPopMatrix()\n x_center+=0.5\n glPopMatrix()\n\n glPushMatrix() \n glTranslatef(7.975*medida, 0, 5.585*medida)\n glRotatef(anglePorta, 0, 1, 0)\n montar_porta()\n glPopMatrix()\n\n glPushMatrix() \n escrever_no_quadro()\n glPopMatrix()\n\n glPushMatrix() \n montar_bases_dos_ventiladores()\n glPopMatrix()\n\n glPushMatrix()\n glTranslatef(5*medida, 2.875*medida, 3.2*medida)\n glRotatef(angleVent, 0, 1, 0)\n montar_ventilador()\n glPopMatrix()\n\n glPushMatrix()\n glTranslatef(2*medida, 2.875*medida, 3.2*medida)\n glRotatef(angleVent, 0, 1, 0)\n montar_ventilador()\n glPopMatrix()\n\n glutSwapBuffers()\n\ndef myInit():\n glClearColor(0.73, 0.95, 0.97, 1)\n glEnable(GL_DEPTH_TEST)\n\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n glFrustum(-1, 1, -1, 1, 1, 100)\n glMatrixMode(GL_MODELVIEW)\n\ndef gerenciaMouse(button,state, x, y):\n global antigo_x, antigo_y\n\n vport = glGetIntegerv(GL_VIEWPORT)\n depth = glReadPixels(x, vport[3] - y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT)\n\n vport = glGetIntegerv(GL_VIEWPORT)\n mvmatrix = glGetDoublev(GL_MODELVIEW_MATRIX)\n projmatrix = glGetDoublev(GL_PROJECTION_MATRIX)\n\n worldCoordinate1 = gluUnProject(x, vport[3] - y, depth, mvmatrix, projmatrix, vport)\n\n if state == 1:\n for pc in turnOnPc:\n if pc['x_max']*medida >= worldCoordinate1[0] >= ((pc['x_min']*medida) - 0.2) and pc['y_max']*medida >= worldCoordinate1[1] >= pc['y_min']*medida and pc['z_max']*medida >= worldCoordinate1[2] >= pc['z_min']*medida:\n if pc['state']:\n pc['state'] = False\n break\n else:\n pc['state'] = True\n break\n\n for switch in turnSwitch:\n if switch['x_max']*medida >= worldCoordinate1[0] >= ((switch['x_min']*medida) - 0.2) and switch['y_max']*medida >= worldCoordinate1[1] >= switch['y_min']*medida and switch['z_max']*medida >= worldCoordinate1[2] >= switch['z_min']*medida:\n if switch['state']:\n switch['state'] = False\n break\n else:\n switch['state'] = True\n break\n\n for lamp in turnLampRoof:\n if lamp['x_max']*medida >= worldCoordinate1[0] >= ((lamp['x_min']*medida) - 0.2) and lamp['y_max']*medida >= worldCoordinate1[1] >= lamp['y_min']*medida and lamp['z_max']*medida >= worldCoordinate1[2] >= lamp['z_min']*medida:\n if lamp['state']:\n lamp['state'] = False\n break\n else:\n lamp['state'] = True\n break\n\n antigo_x = x\n antigo_y = y\n glutPostRedisplay()\n\ndef mouse_camera(mouse_x, mouse_y):\n global ang_x, ang_y, antigo_x, antigo_y, fx, fy, fz\n\n ang_x -= (mouse_x - antigo_x) * mouseSens\n ang_y -= (mouse_y - antigo_y) * mouseSens\n\n fx = math.cos(ang_x) * math.sin(ang_y)\n fy = math.cos(ang_y)\n fz = math.sin(ang_x) * math.sin(ang_y)\n\n antigo_x = mouse_x\n antigo_y = mouse_y\n\n glutPostRedisplay()\n\n\ndef setup_lighting():\n glEnable(GL_COLOR_MATERIAL)\n glEnable(GL_LIGHTING)\n\n glEnable(GL_LIGHT0)\n glEnable(GL_LIGHT7)\n\n # luz no pc\n glEnable(GL_LIGHT1)\n glEnable(GL_LIGHT2)\n glEnable(GL_LIGHT3)\n glEnable(GL_LIGHT4)\n glEnable(GL_LIGHT5)\n glEnable(GL_LIGHT6)\n\n\n\n glShadeModel(GL_SMOOTH)\n glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)\n\n\ndef main():\n global objTeclado, objMonitorOn, texture_board, texture_fan, texture_floor\n\n glutInit()\n glutInitWindowSize(1600, 1000)\n glutInitWindowPosition(0, 0)\n glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE)\n glutCreateWindow(\"lab 2\")\n glEnable(GL_MULTISAMPLE)\n myInit()\n texture_board = load_texture(\"texture/board.jpg\")\n texture_fan = load_texture(\"texture/fan.jpg\")\n texture_floor = load_texture(\"texture/floor.jpeg\")\n objTeclado = OBJ('ObjBlender/teclado.obj')\n objMonitorOn = OBJ('ObjBlender/monitor.obj')\n setup_lighting()\n glutDisplayFunc(Draw)\n glutIdleFunc(loop)\n glutKeyboardFunc(keyboard)\n glutMouseFunc(gerenciaMouse)\n glutMotionFunc(mouse_camera)\n glutMainLoop()\n\nif __name__ == '__main__':\n main()","repo_name":"pedriinho/Computer-Graphics-Project","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":39118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"27190376708","text":"from aiogram.dispatcher import FSMContext\nfrom aiogram.types import CallbackQuery, Message\n\nimport typing\n\nfrom utils.callback import order_cb\nfrom utils.db_api.order_controller import get_orders, update_order\nfrom utils.db_api.user_controller import get_user_id, update_user_balance_set\nfrom states.accept_order import Order\nfrom loader import dp, bot_admin\n\n\n@dp.callback_query_handler(order_cb.filter(accept='True'), state=\"*\")\nasync def accept_order(call: CallbackQuery, callback_data: typing.Dict[str, str], state: FSMContext):\n await state.finish()\n ticker = await get_orders(int(callback_data['order_id']))\n if ticker.accepted is False:\n await update_order(ticker.id, 'Оплата подтверждена', True)\n await bot_admin.send_message(ticker.user_id, 'Заказ ID {}\\nПодтвержден'.format(ticker.id))\n await call.message.answer('Действие подтверждено')\n elif ticker.accepted is True:\n await call.message.answer('Действие подтверждено ранее')\n\n\n@dp.callback_query_handler(order_cb.filter(accept='False'), state=\"*\")\nasync def remove_order(call: CallbackQuery, callback_data: typing.Dict[str, str], state: FSMContext):\n await state.finish()\n ticker = await get_orders(int(callback_data['order_id']))\n if ticker.accepted is False:\n await Order.status_message.set()\n await state.update_data(ticker_id=ticker.id)\n await call.message.answer('Напиши причину отказа платежа:')\n elif ticker.accepted is True:\n await call.message.answer('Действие подтверждено ранее')\n\n\n@dp.message_handler(state=Order.status_message)\nasync def remove_message(message: Message, state: FSMContext):\n ticker_data = await state.get_data()\n await state.finish()\n await update_order(int(ticker_data['ticker_id']), message.text, True)\n ticker = await get_orders(int(ticker_data['ticker_id']))\n user = await get_user_id(ticker.user_id)\n new_balance = round(user.balance + ticker.amount_spend, 2)\n await update_user_balance_set(ticker.user_id, new_balance)\n await bot_admin.send_message(ticker.user_id, 'Пополнение ID {}\\nОтклонено'.format(ticker.id))\n await message.answer('Действие подтверждено')\n\n","repo_name":"Ilissi/admin_transfermonney_bot","sub_path":"handlers/users/accept_order.py","file_name":"accept_order.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"70761855608","text":"from flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\nfrom model.config import Config\nimport json\nfrom flask import Flask, request\nfrom flask_cors import CORS\nimport os\nimport logging\nimport datetime\nfrom dotenv import load_dotenv\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\nload_dotenv(os.path.join(basedir, \".env\"))\n\n\n# For dev logging - comment out for Gunicorn\nlogging.basicConfig(\n level=logging.INFO,\n format=f\"%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s\",\n)\n\n# ~ Databases ~ #\ndb = SQLAlchemy() # <-Initialize database object\nmigrate = Migrate() # <-Initialize migration object\n\n\ndef create_app():\n \"\"\"Construct core application\"\"\"\n app = Flask(__name__)\n\n # For Gunicorn logging\n # gunicorn_logger = logging.getLogger('gunicorn.error')\n # app.logger.handlers = gunicorn_logger.handlers\n # app.logger.setLevel(gunicorn_logger.level)\n\n ###\n # NOTE: to print in Flask, do `app.logger.info(var_to_print)`\n ###\n\n # Pull from config file\n app.config.from_object(Config)\n db.init_app(app) # <- This will get called in our models.py file\n migrate.init_app(app, db) # <- Migration directory\n\n CORS(app, resources={r\"/*\": {\"origins\": \"*\"}})\n\n from model import models # noqa\n from model.models import User, UserModelSession # noqa\n\n # @app.route('/')\n # def home():\n # return \"ok\"\n\n @app.route(\"/api/login\", methods=[\"POST\"])\n def login():\n user_info = json.loads(request.data)[\"user_info\"]\n username = user_info[\"username\"]\n password = user_info[\"password\"]\n usernames = [\"user\" + str(i) for i in range(1, 31)]\n passwords = [\n \"ph6n76gec9\",\n \"l98zjxj6vc\",\n \"mq577o05wz\",\n \"tcty170i9o\",\n \"1kgh4895fx\",\n \"ys175n9iv0\",\n \"0fvcfgxplj\",\n \"vu34rphc82\",\n \"hyhnyg9xob\",\n \"oqqct6wllc\",\n \"oswly1eaxq\",\n \"qe7inpmska\",\n \"7ilhsc46ox\",\n \"wo81yy0eci\",\n \"2kufnda8bs\",\n \"nzlljrerzt\",\n \"ft0jinctnm\",\n \"r3swsmr2rn\",\n \"4cbp35phhh\",\n \"falyezzw4r\",\n \"r5v0mrvpuv\",\n \"auee014rmj\",\n \"wpprodq8vb\",\n \"6nddssd3gg\",\n \"z2394iw3mq\",\n \"a3gkc6czb5\",\n \"ddxzlpkzhv\",\n \"2owdt20zas\",\n \"29uhzahhol\",\n \"mfhs4cyc4x\",\n ]\n for i in range(len(usernames)):\n try:\n # Creates new accounts\n new_user = User(username=usernames[i], password=passwords[i])\n db.session.add(new_user)\n db.session.commit()\n\n except: # noqa\n db.session.rollback()\n\n try:\n guest_user = User(username=\"guest\", password=\"guest\")\n db.session.add(guest_user)\n db.session.commit()\n except: # noqa\n db.session.rollback()\n\n user = User.query.filter_by(username=username).first()\n if user is None:\n return {\"validID\": False, \"userID\": None}\n\n if password == user.password:\n opening_decision = decision_maker.QUESTIONS[\"ask_location\"]\n model_prompt = opening_decision[\"model_prompt\"]\n\n choices = opening_decision[\"choices\"]\n\n # Creates current session; FE will need to pass in session id\n # with Session() as db_session:\n new_session = UserModelSession(user_id=user.id)\n db.session.add(new_session)\n db.session.commit()\n\n decision_maker.initialise_remaining_choices(user.id)\n decision_maker.initialise_prev_questions(user.id)\n decision_maker.clear_suggestions(user.id)\n decision_maker.clear_choices(user.id)\n decision_maker.clear_datasets(user.id)\n decision_maker.user_choices[user.id][\"current_session_id\"] = new_session.id\n\n return {\n \"validID\": True,\n \"userID\": user.id,\n \"sessionID\": new_session.id,\n \"model_prompt\": model_prompt,\n \"choices\": list(choices.keys()),\n }\n return {\"validID\": False, \"userID\": None}\n\n @app.route(\"/api/update_session\", methods=[\"POST\"])\n def update_session():\n user_info = json.loads(request.data)[\"choice_info\"]\n user_id = user_info[\"user_id\"]\n session_id = user_info[\"session_id\"]\n input_type = user_info[\"input_type\"]\n user_choice = user_info[\"user_choice\"]\n\n if type(input_type) == list and len(input_type) == 0:\n input_type = \"any\"\n elif type(input_type) == list and len(input_type) == 1:\n input_type = input_type[0]\n\n user = User.query.filter_by(id=user_id).first()\n user_session = UserModelSession.query.filter_by(id=session_id).first()\n\n decision_maker.save_current_choice(\n user_id, input_type, user_choice, user_session, db.session, app\n )\n # return {\"choice\": choice.choice_desc}\n output = decision_maker.determine_next_choice(\n user_id, input_type, user_choice, db.session, user_session, app\n )\n # Update last accessed\n user.last_accessed = datetime.datetime.utcnow()\n db.session.commit()\n\n return {\n \"chatbot_response\": output[\"model_prompt\"],\n \"user_options\": output[\"choices\"],\n }\n\n return app\n\n\nfrom model.rule_based_model import ModelDecisionMaker # noqa\n\ndecision_maker = ModelDecisionMaker()\n\nif __name__ == \"__main__\":\n app = create_app()\n","repo_name":"lisaalaz/satbot","sub_path":"model/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5675,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"77"} +{"seq_id":"8115640582","text":"import pytest\n\nfrom django.core.mail import send_mail\n\n\n@pytest.fixture(autouse=True)\ndef override_email_backend(settings):\n \"\"\"Override the email backend for all the tests in this file.\"\"\"\n\n settings.EMAIL_BACKEND = \"emails.backends.LocmemWhitelistEmailBackend\"\n settings.EMAIL_WHITELIST = [\"allowed1@example.org\", \"allowed2@example.org\"]\n\n\ndef test_whitelisted_emails_are_sent(settings, mailoutbox):\n send_mail(\"Test\", \"Test\", \"from@example.org\", [\"allowed1@example.org\"])\n assert len(mailoutbox) == 1\n\n\ndef test_non_whitelisted_emails_are_rejected(settings, mailoutbox):\n send_mail(\"Test\", \"Test\", \"from@example.org\", [\"disallowed1@example.org\"])\n assert len(mailoutbox) == 0\n\n\ndef test_partial_whitelist_emails_are_rejected(settings, mailoutbox):\n send_mail(\n \"Test\",\n \"Test\",\n \"from@example.org\",\n [\"allowed1@example.org\", \"disallowed1@example.org\"],\n )\n assert len(mailoutbox) == 0\n\n\ndef test_emails_with_many_whitelisted_contacts_are_sent(settings, mailoutbox):\n send_mail(\n \"Test\",\n \"Test\",\n \"from@example.org\",\n [\"allowed1@example.org\", \"allowed2@example.org\"],\n )\n assert len(mailoutbox) == 1\n","repo_name":"MTES-MCT/aides-territoires","sub_path":"src/emails/tests/test_backends.py","file_name":"test_backends.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"77"} +{"seq_id":"70491224570","text":"\n# Space: O(1)\n# Time: O(n)\n\nclass Solution:\n def moveZeroes(self, nums) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n\n n = len(nums)\n temp = 0\n while n:\n if nums[temp] == 0:\n nums.append(nums.pop(temp))\n else:\n temp += 1\n n -= 1\n\n\n\n\n\n\n","repo_name":"lht19900714/Leetcode_Solutions","sub_path":"Algorithms/0283_Move_Zeroes/Python/Move_Zeroes_Solution_2.py","file_name":"Move_Zeroes_Solution_2.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":"74947999927","text":"from pyrogram import Client, filters\nfrom fbot.sample_config import Config\nfrom fbot import AUTH_USERS\n\n\nusers = Config.AUTH_USERS\n\n@Client.on_message(filters.command([\"start\", \"help\"]))\nasync def start(bot, update):\n if update.from_user.id not in users:\n await bot.delete_messages(\n chat_id=update.chat.id,\n message_ids=update.message_id,\n revoke=True\n )\n return\n","repo_name":"ConfusedKarma/Fbot","sub_path":"fbot/plugins/delcmd.py","file_name":"delcmd.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"9298584219","text":"from tkinter import *\r\nimport xlrd\r\nxlrd.xlsx.ensure_elementtree_imported(False, None)\r\nxlrd.xlsx.Element_has_iter = True\r\nfrom random import random, sample\r\n\r\nwindow=Tk()\r\nwindow.title(\"Let's learn Languages!\")\r\nwindow.geometry('500x500+700+200')\r\n\r\nlocation = 'words.xlsx'\r\nwb = xlrd.open_workbook(location)\r\nsheet = wb.sheet_by_index(0)\r\nglobal value\r\n\r\ndef showanswer():\r\n global value\r\n global label2\r\n label2 = Label(window, text = sheet.cell_value(value,0), wraplength=300, justify=\"left\",font=15)\r\n label2.pack(padx = 20, pady = 50)\r\n label.pack_forget()\r\n show_answer_button.pack_forget()\r\n #print(sheet.nrows)\r\n #print(int(100000*random()%sheet.nrows))\r\n global nextbutton\r\n nextbutton = Button(window, text='Next', command=next)\r\n nextbutton.pack(side=BOTTOM, pady=10)\r\n\r\ndef next():\r\n global label2\r\n label2.pack_forget()\r\n global nextbutton\r\n nextbutton.pack_forget()\r\n start()\r\n\r\n\r\n\r\ndef start():\r\n global value\r\n value = int(100000*random()%sheet.nrows)\r\n value = value\r\n global label \r\n label = Label(window, text = sheet.cell_value(value,1), wraplength=300, justify=\"left\", font=30)\r\n label.pack(padx = 20, pady = 50)\r\n startbutton.pack_forget()\r\n global show_answer_button\r\n show_answer_button = Button(window, text = 'Show answer', command=showanswer)\r\n show_answer_button.pack(side=BOTTOM, pady=10)\r\n# print(sheet.cell_value(0, 0))\r\n# print(sheet.cell_value(0, 1))\r\n \r\n\r\n\r\nstartbutton = Button(window, text = 'Start', command=start)\r\nstartbutton.pack(side=BOTTOM, pady=10)\r\n#print(int(100000*random()%sheet.nrows))\r\nwindow.mainloop()\r\n\r\n","repo_name":"Tam8thang/Sentence_learning","sub_path":"Languagelearnings.py","file_name":"Languagelearnings.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"5905453235","text":"from __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING, Optional\n\nimport discord\nfrom discord import app_commands\nfrom discord.ext import commands\nfrom pyot.core.exceptions import NotFound\nfrom pyot.utils.lol import champion\n\nfrom utils import checks, const\nfrom utils.lol.const import LiteralServer, LiteralServerUpper, platform_to_server, server_to_platform\nfrom utils.lol.utils import get_all_champ_names, get_meraki_patch, get_pyot_meraki_champ_diff_list\n\nfrom .._fpc_utils import FPCSettingsBase\nfrom ._models import Account\n\n# need to import the last because in import above we activate 'lol' model\nfrom pyot.models.lol import summoner # isort: skip\n\nif TYPE_CHECKING:\n from utils import AluBot, AluGuildContext\n\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.DEBUG)\n\n\nclass AddStreamFlags(commands.FlagConverter, case_insensitive=True):\n name: str\n server: LiteralServer\n account: str\n\n\nclass RemoveStreamFlags(commands.FlagConverter, case_insensitive=True):\n name: str\n server: Optional[LiteralServer]\n account: Optional[str]\n\n\nclass LoLNotifsSettings(FPCSettingsBase, name='LoL'):\n \"\"\"Commands to set up fav champ + fav stream notifs.\n\n These commands allow you to choose streamers from our database as your favorite \\\n (or you can request adding them if they are missing) and choose your favorite League of Legends champions \\\n The bot will send messages in a chosen channel when your fav streamer picks your fav champ.\n \"\"\"\n\n def __init__(self, bot: AluBot, *args, **kwargs):\n super().__init__(\n bot,\n *args,\n colour=const.Colour.rspbrry(),\n game='lol',\n game_mention='League of Legends',\n game_icon=const.Logo.lol,\n extra_account_info_columns=['platform', 'account'],\n character_name_by_id=champion.name_by_id,\n character_id_by_name=champion.id_by_name,\n all_character_names=get_all_champ_names,\n character_word_plural='champs',\n **kwargs,\n )\n\n async def cog_load(self) -> None:\n await self.bot.ini_twitch()\n return await super().cog_load()\n\n # lol ##############################################\n\n slh_lol = app_commands.Group(\n name=\"lol\",\n description=\"League of Legends FPC (Favourite Player+Character) commands.\",\n default_permissions=discord.Permissions(manage_guild=True),\n guild_only=True,\n )\n\n @checks.hybrid.is_manager()\n @commands.group(name='lol', aliases=['league'])\n async def ext_lol(self, ctx: AluGuildContext):\n \"\"\"League of Legends FPC (Favourite Player+Character) commands.\"\"\"\n await ctx.send_help(ctx.command)\n\n # lol channel ##############################################\n\n slh_lol_channel = app_commands.Group(\n name='channel', description='Commands to manage your LoL FPC channel.', parent=slh_lol\n )\n\n @checks.hybrid.is_manager()\n @ext_lol.group(name='channel')\n async def ext_lol_channel(self, ctx: AluGuildContext):\n \"\"\"Commands to manage your LoL FPC channel.\"\"\"\n await ctx.send_help(ctx.command)\n\n # lol channel set ##############################################\n\n @slh_lol_channel.command(name='set')\n @app_commands.describe(channel='Choose channel to set up LoLFeed notifications')\n async def slh_lol_channel_set(\n self, ntr: discord.Interaction[AluBot], channel: Optional[discord.TextChannel] = None\n ):\n \"\"\"Set channel to be the LoLFeed notifications channel.\"\"\"\n await self.channel_set(ntr, channel)\n\n @checks.hybrid.is_manager()\n @ext_lol_channel.command(name='set', usage='[channel=curr]')\n async def ext_lol_channel_set(self, ctx: AluGuildContext, channel: Optional[discord.TextChannel] = None):\n \"\"\"Set channel to be the LoLFeed notifications channel.\"\"\"\n await self.channel_set(ctx, channel)\n\n # lol channel disable ##############################################\n\n @slh_lol_channel.command(name='disable')\n async def slh_lol_channel_disable(self, ntr: discord.Interaction[AluBot]):\n \"\"\"Disable LoLFeed notifications channel.\"\"\"\n await self.channel_disable(ntr)\n\n @checks.hybrid.is_manager()\n @ext_lol_channel.command(name='disable')\n async def ext_lol_channel_disable(self, ctx: AluGuildContext):\n \"\"\"Stop getting LoLFeed notifs. Data about fav champs/players won't be affected.\"\"\"\n await self.channel_disable(ctx)\n\n # lol channel check ##############################################\n\n @slh_lol_channel.command(name='check')\n async def slh_lol_channel_check(self, ntr: discord.Interaction[AluBot]):\n \"\"\"Check if LoLFeed channel is set up.\"\"\"\n await self.channel_check(ntr)\n\n @checks.hybrid.is_manager()\n @ext_lol_channel.command(name='check')\n async def ext_lol_channel_check(self, ctx: AluGuildContext):\n \"\"\"Check if LoLFeed channel is set up in the server.\"\"\"\n await self.channel_check(ctx)\n\n # lol database ##############################################\n\n slh_lol_database = app_commands.Group(\n name='database',\n description='Group command about LoLFeed database',\n parent=slh_lol,\n )\n\n @checks.hybrid.is_manager()\n @ext_lol.group(name='database', aliases=['db'])\n async def ext_lol_database(self, ctx: AluGuildContext):\n \"\"\"Group command about LoL database, for actual commands use it together with subcommands\"\"\"\n await ctx.send_help(ctx.command)\n\n # helper functions ##############################################\n\n @staticmethod\n def cmd_usage_str(**kwargs):\n platform = kwargs.pop('platform')\n account = kwargs.pop('account')\n return f'server: {platform_to_server(platform).upper()} account: {account}'\n\n @staticmethod\n def player_acc_string(**kwargs):\n platform = kwargs.pop('platform')\n account = kwargs.pop('account')\n return f\"`{platform_to_server(platform).upper()}` - `{account}` {Account(platform, account).links}\"\n\n @staticmethod\n async def get_lol_id(server: LiteralServer, account: str) -> tuple[str, str, str]:\n try:\n platform = server_to_platform(server)\n player = await summoner.Summoner(name=account, platform=platform).get()\n return player.id, player.platform, player.name\n except NotFound:\n raise commands.BadArgument(\n f\"Error checking league account with name `{account}` for `{server}` server: \\n\"\n f\"This account does not exist.\"\n )\n\n async def get_account_dict(self, *, server: LiteralServer, account: str) -> dict:\n lol_id, platform, account = await self.get_lol_id(server, account)\n return {'id': lol_id, 'platform': platform, 'account': account}\n\n # lol database list ##################################\n\n @slh_lol_database.command(name='list')\n async def slh_lol_database_list(self, ntr: discord.Interaction[AluBot]):\n \"\"\"List of players in the database available for LoLFeed feature.\"\"\"\n await self.database_list(ntr)\n\n @checks.hybrid.is_manager()\n @ext_lol_database.command(name='list')\n async def ext_lol_database_list(self, ctx: AluGuildContext):\n \"\"\"List of players in the database available for LoLFeed feature.\"\"\"\n await self.database_list(ctx)\n\n # lol database request ##################################\n\n @slh_lol_database.command(name='request')\n @app_commands.describe(\n name='twitch.tv player\\'s handle',\n server='Server of the account, i.e. \"NA\", \"EUW\"',\n account='Summoner name of the account',\n )\n async def slh_lol_database_request(\n self, ntr: discord.Interaction[AluBot], name: str, server: LiteralServerUpper, account: str\n ):\n \"\"\"Request player to be added into the database.\"\"\"\n player_dict = await self.get_player_dict(name_flag=name, twitch_flag=True)\n account_dict = await self.get_account_dict(server=server, account=account)\n await self.database_request(ntr, player_dict, account_dict)\n\n @checks.hybrid.is_manager()\n @ext_lol_database.command(\n name='request',\n usage='name: server: account: ',\n )\n async def ext_lol_database_request(self, ctx: AluGuildContext, *, flags: AddStreamFlags):\n \"\"\"Request player to be added into the database.\n This will send a request message into Aluerie's personal logs channel.\n \"\"\"\n player_dict = await self.get_player_dict(name_flag=flags.name, twitch_flag=True)\n account_dict = await self.get_account_dict(server=flags.server, account=flags.account)\n await self.database_request(ctx, player_dict, account_dict)\n\n # lol player ##################################\n\n slh_lol_player = app_commands.Group(\n name='player',\n description='Group command about LoLFeed player',\n parent=slh_lol,\n )\n\n @checks.hybrid.is_manager()\n @ext_lol.group(name='player', aliases=['streamer'])\n async def ext_lol_player(self, ctx: AluGuildContext):\n \"\"\"Group command about LoL player, for actual commands use it together with subcommands\"\"\"\n await ctx.send_help(ctx.command)\n\n # lol player add ##################################\n\n async def lol_player_add_autocomplete(\n self, ntr: discord.Interaction, current: str\n ) -> list[app_commands.Choice[str]]:\n return await self.player_add_remove_autocomplete(ntr, current, mode_add=True)\n\n @slh_lol_player.command(name='add')\n @app_commands.describe(\n **{\n f'name{i}': 'Name of a player. Suggestions from database above exclude your already fav players'\n for i in range(1, 11)\n }\n )\n @app_commands.autocomplete(\n name1=lol_player_add_autocomplete,\n name2=lol_player_add_autocomplete,\n name3=lol_player_add_autocomplete,\n name4=lol_player_add_autocomplete,\n name5=lol_player_add_autocomplete,\n name6=lol_player_add_autocomplete,\n name7=lol_player_add_autocomplete,\n name8=lol_player_add_autocomplete,\n name9=lol_player_add_autocomplete,\n name10=lol_player_add_autocomplete,\n )\n # @app_commands.autocomplete(**{f'name{i}': player_add_autocomplete for i in range(1, 11)})\n async def slh_lol_player_add(\n self,\n ntr: discord.Interaction[AluBot],\n name1: Optional[str],\n name2: Optional[str],\n name3: Optional[str],\n name4: Optional[str],\n name5: Optional[str],\n name6: Optional[str],\n name7: Optional[str],\n name8: Optional[str],\n name9: Optional[str],\n name10: Optional[str],\n ):\n \"\"\"Add player to your favourites.\"\"\"\n await self.player_add_remove(ntr, locals(), mode_add=True)\n\n @checks.hybrid.is_manager()\n @ext_lol_player.command(name='add', usage='')\n async def ext_lol_player_add(self, ctx: AluGuildContext, *, player_names: str):\n \"\"\"Add player to your favourites.\"\"\"\n await self.player_add_remove(ctx, locals(), mode_add=True)\n\n # lol player remove ##################################\n\n async def player_remove_autocomplete(\n self, ntr: discord.Interaction, current: str\n ) -> list[app_commands.Choice[str]]:\n return await self.player_add_remove_autocomplete(ntr, current, mode_add=False)\n\n @slh_lol_player.command(name='remove')\n @app_commands.describe(**{f'name{i}': 'Name of a player' for i in range(1, 11)})\n @app_commands.autocomplete(\n name1=player_remove_autocomplete,\n name2=player_remove_autocomplete,\n name3=player_remove_autocomplete,\n name4=player_remove_autocomplete,\n name5=player_remove_autocomplete,\n name6=player_remove_autocomplete,\n name7=player_remove_autocomplete,\n name8=player_remove_autocomplete,\n name9=player_remove_autocomplete,\n name10=player_remove_autocomplete,\n )\n # @app_commands.autocomplete(**{f'name{i}': player_remove_autocomplete for i in range(1, 11)})\n async def slh_lol_player_remove(\n self,\n ntr: discord.Interaction[AluBot],\n name1: Optional[str],\n name2: Optional[str],\n name3: Optional[str],\n name4: Optional[str],\n name5: Optional[str],\n name6: Optional[str],\n name7: Optional[str],\n name8: Optional[str],\n name9: Optional[str],\n name10: Optional[str],\n ):\n \"\"\"Remove player from your favourites.\"\"\"\n await self.player_add_remove(ntr, locals(), mode_add=False)\n\n @checks.hybrid.is_manager()\n @ext_lol_player.command(name='remove', usage='')\n async def ext_lol_player_remove(self, ctx: AluGuildContext, *, player_names: str):\n \"\"\"Add player to your favourites.\"\"\"\n await self.player_add_remove(ctx, locals(), mode_add=False)\n\n # lol player list ##################################\n\n @slh_lol_player.command(name='list')\n async def slh_lol_player_list(self, ntr: discord.Interaction[AluBot]):\n \"\"\"Show list of your favourite players.\"\"\"\n await self.player_list(ntr)\n\n @checks.hybrid.is_manager()\n @ext_lol_player.command(name='list')\n async def ext_lol_player_list(self, ctx: AluGuildContext):\n \"\"\"Show list of your favourite players.\"\"\"\n await self.player_list(ctx)\n\n # lol champ ##################################\n\n slh_lol_champ = app_commands.Group(\n name='champion',\n description='Group command about LoLFeed champs',\n parent=slh_lol,\n )\n\n @checks.hybrid.is_manager()\n @ext_lol.group(name='champion', aliases=['champ'])\n async def ext_lol_champ(self, ctx: AluGuildContext):\n \"\"\"Group command about LoL champs, for actual commands use it together with subcommands\"\"\"\n await ctx.send_help(ctx.command)\n\n # lol champ add ##################################\n\n async def lol_champ_add_autocomplete(\n self, ntr: discord.Interaction, current: str\n ) -> list[app_commands.Choice[str]]:\n return await self.character_add_remove_autocomplete(ntr, current, mode_add=True)\n\n @slh_lol_champ.command(name='add')\n @app_commands.describe(**{f'name{i}': 'Name of a champ' for i in range(1, 11)})\n @app_commands.autocomplete(\n name1=lol_champ_add_autocomplete,\n name2=lol_champ_add_autocomplete,\n name3=lol_champ_add_autocomplete,\n name4=lol_champ_add_autocomplete,\n name5=lol_champ_add_autocomplete,\n name6=lol_champ_add_autocomplete,\n name7=lol_champ_add_autocomplete,\n name8=lol_champ_add_autocomplete,\n name9=lol_champ_add_autocomplete,\n name10=lol_champ_add_autocomplete,\n )\n # @app_commands.autocomplete(**{f'name{i}': lol_champ_add_autocomplete for i in range(1, 11)})\n async def slh_lol_champ_add(\n self,\n ntr: discord.Interaction[AluBot],\n name1: Optional[str],\n name2: Optional[str],\n name3: Optional[str],\n name4: Optional[str],\n name5: Optional[str],\n name6: Optional[str],\n name7: Optional[str],\n name8: Optional[str],\n name9: Optional[str],\n name10: Optional[str],\n ):\n \"\"\"Add champ to your favourites.\"\"\"\n await self.character_add_remove(ntr, locals(), mode_add=True)\n\n @checks.hybrid.is_manager()\n @ext_lol_champ.command(\n name='add',\n usage='',\n )\n async def ext_lol_champ_add(self, ctx: AluGuildContext, *, champ_names: str):\n \"\"\"Add champ(-s) to your fav champ list.\"\"\"\n await self.character_add_remove(ctx, locals(), mode_add=True)\n\n # lol champ remove ##################################\n\n async def lol_champ_remove_autocomplete(\n self, ntr: discord.Interaction, current: str\n ) -> list[app_commands.Choice[str]]:\n return await self.character_add_remove_autocomplete(ntr, current, mode_add=False)\n\n @slh_lol_champ.command(name='remove')\n @app_commands.describe(**{f'name{i}': 'Name of a champ' for i in range(1, 11)})\n @app_commands.autocomplete(\n name1=lol_champ_remove_autocomplete,\n name2=lol_champ_remove_autocomplete,\n name3=lol_champ_remove_autocomplete,\n name4=lol_champ_remove_autocomplete,\n name5=lol_champ_remove_autocomplete,\n name6=lol_champ_remove_autocomplete,\n name7=lol_champ_remove_autocomplete,\n name8=lol_champ_remove_autocomplete,\n name9=lol_champ_remove_autocomplete,\n name10=lol_champ_remove_autocomplete,\n )\n # @app_commands.autocomplete(**{f'name{i}': lol_champ_add_autocomplete for i in range(1, 11)})\n async def slh_lol_champ_remove(\n self,\n ntr: discord.Interaction[AluBot],\n name1: Optional[str],\n name2: Optional[str],\n name3: Optional[str],\n name4: Optional[str],\n name5: Optional[str],\n name6: Optional[str],\n name7: Optional[str],\n name8: Optional[str],\n name9: Optional[str],\n name10: Optional[str],\n ):\n \"\"\"Remove champ from your favourites.\"\"\"\n await self.character_add_remove(ntr, locals(), mode_add=False)\n\n @checks.hybrid.is_manager()\n @ext_lol_champ.command(name='remove', usage='')\n async def ext_lol_champ_remove(self, ctx: AluGuildContext, *, champ_names: str):\n \"\"\"Remove champ(-es) from your fav champs list.\"\"\"\n await self.character_add_remove(ctx, locals(), mode_add=False)\n\n # lol champ list ##################################\n\n @slh_lol_champ.command(name='list')\n async def slh_lol_champ_list(self, ntr: discord.Interaction[AluBot]):\n \"\"\"Show your favourite champs list.\"\"\"\n await self.character_list(ntr)\n\n @checks.hybrid.is_manager()\n @ext_lol_champ.command(name='list')\n async def ext_lol_champ_list(self, ctx: AluGuildContext):\n \"\"\"Show current list of fav champ.\"\"\"\n await self.character_list(ctx)\n\n # lol champ spoil ##################################\n\n @slh_lol.command(name='spoil')\n @app_commands.describe(spoil='`True` to enable spoiling with stats, `False` for disable')\n async def slh_lol_spoil(self, ntr: discord.Interaction[AluBot], spoil: bool):\n \"\"\"Turn on/off spoiling resulting stats for matches.\"\"\"\n await self.spoil(ntr, spoil)\n\n @checks.hybrid.is_manager()\n @ext_lol.command(name='spoil')\n async def ext_lol_spoil(self, ctx: AluGuildContext, spoil: bool):\n \"\"\"Turn on/off spoiling resulting stats for matches.\n It is \"on\" by default, so it can show what items players finished with and KDA.\n \"\"\"\n await self.spoil(ctx, spoil)\n\n # character setup\n\n async def get_character_data(self):\n return await champion.champion_keys_cache.data\n\n @slh_lol_champ.command(name='setup')\n async def slh_lol_champ_setup(self, ntr: discord.Interaction[AluBot]):\n \"\"\"Interactive setup to add/remove champions in/from your favourite list.\"\"\"\n await self.character_setup(ntr)\n\n @checks.hybrid.is_manager()\n @ext_lol_champ.command(name='setup')\n async def ext_lol_champ_setup(self, ctx: AluGuildContext):\n \"\"\"Interactive setup to add/remove champions in/from your favourite list.\"\"\"\n await self.character_setup(ctx)\n\n # meraki ##################################\n\n @commands.command(hidden=True)\n async def meraki(self, ctx: AluGuildContext):\n \"\"\"Show list of champions that are missing from Meraki JSON.\"\"\"\n champ_ids = await get_pyot_meraki_champ_diff_list()\n champ_str = [f'\\N{BLACK CIRCLE} {await champion.key_by_id(i)} - `{i}`' for i in champ_ids] or ['None missing']\n\n meraki_patch = await get_meraki_patch()\n\n e = discord.Embed(title='List of champs missing from Meraki JSON', colour=const.Colour.rspbrry())\n e.description = '\\n'.join(champ_str)\n e.add_field(\n name='Links',\n value=(\n f'• [GitHub](https://github.com/meraki-analytics/role-identification)\\n'\n f'• [Json](https://cdn.merakianalytics.com/riot/lol/resources/latest/en-US/championrates.json)'\n ),\n )\n e.add_field(name='Meraki last updated', value=f'Patch {meraki_patch}')\n await ctx.reply(embed=e)\n","repo_name":"Aluerie/AluBot","sub_path":"exts/fpc_notifs/lol/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":20408,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"77"} +{"seq_id":"30932785476","text":"import random\nimport logging\nimport enum\n\nLOGGER = logging.getLogger(__name__)\n\nclass Direction(enum.Enum):\n \"\"\"Stellt die Bewegungsrichtungen dar\"\"\"\n UP = (0,-1)\n RIGHT = (1,0)\n DOWN = (0,1)\n LEFT = (-1,0)\n\n def __init__(self, dir_x, dir_y):\n self.dir_x = dir_x\n self.dir_y = dir_y\n\n @classmethod\n def parse(cls, text):\n return Direction[text.upper()]\n\nclass GameState(): \n WIDTH = 4\n HEIGHT = 4\n\n def __init__(self):\n # Erstelle das leere 2D-Array\n self.game_grid = [[None for y in range(self.HEIGHT)] for x in range(self.WIDTH)]\n \n # Füge 2 Zahlen ein\n self.spawn_nr(amount=2)\n\n def handle_key(self, dir):\n dir = Direction.parse(dir)\n LOGGER.info('moving in direction: {}'.format(dir))\n moved_any = False\n dir_x, dir_y = dir.dir_x, dir.dir_y\n x_iter = range(0, self.WIDTH, 1) if dir_x < 0 else range(self.WIDTH-1, -1, -1)\n y_iter = range(0, self.HEIGHT, 1) if dir_y < 0 else range(self.WIDTH-1, -1, -1)\n for x in x_iter:\n for y in y_iter:\n nr = self.game_grid[x][y]\n if nr is not None:\n moved = self.move_in_dir(x, y, dir)\n LOGGER.info('({},{}) moved: {}'.format(x,y, moved))\n moved_any = moved_any or moved \n if moved_any:\n self.spawn_nr()\n return len(set(self.free_fields())) == 0\n\n def move_in_dir(self, x, y, dir):\n \"\"\"\n Bewegt Zahl so weit wie möglich in Richtung. Gibt True zurück,\n wenn eine Bewegung stattfand\n \"\"\"\n nr = self.game_grid[x][y]\n if nr is not None:\n # Postion zu der sich Nummer bewegt\n target_x, target_y = self.get_target_pos(nr, x, y, dir)\n LOGGER.info('moving {} from {},{} to {},{}'.format(nr, x, y, target_x, target_y))\n # lösche alte Nummer\n self.game_grid[x][y] = None\n\n # Schreibe Nummer an neue Postion\n target_nr = self.game_grid[target_x][target_y]\n self.game_grid[target_x][target_y] = 2 * nr if target_nr is not None else nr\n return target_x != x or target_y != y\n return False\n\n\n def get_target_pos(self, nr, x, y, dir):\n \"\"\"Berechne die Postion in die sich die Nummer bewegen kann\"\"\"\n\n # Addire dir_x und dir_y um 1 Schritt in Richtung zu gehen\n dir_x, dir_y = dir.dir_x, dir.dir_y\n \n # Position die als nächstes überprüft wird\n next_x = x + dir_x\n next_y = y + dir_y\n \n # Solange nächste Postion noch im Feld ist\n while next_x >= 0 and next_x < GameState.WIDTH and next_y >= 0 and next_y < GameState.HEIGHT:\n if self.game_grid[next_x][next_y] is not None:\n # wenn bei nächster Position gleiche nr ist vereinige\n if nr == self.game_grid[next_x][next_y]:\n return next_x, next_y\n # wenn andere nummer gehe zur letzten postion\n else:\n return x, y\n # wenn leer überprüfe nächstes Feld\n x, y = next_x, next_y\n next_x += dir_x \n next_y += dir_y\n return x, y\n\n def spawn_nr(self, amount=1):\n spawns = random.sample(set(self.free_fields()), amount)\n LOGGER.info('spawning nrs at: {}'.format(spawns))\n for x, y in spawns:\n self.game_grid[x][y] = 2\n\n def free_fields(self):\n for x, y in self.all_positions():\n if self.game_grid[x][y] is None:\n yield (x,y)\n\n def all_positions(self):\n for x, row in enumerate(self.game_grid):\n for y, _ in enumerate(row):\n yield (x,y) \n\n \n\n \n\n \n","repo_name":"hwse/game2048","sub_path":"game_state.py","file_name":"game_state.py","file_ext":"py","file_size_in_byte":3786,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"8015973391","text":"from turtle import Turtle, Screen\nfrom random import randint\n\nwidth: int = 500\nheight: int = 400\ncolors: list[str] = [\"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"purple\"]\nall_turtles: list[Turtle] = []\nscreen = Screen()\nscreen.setup(width, height)\n\nuser_bet = screen.textinput(title=\"Make your bet\", prompt=f\"Which turtle will win the race? Enter a color: {colors} \")\n\n\ndef starting_position(offset: int):\n x_postion: float = -(width / 2 - 20)\n y_postion: float = (height / 2) - (offset * 55)\n return (x_postion, y_postion)\n\n\ncount = 1\nfor color in colors:\n turtle = Turtle(shape=\"turtle\")\n turtle.color(color)\n turtle.penup()\n turtle.goto(starting_position(count))\n count += 1\n all_turtles.append(turtle)\n\n\nif user_bet:\n is_race_on: bool = True\nelse:\n exit()\n\nwhile is_race_on:\n for turtle in all_turtles:\n turtle.forward(randint(0, 5))\n if turtle.xcor() == (width / 2 - 60):\n is_race_on = False\n if turtle.pencolor() == user_bet:\n print(f\"You've won! The {turtle.pencolor()} turtle is the winning color\")\n else:\n print(f\"You've lost. The {turtle.pencolor()} turtle is the winning color\")\n\nscreen.exitonclick()\n","repo_name":"mleclerc00/100-days-of-code-python","sub_path":"day-19/day-19-turtle-race/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"23921507659","text":"import math\nfrom queue import PriorityQueue\n\nwith open(\"problems.txt\") as f:\n cases = int(f.readline())\n case1 = list(map(int, f.readline().split()))\n case2 = list(map(int, f.readline().split()))\n case3 = list(map(int, f.readline().split()))\n case4 = list(map(int, f.readline().split()))\n\nprint(cases, case1, case2, case3)\nc1 = len(case1)\nc2 = len(case2)\nc3 = len(case3)\nc4 = len(case4)\nprint(\"The dimensions of the each example respectively is : \", c1, c2, c3, c4)\n\ndef check_inversion(row):\n count=0\n size = int(math.sqrt(len(row)))\n print(size)\n row_size = size*size\n for i in range(row_size):\n for j in range(i+1,row_size):\n if(row[i]>row[j] and row[j] is not 0):\n count=count+1\n print(count)\n if((count%2==0 and row_size%2==1) or (count%2==1 and row_size%2==0)):\n return True\n else:\n return False\n\nwith open(\"problems.txt\", \"r\") as file:\n n = int(file.readline().strip())\n #print(n)\n for i in range(n):\n row=list(map(int,file.readline().split()))\n #print(row)\n flag=check_inversion(row)\n if(flag):\n print(\"solvable\")\n else:\n print(\"not solvable\")\n\n\n ## Task 01 Done Task 2 Started\n\nclass Node:\n def __init__(self, initial_state, cost, action, heuristic, zeroindex, parent):\n self.initial_state = initial_state # this is the list of the input\n self.parent = parent\n self.action = action # UP , DOWN , LEFT , RIGHT\n self.cost = cost\n self.zeroindex = zeroindex\n self.heuristic = heuristic\n self.priority = cost + heuristic\n\n\ndef Goal_Test(state, goal):\n if state == goal:\n return True\n else:\n return False\n\n\nclass Problem: # defining a well define problem\n def __init__(self, ini_list, goal_state):\n self.ini_list = ini_list\n self.goal_state = goal_state\n\n\ndef heuristic(state,\n goal_state): # this function will give us the value that show how much our goal look alike our current state\n count = 0\n for i in range(len(state)):\n if state[i] != goal_state[i]:\n count += 1\n return count\n\n\ndef swap(lst, index1, index2):\n # Create a copy of the original list\n new_lst = lst.copy()\n\n # Swap the values at the specified indices\n new_lst[index1], new_lst[index2] = new_lst[index2], new_lst[index1]\n\n return new_lst\n\n\ndef check(state1, state2):\n for i in range(len(state1)):\n if state1[i] != state2[i]:\n return False\n return True\n\n\ndef solution(node):\n actions = []\n while node.parent is not None:\n actions.append(node.action)\n node = node.parent\n\n actions.reverse()\n return actions\n\n\ndef A_Star(p):\n length = len(p.ini_list)\n\n dim = math.sqrt(length) # this will show us the dimension of the 2d array from row major\n frontier = PriorityQueue()\n\n h = heuristic(p.ini_list, p.goal_state)\n if h == 0:\n print(\" we are already at the goal state \\n \")\n return\n zindex = int(p.ini_list.index(0))\n n = Node(p.ini_list, 0, None, h, zindex, None)\n frontier.put((n.priority, n))\n explored = [] # we only put state in it\n action_list = []\n while not frontier.empty():\n priority, n = frontier.get() # we get node, on the base of the priority\n\n flag = Goal_Test(n.initial_state, p.goal_state)\n if flag:\n print(\" Goal Found \\n \")\n action_list = solution(n)\n return\n explored.append(n.initial_state)\n val = 0\n index = int(p.ini_list.index(val))\n row = index // dim\n col = index % dim\n if row - 1 >= 0:\n # we can move upward action name is 1\n ind = int(row - dim) # this is the index at where we have to put zero it's not a zero index\n # create a separate state for this\n # swapping the values with the index\n # initial_state, cost, action, heuristic, zeroindex, parent):\n\n nlist = swap(n.initial_state, int(n.zeroindex), ind)\n h = heuristic(nlist, p.goal_state)\n index = int(nlist.index(0))\n child = Node(nlist, n.cost + 1, \"UP\", h, index,\n n) # the priority value will be set in the constructor on the bases of cost and heuristic value\n\n found = False\n matched_node = None\n for existing_node in frontier.queue:\n if child.initial_state == existing_node.initial_state:\n found = True\n matched_node = existing_node\n break\n\n if not found:\n frontier.put((child.priority, child))\n else:\n if child.priority < matched_node.priority:\n frontier.queue.remove(matched_node)\n frontier.put((child.priority, child))\n else:\n pass # do nothing\n\n if row + 1 < dim:\n # we can move to down we name this action as 10\n ind = int(row + dim) # ye wo index hai jis k sath hme swapping krni hai\n\n nlist = swap(n.initial_state, int(n.zeroindex), ind)\n h = heuristic(nlist, p.goal_state)\n index = int(nlist.index(0))\n child = Node(nlist, n.cost + 1, \"DOWN\", h, index, n)\n found = False\n matched_node = None\n for existing_node in frontier.queue:\n if child.initial_state == existing_node[1].initial_state:\n found = True\n matched_node = existing_node\n break\n\n if not found:\n frontier.put((child.priority, child))\n else:\n if child.priority < matched_node.priority:\n frontier.queue.remove(matched_node)\n frontier.put((child.priority, child))\n else:\n pass # do nothing\n\n if col + 1 < dim:\n # move to the right we name this action as a 2\n ind = int(col + 1) # ye wo index hai jis k sath hme swapping krni hai\n\n nlist = swap(n.initial_state, int(n.zeroindex), ind)\n h = heuristic(nlist, p.goal_state)\n index = int(nlist.index(0))\n child = Node(nlist, n.cost + 1, \"RIGHT\", h, index, n)\n\n found = False\n matched_node = None\n for existing_node in frontier.queue:\n if child.initial_state == existing_node[1].initial_state:\n found = True\n matched_node = existing_node\n break\n\n if not found:\n frontier.put((child.priority, child))\n else:\n if child.priority < matched_node.priority:\n frontier.queue.remove(matched_node)\n frontier.put((child.priority, child))\n else:\n pass # do nothing\n\n if col - 1 >= 0:\n # move to the Left and we name this action as 20\n ind = int(col - 1)\n nlist = swap(n.initial_state, int(n.zeroindex), ind)\n h = heuristic(nlist, p.goal_state)\n index = int(nlist.index(0))\n child = Node(nlist, n.cost + 1, \"LEFT\", h, index, n)\n\n found = False\n matched_node = None\n for existing_node in frontier.queue:\n if child.initial_state == existing_node[1].initial_state:\n found = True\n matched_node = existing_node\n break\n\n if not found:\n frontier.put((child.priority, child))\n else:\n if child.priority < matched_node.priority:\n frontier.queue.remove(matched_node)\n frontier.put((child.priority, child))\n else:\n pass # do nothing\n\n # if child not in frontier_q and child.index not in explored_q:\n # if p.GOAL_TEST(goal1):\n # print(\"Our Goal Found \\n \")\n # # sol_list = solution(child)\n # # sol_list.append(child.index)\n # action_list = action(child)\n # action_list.reverse()\n #\n # print(\"\\t or In the form of Array are : \")\n # action_list.remove(0)\n # print(\"\\t \", action_list)\n # print()\n # return True\n # else:\n # frontier_q.append(child)\n return n\n\n\n### =============## Main Function======================= ##\n\ngoal = [1, 2, 3, 4, 5, 6, 7, 8, 0]\np = Problem(case2, goal)\nA_Star(p)\n","repo_name":"QANBAR-KHAKI/ARTIFICIAL-INTELLIGENCE-ALGOS","sub_path":"bcsf20a007_AI Lab Ass A star.py","file_name":"bcsf20a007_AI Lab Ass A star.py","file_ext":"py","file_size_in_byte":8771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"2118075691","text":"import numpy as np\nimport pandas as pd\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nimport gensim\n\nimport pickle\nimport os\nfrom collections import Counter\n\n\n# tokenize and anonymize one tweet\ndef token_tweet(tweet):\n '''The data has been tokenized during building process\n No need for more process\n '''\n pass\n\n\ndef anonymize_data(idir, odir):\n '''Anonymize dataset\n \n idir: input directory\n odir: output directory\n '''\n # output anonymized dataset\n opath_utable = odir + 'utable.tsv'\n opath_corpus = odir + 'corpus.tsv'\n hashtable = {'user': dict(), 'corpus': dict()}\n\n if os.path.exists(opath_utable) and os.path.exists(opath_corpus):\n # return the existing directory\n return odir\n else:\n # create the directory if not exist\n if not os.path.exists(odir):\n os.mkdir(odir)\n\n # user table\n with open(idir+'utable.tsv') as dfile:\n with open(opath_utable, 'w') as wfile:\n wfile.write(dfile.readline())\n for line in dfile:\n line = line.strip().split('\\t')\n hash_uid = str(hash(line[0]))\n hashtable['user'][line[0][:]] = hash_uid\n line[0] = hash_uid\n\n wfile.write('\\t'.join(line)+'\\n')\n \n # corpus\n with open(idir + 'corpus.tsv') as dfile:\n with open(opath_corpus, 'w') as wfile:\n wfile.write(dfile.readline())\n for line in dfile:\n line = line.strip().split('\\t')\n hash_did = str(hash(line[0]))\n hashtable['corpus'][line[0][:]] = hash_did\n line[0] = hash_did\n line[1] = hashtable['user'][line[1]]\n wfile.write('\\t'.join(line)+'\\n')\n\n # pickle to save hash table, save to the raw dir\n with open(idir + 'hash_table.tsv', 'wb') as wfile:\n pickle.dump(hashtable, wfile)\n\n\ndef encode_data(idir, odir):\n '''Encode attribute and label of dataset\n \n idir: input directory\n odir: output directory\n '''\n # output encoded utable and corpus\n opath_utable = odir + 'utable.tsv'\n opath_corpus = odir + 'corpus.tsv'\n\n if os.path.exists(opath_utable) and os.path.exists(opath_corpus):\n # return the existing directory\n return odir\n else:\n # create the directory if not exist\n if not os.path.exists(odir):\n os.mkdir(odir)\n\n # load utable: know how to binarize attributes\n utable = pd.read_csv(\n idir+'utable.tsv', sep='\\t', na_values='x')\n # find the median age\n median = utable.age.median()\n # find the country\n country = Counter(\n utable[utable.country.notnull()].country\n ).most_common(1)[0][0]\n \n # load utable: encode the table\n utable = dict()\n with open(idir+'utable.tsv') as dfile:\n cols = dfile.readline()\n for line in dfile:\n line = line.strip().split('\\t')\n# print(len(line))\n\n # encode gender\n if line[1] != 'x':\n if line[1] == 'female':\n line[1] = '1'\n else:\n line[1] = '0'\n\n # encode age\n if line[2] != 'x':\n if float(line[2]) > median:\n line[2] = '0'\n else:\n line[2] = '1'\n\n # encode country\n if line[5] != 'x':\n if line[5] == country:\n line[5] = '1'\n else:\n line[5] = '0'\n \n # encode race\n if line[6] != 'x':\n if line[6] == 'white':\n line[6] = '0'\n else:\n line[6] = '1'\n\n utable[line[0]] = line[1:]\n \n # write user table to encoded file\n with open(opath_utable, 'w') as wfile:\n wfile.write(cols)\n for uid in utable:\n wfile.write(uid+'\\t'+'\\t'.join(utable[uid])+'\\n')\n\n # load the corpus\n with open(idir+'corpus.tsv') as dfile:\n with open(opath_corpus, 'w') as wfile:\n wfile.write(dfile.readline())\n for line in dfile:\n line = line.strip().split('\\t')\n # attributes\n line[4:-1] = utable[line[1]]\n # labels\n if line[-1] in ['0', 'no', 'neither', 'normal']:\n line[-1] = '0'\n else:\n line[-1] = '1'\n wfile.write('\\t'.join(line)+'\\n')\n\n\n# build tokenizer\ndef build_tok(idir, odir, name):\n doc_idx = 2 # column of document\n \n if not os.path.exists(odir):\n os.mkdir(odir)\n \n opath = odir + name + '.tkn'\n if os.path.exists(opath):\n return pickle.load(open(opath, 'rb'))\n else:\n # load corpus\n corpus = []\n tkn = Tokenizer(num_words=15000)\n\n with open(idir+'corpus.tsv') as dfile:\n dfile.readline() # skip column names\n for line in dfile:\n corpus.append(\n line.strip().split('\\t')[doc_idx]\n )\n tkn.fit_on_texts(corpus)\n\n with open(opath, 'wb') as wfile:\n pickle.dump(tkn, wfile)\n return tkn\n\n\n# split data\ndef split_data(idir, odir):\n '''Split dataset into \n 70/15/15: train/valid/test\n \n idir: input directory\n odir: output directory\n '''\n datap = idir + 'corpus.tsv'\n\n if not os.path.exists(odir):\n os.mkdir(odir)\n\n trainp = odir + 'train.tsv'\n validp = odir + 'valid.tsv'\n testp = odir + 'test.tsv'\n writers = [\n open(trainp, 'w'),\n open(validp, 'w'),\n open(testp, 'w'),\n ]\n\n # load data\n corpus = []\n with open(datap) as dfile:\n cols = dfile.readline()\n for line in dfile:\n corpus.append(line)\n \n indices = list(range(len(corpus)))\n np.random.shuffle(indices)\n \n # train\n with open(trainp, 'w') as wfile:\n wfile.write(cols)\n for idx in range(int(len(indices)*.7)):\n wfile.write(corpus[indices[idx]])\n\n # valid\n with open(validp, 'w') as wfile:\n wfile.write(cols)\n for idx in range(int(len(indices)*.7), int(len(indices)*.85)):\n wfile.write(corpus[indices[idx]])\n\n # test\n with open(testp, 'w') as wfile:\n wfile.write(cols)\n for idx in range(int(len(indices)*.85), len(indices)):\n wfile.write(corpus[indices[idx]])\n\n\ndef build_indices(split_dir, tok, indices_dir, max_len=40):\n '''Convert the raw text into indices\n '''\n files = [\n 'train.tsv', 'valid.tsv', 'test.tsv'\n ]\n doc_idx = 2\n if not os.path.exists(indices_dir):\n os.mkdir(indices_dir)\n \n for filen in files:\n filep = split_dir + filen # input\n wfile = open(indices_dir + filen, 'w') # output\n\n with open(filep) as dfile:\n wfile.write(dfile.readline())\n for line in dfile:\n line = line.strip().split('\\t')\n line[doc_idx] = ' '.join(\n map(str, \n pad_sequences(\n tok.texts_to_sequences([line[doc_idx]]),\n maxlen=max_len\n )[0]\n )\n )\n wfile.write('\\t'.join(line)+'\\n')\n wfile.flush()\n wfile.close()\n\n\ndef build_wt(lang, tkn, emb_path, opt):\n '''Create embedding weights\n \n lang: The langugage name\n tkn: tokenizer\n emb_path: embedding file path\n opt: output path of weight file\n '''\n embed_len = len(tkn.word_index)\n if embed_len > tkn.num_words:\n embed_len = tkn.num_words\n \n # obtain the size of embedding\n if emb_path.endswith('.bin'):\n embeds = gensim.models.KeyedVectors.load_word2vec_format(\n emb_path, binary=True, unicode_errors='ignore'\n )\n for pair in zip(embeds.wv.index2word, embeds.wv.syn0):\n size = len([float(item) for item in pair[1]])\n break\n else:\n with open(emb_path) as dfile:\n for line in dfile:\n line = line.strip().split()\n if line[0] in tkn.word_index:\n size = len([float(item) for item in line[1:]])\n break\n\n emb_matrix = np.zeros((embed_len + 1, size))\n if emb_path.endswith('.bin'):\n embeds = gensim.models.KeyedVectors.load_word2vec_format(\n emb_path, binary=True, unicode_errors='ignore'\n )\n for pair in zip(embeds.wv.index2word, embeds.wv.syn0):\n if pair[0] in tkn.word_index and \\\n tkn.word_index[pair[0]] < tkn.num_words:\n emb_matrix[tkn.word_index[pair[0]]] = [\n float(item) for item in pair[1]\n ]\n else:\n with open(emb_path) as dfile:\n for line in dfile:\n line = line.strip().split()\n if line[0] in tkn.word_index and \\\n tkn.word_index[line[0]] < tkn.num_words:\n emb_matrix[tkn.word_index[line[0]]] = [\n float(item) for item in line[1:]\n ]\n np.save(opt, emb_matrix)\n\n\nif __name__ == '__main__':\n dir_list = [\n 'English', 'Italian', 'Polish',\n 'Portuguese', 'Spanish',\n ]\n \n # create resources folders\n for dirp in ['./resources/tokenizer/', './resources/embedding/', './resources/weight/']:\n if not os.path.exists(dirp):\n os.mkdir(dirp)\n \n for dirp in dir_list:\n raw_dir = './data/raw/'+dirp+'/'\n anonymize_dir = './data/anonymize/'+dirp+'/'\n encode_dir = './data/encode/'+dirp+'/'\n split_dir = './data/split/'+dirp+'/'\n indices_dir = './data/indices/'+dirp+'/'\n tok_dir = './resources/tokenizer/'\n emb_dir = './resources/embedding/'\n wt_dir = './resources/weight/'\n\n # anonymize data, this is only for author usage\n# print('anonymize data: ', dirp)\n# anonymize_data(\n# raw_dir, \n# anonymize_dir\n# )\n\n # encode data\n print('encode data: ', dirp)\n encode_data(\n anonymize_dir, \n encode_dir\n )\n\n # build tokenizer\n print('build tokenizer: ', dirp)\n tok = build_tok(encode_dir, tok_dir, dirp)\n\n # split data\n print('split data: ', dirp)\n split_data(\n encode_dir,\n split_dir\n )\n\n # encode into indices\n print('data to indices: ', dirp)\n build_indices(\n split_dir, tok, indices_dir\n )\n\n # build weights\n opt = wt_dir + dirp\n emb_path = emb_dir + dirp\n\n if os.path.exists(emb_path + '.vec'):\n build_wt(dirp, tok, emb_path + '.vec', opt)\n else:\n build_wt(dirp, tok, emb_path + '.bin', opt)\n","repo_name":"xiaoleihuang/Multilingual_Fairness_LREC","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":11399,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"77"} +{"seq_id":"24001196168","text":"import re\nimport smc.bibencodings\nimport json\nimport msgpack\nfrom .utils import chunkify\nfrom .mir import MIR, Field, SubField\n\n\nclass MARCSerializer(object):\n \"\"\"\n \"\"\"\n\n binary_mode = False\n\n def load(self, buffer):\n raise NotImplementedError()\n\n def _deserialize(self, callable, *args, **kwargs):\n for leader, *fields in callable(*args, **kwargs):\n yield MIR(leader, fields)\n\n def dump(self, buffer, mirs):\n raise NotImplementedError()\n\n\nclass ISO2709(MARCSerializer):\n \"\"\" ISO2709 format\n \"\"\"\n\n binary_mode = True\n\n def __init__(self, end_of_record=b'\\x1d', end_of_field=b'\\x1e',\n end_of_subfield=b'\\x1f', chunk_size=1024, encoding='mab2'):\n self.chunk_size = chunk_size\n self.encoding = encoding\n self.end_of_record = self._decode(end_of_record)\n self.end_of_field = self._decode(end_of_field)\n self.end_of_subfield = self._decode(end_of_subfield)\n self.subfield_parser = re.compile(self.end_of_subfield + '(.)')\n\n def _decode(self, value):\n return value.decode(self.encoding)\n\n def _encode(self, value):\n return value.encode(self.encoding)\n\n def _read(self, buffer):\n return self._decode(buffer.read(self.chunk_size))\n\n def _write(self, buffer, value):\n buffer.write(self._encode(value))\n\n def load(self, buffer):\n chunk = self._read(buffer)\n while chunk:\n if self.end_of_record in chunk:\n record, _, chunk = chunk.partition(self.end_of_record)\n leader, fields = self._parse(record)\n yield MIR(leader, fields)\n if not chunk:\n chunk = self._read(buffer)\n else:\n chunk += self._read(buffer)\n\n def _parse(self, record):\n head, *raw_fields = record[:-1].split(self.end_of_field)\n\n head_length = len(head)\n if head_length < 24 or head_length % 12 != 0:\n raise BadHeaderException(head)\n\n leader = head[:24]\n\n fields = []\n for name, value in zip(chunkify(head[24:], 3, slicing=12), raw_fields):\n chunks = self.subfield_parser.split(value)\n if len(chunks) == 1:\n field = Field(name, value=value)\n else:\n indicators = list(chunks.pop(0))\n subfields = [SubField(name, value) for name, value in\n chunkify(chunks, 2)]\n field = Field(name, indicators=indicators, subfields=subfields)\n fields.append(field)\n\n return leader, fields\n \n def dump(self, buffer, mirs):\n field_format = lambda field: '{0.tag}{0.value}'.format(field)\n for mir in mirs:\n header = self._format_header(mir)\n self._write(buffer, header)\n self._write(buffer, self.end_of_field)\n for field in mir.fields:\n if field.is_control():\n self._write(buffer, field.value)\n else:\n self._write(buffer, ''.join(field.indicators))\n self._write(buffer, self.end_of_subfield)\n subfield = self.end_of_subfield.join(\n field_format(subfield) for subfield in field.subfields)\n self._write(buffer, subfield)\n self._write(buffer, self.end_of_field)\n self._write(buffer, self.end_of_record)\n\n def _format_header(self, mir):\n length_format = lambda field_length: '{:0<4}'.format(field_length)\n address_format = lambda position: '{:0<5}'.format(position)\n position = 0 \n header = mir.leader\n\n for field in mir.fields:\n header += field.tag\n if field.is_control():\n field_length = len(field.value) + 1\n else:\n lindicators = len(field.indicators)\n lsubfields = sum([len(sub.tag) + len(sub.value) for sub in\n field.subfields])\n field_length = lindicators + lsubfields + 1\n header += length_format(field_length)\n header += address_format(position)\n position += field_length\n\n return header\n\n\nclass MsgPack(MARCSerializer):\n \"\"\" msgpack format\n \"\"\"\n\n binary_mode = True\n \n def load(self, buffer):\n return self._deserialize(msgpack.Unpacker, buffer, encoding='utf-8')\n\n def dump(self, buffer, mirs):\n for mir in mirs:\n buffer.write(msgpack.packb(mir, use_bin_type=True))\n\n\nclass Json(MARCSerializer):\n \"\"\" json format\n \"\"\"\n\n def __init__(self, indent=None):\n self.indent = indent\n\n def load(self, buffer):\n return self._deserialize(json.load, buffer)\n\n def dump(self, buffer, mirs):\n mirs = list(mirs)\n for chunk in json.JSONEncoder(indent=self.indent).iterencode(mirs):\n buffer.write(chunk)\n\n\nclass BadHeaderException(Exception):\n \"\"\" Header does not match the MARC standard\n \"\"\"\n\n def __init__(self, header, *args, **kwargs):\n super(BadHeaderException, self).__init__(*args, **kwargs)\n self.header = header\n\n def __str__(self):\n return '{} is not a valid header'.format(self.header)\n\n\nclass UnrecognizedFormat(Exception):\n \"\"\" The serializing format is not handled by pyromarc\n \"\"\"\n\n def __init__(self, serializer, *args, **kwargs):\n super(UnrecognizedFormat, self).__init__(*args, **kwargs)\n self.serializer = repr(serializer)\n\n def __str__(self):\n return '{} is not a valid format.'.format(self.serializer)\n\n\nclass BadIOMode(Exception):\n \"\"\" File handler has a bad opening mode\n \"\"\"\n\n def __init__(self, serializer, open_mode, *args, **kwargs):\n super(BadIOMode, self).__init__(*args, **kwargs)\n self.serializer = serializer.__class__.__name__\n self.open_mode = open_mode\n\n def __str__(self):\n return 'Bad opening mode {0.open_mode} for {0.serializer}'.format(self)\n","repo_name":"agrausem/pyromarc","sub_path":"pyromarc/format.py","file_name":"format.py","file_ext":"py","file_size_in_byte":6016,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"77"} +{"seq_id":"10453067588","text":"import json\nimport os\nimport tornado.web\nfrom kaltura_service import KalturaService\nimport uuid\n\nclass MediaHandler(tornado.web.RequestHandler):\n\n CHANNEL_TAG_MARKER = \"_channel\"\n\n def post(self):\n service = KalturaService.get_instance()\n result = {}\n for name, files in self.request.files.items():\n for datafile in files:\n try:\n self.ensure('/tmp')\n name = 'tmp/file_{0}'.format(uuid.uuid1().hex)\n with open(name, 'wb') as f:\n f.write(datafile[\"body\"])\n media_entry = service.upload(name, self.get_argument(\"name\"), \"%s:%s\" % (MediaHandler.CHANNEL_TAG_MARKER, self.get_argument(\"channel\")))\n result[name] = { 'id' : media_entry.id }\n os.remove(name)\n except Exception as e:\n result[name] = { 'error' : e.message }\n self.write(json.dumps(result))\n\n def ensure(self, path):\n if not os.path.exists('tmp'):\n os.mkdir('tmp')\n","repo_name":"rgan/media_upload","sub_path":"handlers/media_handler.py","file_name":"media_handler.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"43260883255","text":"# 8-12\ndef sandwich(*topping):\n print(topping)\n\nsandwich('a')\nsandwich('b', 'c', 'd')\nsandwich('e', 'f', 'g')\n\n# 8-13\n\n\ndef build_profile(first, last, **user_info):\n profile = {}\n profile['first_name'] = first\n profile['last_name'] = last\n for key, value in user_info.items():\n profile[key] = value\n return profile\n\nuser_profile = build_profile(\n 'mt', 'c', location='chongqing', field='IT')\nprint(user_profile)\n\n# 8-14\n\n\ndef make_car(manufacturer, model, **car_info):\n profile = {}\n profile['manufacturer'] = manufacturer\n profile['model'] = model\n for key, value in car_info.items():\n profile[key] = value\n print(profile)\n\ncar = make_car('sabaru', 'outback', color='blue', tow_package=True)\n","repo_name":"gamecmt/pcc","sub_path":"chapter8/sandwich.py","file_name":"sandwich.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"28762224480","text":"'''\nInspired by JetsonHacks's video about Jetson RACECAR Motor ESC Control:\nhttps://www.youtube.com/watch?v=Mp-aSmxGAE8, last visited 26.01.2022\n'''\n\n\n\nfrom tkinter.constants import END\nimport board\nimport busio\nimport adafruit_pca9685\nimport tkinter as tk\nimport re\n\n\ndef decrement():\n print('Decrement')\n global dutyCycle\n dutyCycle = (dutyCycle - 1) if dutyCycle > 0 else 0\n setDutyCycle(dutyCycle)\n\ndef neutral():\n print('Reset')\n global dutyCycle\n dutyCycle = 0\n setDutyCycle(dutyCycle)\n\ndef increment():\n print('Increment')\n global dutyCycle\n dutyCycle = dutyCycle + 1\n setDutyCycle(dutyCycle)\n\n\ndef setDutyCycle(cycle):\n pca.channels[channel].duty_cycle = cycle\n setText(str(cycle))\n\ndef selectElement(selection):\n global channel\n print(selection)\n channel = SELECTIONLIST.index(selection)\n print(channel)\n\ndef setText(text):\n dutyCycleInput.delete(0, END)\n dutyCycleInput.insert(0, text)\n\ndef onTextChange(text):\n global dutyCycle\n\n if text.get() != '' and re.match('^[\\d]{4}$', text.get()):\n print(text.get())\n dutyCycle = int(text.get(), base=10)\n setDutyCycle(dutyCycle) \n\ni2c = busio.I2C(board.SCL, board.SDA)\npca = adafruit_pca9685.PCA9685(i2c_bus = i2c, address = 0x40)\npca.frequency = 50\ndutyCycle = 0\nchannel = 0\n\n\nroot = tk.Tk()\nroot.title('RC Car Configurator')\n\ncanvas = tk.Canvas(root, width = 620, height = 480)\ncanvas.pack()\n\nSELECTIONLIST = [\n 'ESC THROTTLE',\n 'STEERING'\n]\n\nselectRelX = 0.35\nselectRelY = 0.05\n\nvariable = tk.StringVar(root)\nvariable.set(SELECTIONLIST[channel])\n\nselect = tk.OptionMenu(root, variable, *SELECTIONLIST, command=selectElement)\nselect.config(width = 20, font = ('Helvetica', 12))\nselect.place(relx = selectRelX, rely = selectRelY)\n\nbuttonReverse = tk.Button(root, text = \"Decrement\", command=decrement)\nbuttonReset = tk.Button(root, text = \"Reset\", command=neutral)\nbuttonForward = tk.Button(root, text = \"Increment\", command=increment)\n\nbuttonRelX = 0.1\nbuttonRelY = selectRelY + 0.15\n\nbuttonReverse.place(relx = buttonRelX, rely = buttonRelY)\nbuttonReset.place(relx = buttonRelX + 1/3, rely = buttonRelY)\nbuttonForward.place(relx = buttonRelX + 2/3, rely = buttonRelY)\n\nbuttonRelX = 0.1\nbuttonRelY = 0.15\n\nsv = tk.StringVar()\nsv.trace(\"w\", lambda name, index, mode, sv = sv: onTextChange(sv))\n\ndutyCycleLabel = tk.Label(root, width = 20, text = 'Duty Cycle')\ndutyCycleInput = tk.Entry(root, width = 20, validate = 'key', textvariable= sv)\n\ndutyCycleRelX = 0.37\ndutyCycleRelY = buttonRelY + 0.30\n\ndutyCycleLabel.place(relx = dutyCycleRelX, rely = dutyCycleRelY)\ndutyCycleInput.place(relx = dutyCycleRelX, rely = dutyCycleRelY + 0.05)\nsetText(dutyCycle)\nsetDutyCycle(dutyCycle)\n\n\nroot.mainloop()\n\n","repo_name":"Tr4in/RC-Car-Configurator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"69995499770","text":"import os\n\nPRODUCT_NAME = 'Product name'\nPRODUCT_DESCRIPTION = 'This is a description for your product.'\nCOMPANY = 'Company Inc.'\n\nPROJECT_DIR = os.path.abspath(os.path.dirname('__file__'))\nURL = 'http://127.0.0.1:8000'\n\npath = lambda *args: os.path.join(PROJECT_DIR, *args)\n\nDEV = True\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nADMINS = (\n ('admin', 'mail@company.com'),\n)\n\nMANAGERS = ADMINS\n\n\nAUTH_PROFILE_MODULE = 'auth.UserProfile'\n\nLOGIN_REDIRECT_URL = '/home/'\nLOGIN_URL = '/'\n\n# Twitter keys\nTWITTERAUTH_KEY = ''\nTWITTERAUTH_SECRET = ''\n\n# Facebook keys\nAPP_ID_FACEBOOK = ''\nSECRET_KEY_FACEBOOK = ''\n\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': path('db.sqlite'),\n 'USER': '',\n 'PASSWORD': '',\n 'HOST': '',\n 'PORT': '',\n }\n}\n\nTIME_ZONE = 'America/Chicago'\n\nLANGUAGE_CODE = 'en'\n\nSITE_ID = 1\n\nUSE_I18N = False\n\nUSE_L10N = False\n\nMEDIA_ROOT = path('media')\n\nMEDIA_URL = URL+'/medios'\n\nADMIN_MEDIA_PREFIX = '/media/'\n\nSECRET_KEY = 'iiybage0^@igkdua+wxk%+jcm*e_po2$8n9$-5h2!2^1#6*3s+'\n\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n)\n\nROOT_URLCONF = 'urls'\n\nTEMPLATE_DIRS = (\n path('auth','templates'),\n path('main','templates'),\n)\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.admin',\n 'auth',\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.core.context_processors.request',\n 'django.core.context_processors.auth',\n 'django.core.context_processors.media',\n 'django.contrib.messages.context_processors.messages',\n 'django.core.context_processors.csrf',\n 'context_processors.default',\n)\n","repo_name":"julsdelatierra/django-boilerplate","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"77"} +{"seq_id":"35222657599","text":"\"\"\"\nThis module contains the Environment of the Robot.\n\nImplemented by Alexandra Gianzina\n\"\"\"\nfrom typing import List, Optional, Tuple\nimport numpy as np\nimport Geometry\n\n\nclass Robot:\n \"\"\"\n Robot class.\n\n Args:\n position: position of the robot as [x, y, rotation]\n radius: radius of the circular robot\n maximum_value_sensor: maximum distance that can be sensed by the robot\n acceleration: acceleration of the robot, used to change its velocity\n sensors: list of sensors. The sensors are define with the counter-clockwise\n angle (in radiants) w.r.t. the foward direction of the robot.\n E.g., [0, pi/2, pi, 3pi/2] represent 4 sensors: one on the front,\n one on the left, one on the right, and one on the back\n trace: keep history of positions\n trace_size: maximum size of the trace history\n map_: map of the environment to estimate the position given the landmarks\n rng: random number generator\n noise: Gaussian noise of the position sensors. Given as tuple (mu, Sigma)\n \"\"\"\n\n def __init__(\n self,\n position: np.array,\n radius: int,\n maximum_value_sensor: float,\n acceleration: float,\n sensors: List[float],\n trace: Optional[bool] = False,\n trace_size: Optional[int] = 0,\n map_: Optional[\"Environment\"] = None,\n rng=None,\n noise: Tuple[np.array, np.array] = (np.zeros((3,)), np.eye(3)),\n ) -> None:\n # Base robot\n self._position = position\n self._radius = radius\n self.v_left = 0\n self.v_right = 0\n self.maximum_value_sensor = maximum_value_sensor\n self.acceleration = acceleration\n\n # Distance sensors\n self.sensors = sensors.copy()\n self.sensor_values = [self.maximum_value_sensor for i in self.sensors]\n\n # GE robot\n self.collisions = 0\n self._keep_trace = trace\n if trace:\n self._trace = [None for i in range(trace_size + 1)]\n self._trace[0] = self.position.copy()\n self._iteration = 1\n\n # KF robot\n self.beacons = []\n self.estimated_position = position.copy()\n self.map = map_\n self._rng = rng\n self._noise_mean = noise[0].copy()\n self._noise_cov = noise[1].copy()\n\n def _calculate_omega(self) -> float:\n \"\"\"\n Returns:\n Calculates and returns omega for the ICC formula\n\n \"\"\"\n if self.v_right == self.v_left:\n return 0\n else:\n return (self.v_left - self.v_right) / (2 * self.radius)\n\n def _calculate_r_capital(self) -> float:\n \"\"\"\n Returns:\n Calculates and returns R for the ICC formula\n\n \"\"\"\n if self.v_right == self.v_left:\n # in case they have similar values\n # we should not divide by zero\n # so, we are adding a very small constant\n constant = 0.0001\n return (\n self.radius\n * (self.v_left + self.v_right)\n / (self.v_left - self.v_right + constant)\n )\n else:\n return (\n self.radius\n * (self.v_left + self.v_right)\n / (self.v_left - self.v_right)\n )\n\n def _calculate_icc(self, r_capital) -> np.array:\n \"\"\"\n Returns:\n Calculates and returns ICC\n \"\"\"\n return np.array(\n [\n self._position[0] - r_capital * np.sin(self._position[2]),\n self._position[1] + r_capital * np.cos(self._position[2]),\n ]\n )\n\n def _calculate_new_position(\n self, omega: float, delta_t: float, icc: np.array\n ) -> np.array:\n \"\"\"\n Args:\n omega: angle\n delta_t: time step\n icc: icc component\n\n Returns:\n New position of the robot\n\n \"\"\"\n if self.v_right == self.v_left:\n delta_r_x = self.v_right * delta_t * np.cos(self._position[2])\n delta_r_y = self.v_right * delta_t * np.sin(self._position[2])\n return self._position + [delta_r_x, delta_r_y, 0]\n\n else:\n return np.array(\n np.array(\n [\n [np.cos(omega * delta_t), -np.sin(omega * delta_t), 0],\n [np.sin(omega * delta_t), np.cos(omega * delta_t), 0],\n [0, 0, 1],\n ]\n )\n @ np.array(\n [\n [self._position[0] - icc[0]],\n [self._position[1] - icc[1]],\n [self._position[2]],\n ]\n )\n + np.array([[icc[0]], [icc[1]], [omega * delta_t]])\n ).ravel()\n\n def compute_movement(self, dt: float) -> np.array:\n \"\"\"\n Compute the kinematic movement of the robot, assuming no collisions.\n\n Args:\n dt: time elapsed\n\n Returns:\n New position as [x, y, angle]\n \"\"\"\n omega = self._calculate_omega()\n r_capital = self._calculate_r_capital()\n icc = self._calculate_icc(r_capital)\n return self._calculate_new_position(omega, dt, icc)\n\n def compute_motion(self, dt: float) -> np.array:\n \"\"\"\n Compute the velocity and angular velocty of the robot. Ignore collisions\n\n Args:\n dt: time elapsed\n\n Returns:\n Array containing the magnitude of the velocity and the angular\n velocity [v, omega].\n\n \"\"\"\n omega = (self.compute_movement(dt)[2] - self.angle) / dt\n return np.array([self.v_left + self.v_right, omega])\n\n def set_position(self, position: np.array, angle: Optional[float] = None) -> None:\n \"\"\"\n Set the new position and angle of the robot\n\n Args:\n position: position as [x, y, angle] or [x, y]\n angle: angle. If None, then the position must include the angle\n\n Returns:\n None\n \"\"\"\n self._position[:2] = position.copy()\n if angle is None:\n self._position[2] = position[2]\n else:\n self._position[2] = angle\n if self._keep_trace:\n if self._iteration < len(self.trace):\n self._trace[self._iteration] = self.position.copy()\n self._iteration += 1\n\n def update_sensors(\n self, values: List[float], beacons: Optional[List[np.array]] = []\n ) -> None:\n \"\"\"\n Args:\n values: new values of the sensors\n beacons: distance, angle snd id from the beacons\n\n Returns:\n None\n \"\"\"\n self.sensor_values = values.copy()\n\n # Keep closest beacons\n self.beacons = sorted(beacons, key=lambda x: x[0])[:2]\n self.estimated_position = self._triangulate_position()\n\n def _triangulate_position(self) -> Optional[np.array]:\n \"\"\"\n Returns:\n Position estimate from the beacons\n\n \"\"\"\n # TODO clean this method\n if len(self.beacons) == 0:\n return None\n\n point = None\n angle = None\n\n if len(self.beacons) == 2:\n points = Geometry.sphere_sphere_intersection(\n self.map.landmarks[int(self.beacons[0][2])],\n self.beacons[0][0],\n self.map.landmarks[int(self.beacons[1][2])],\n self.beacons[1][0],\n )\n if len(points) == 1:\n angle = Geometry.ray_point_angle(\n points[0],\n self.map.landmarks[int(self.beacons[0][2])],\n self.beacons[0][1],\n )\n point = points[0]\n else:\n # Check first point\n point = points[0]\n angle = Geometry.ray_point_angle(\n point,\n self.map.landmarks[int(self.beacons[0][2])],\n self.beacons[0][1],\n )\n angle_other = Geometry.ray_point_angle(\n point,\n self.map.landmarks[int(self.beacons[1][2])],\n self.beacons[1][1],\n )\n\n if not np.allclose(angle - angle_other, 0):\n # Wrong point -> compute the angle with the other point\n point = points[1]\n angle = Geometry.ray_point_angle(\n point,\n self.map.landmarks[int(self.beacons[0][2])],\n self.beacons[0][1],\n )\n\n if point is not None and angle is not None:\n return np.array([*point, angle]) + self._rng.multivariate_normal(\n self._noise_mean, self._noise_cov\n )\n else:\n return None\n\n @property\n def position(self) -> np.array:\n \"\"\"\n Returns:\n Position of the robot in the x-y plane\n\n \"\"\"\n return self._position[:2].copy()\n\n @property\n def angle(self) -> float:\n \"\"\"\n Returns:\n Angle of the robot w.r.t. the horizontal axis. The angle is\n counterclock-wise and expressed in radiants.\n \"\"\"\n return self._position[2].copy()\n\n @property\n def pose(self) -> float:\n \"\"\"\n Returns:\n Position and angle of the robot\n \"\"\"\n return self._position.copy()\n\n @staticmethod\n def make_sensors(number: int) -> List[float]:\n \"\"\"\n Generate a list of sensors uniformely distributed.\n\n Args:\n number: number of sensors\n\n Returns:\n List of sensor angles\n\n \"\"\"\n return list(np.linspace(0, np.pi * 2, number + 1)[:-1])\n\n @property\n def trace(self) -> List[np.array]:\n \"\"\"\n Returns:\n Position of the robot at each time step of the simulation\n\n \"\"\"\n return self._trace\n\n @property\n def detected_beacons(self) -> List[int]:\n \"\"\"\n Returns:\n Index of the beacons currently detected\n \"\"\"\n return [i[2] for i in self.beacons]\n\n @property\n def radius(self) -> float:\n \"\"\"\n Returns:\n Radius of the robot\n \"\"\"\n return self._radius\n\n\nif __name__ == \"__main__\":\n robot = Robot(np.array([10, 10, 90]), 20, 200, 10, [0])\n robot.v_left = 10\n robot.v_right = 10\n robot.compute_movement(0.1)\n","repo_name":"AlexandraDI/Autonomous_Robotic_Systems","sub_path":"Assignment5/Robot.py","file_name":"Robot.py","file_ext":"py","file_size_in_byte":10598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"11424719798","text":"from vpython import *\nfrom vector import *\nfrom scattering import scatter\n\nelectron = sphere(pos = vector(0, 0, 100), make_trail = True)\n\nB = lambda h: Vector(0, 0, 0) - Khat\n\nP = Vector(0, 0, 100)\n\nL = 1000\n\nt = 0\n\nwhile True:\n rate(3)\n P, t = scatter(P, B, L, t)\n electron.pos = vector(P.x, P.y, P.z)","repo_name":"vidh2000/Aurora-Borealis-Simulation","sub_path":"scattering_test.py","file_name":"scattering_test.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"41886212662","text":"import os.path\nimport gc\nimport numpy as np\nimport rospkg\nimport rospy\nimport joblib\nimport std_msgs.msg\nimport sensor_msgs.msg\nimport torch\nimport time\nfrom sensor_msgs.msg import JointState\nfrom roboy_middleware_msgs.msg import MagneticSensor\nfrom libs.deploy_utils import BodyPart, MagneticId\nfrom libs.nn_models import LSTMRegressor\nfrom libs.orientation_utils import compute_rotation_matrix_from_ortho6d, compute_euler_angles_from_rotation_matrices\n\nMAX_ERROR = 0.3\nRESET_AFTER_N_REJECTIONS = 5\n\nfilter_n = 3\nhistory_n = 5\ninit_n = 5\n\nrospy.init_node('ball_socket_neural_network')\nsensors_scaler_lstm = [None for _ in MagneticId]\nmodel_lstm = [None for _ in MagneticId]\nhistory_lstm = [None for _ in MagneticId]\nfilter_lstm = [None for _ in MagneticId]\nreject_count_lstm = [0 for _ in MagneticId]\n\nlstmPublisher = rospy.Publisher(\"/roboy/oxford/prediction/external_joint_states\", sensor_msgs.msg.JointState, queue_size=1)\njoint_targets = [None for _ in MagneticId]\n\nprev_time = time.time()\n\ndef load_data(name, id):\n global sensors_scaler_lstm, filter, history\n sensors_scaler_lstm[id], _ = joblib.load(name + '/scaler.pkl')\n\n filter_lstm[id] = np.zeros((1, 3))\n\n history_lstm[id] = np.zeros((1, 12))\n\n\ndef target_data_callback(target_data):\n global joint_target\n\n for i in range(len(model_lstm)):\n body_part = BodyPart[MagneticId(i).name].value\n\n if f'{body_part}_axis0' in target_data.name:\n idx = target_data.name.index(f'{body_part}_axis0')\n joint_targets[MagneticId(i).value] = np.array(target_data.position[idx:idx+3])\n\n\ndef magentic_data_callback(magnetic_data):\n global filter_lstm, history_lstm, reject_count_lstm, prev_time\n\n if sensors_scaler_lstm[magnetic_data.id] is None:\n return\n \n if magnetic_data.id != 0:\n return\n\n x_test = np.array(\n [magnetic_data.x[0], magnetic_data.y[0], magnetic_data.z[0],\n magnetic_data.x[1], magnetic_data.y[1], magnetic_data.z[1],\n magnetic_data.x[2], magnetic_data.y[2], magnetic_data.z[2],\n magnetic_data.x[3], magnetic_data.y[3], magnetic_data.z[3]])\n rospy.loginfo_throttle(1, magnetic_data.id)\n rospy.loginfo_throttle(1, x_test)\n\n # Normalize input data\n x_test = x_test.reshape((1, len(x_test)))\n x_lstm_test = sensors_scaler_lstm[magnetic_data.id].transform(x_test).astype('float32')\n\n #################### LSTM #####################\n # Make sure we have a long enough trajectory to do the prediction\n history_lstm[magnetic_data.id] = np.append(history_lstm[magnetic_data.id], x_lstm_test, axis=0)\n if len(history_lstm[magnetic_data.id]) > history_n:\n history_lstm[magnetic_data.id] = np.delete(history_lstm[magnetic_data.id], 0, axis=0)\n \n x_in = torch.tensor(history_lstm[magnetic_data.id][None, :, :], dtype=torch.float32)\n out_set = model_lstm[magnetic_data.id](x_in)[:, -1]\n out_set = compute_rotation_matrix_from_ortho6d(out_set)\n output_lstm = compute_euler_angles_from_rotation_matrices(out_set).detach().numpy()\n\n if len(filter_lstm[magnetic_data.id]) < filter_n:\n filter_lstm[magnetic_data.id] = np.append(filter_lstm[magnetic_data.id], output_lstm, axis=0)\n\n error = np.abs(filter_lstm[magnetic_data.id][-1] - output_lstm)\n\n if error.max() < MAX_ERROR:\n filter_lstm[magnetic_data.id] = np.append(filter_lstm[magnetic_data.id], output_lstm, axis=0)\n filter_lstm[magnetic_data.id] = np.delete(filter_lstm[magnetic_data.id], 0, axis=0)\n\n # Publish messages\n msg = sensor_msgs.msg.JointState()\n msg.header = std_msgs.msg.Header()\n msg.header.stamp = rospy.Time.now()\n\n output_lstm = output_lstm[0]\n # msg.name = [BodyPart[MagneticId(magnetic_data.id).name] + \"_axis\" + str(i) for i in range(3)]\n msg.name = [\"axis\" + str(i) for i in range(3)]\n msg.position = [output_lstm[0], output_lstm[1], output_lstm[2]]\n msg.velocity = [0, 0, 0]\n msg.effort = [0, 0, 0]\n rospy.loginfo_throttle(1, msg.position)\n\n lstmPublisher.publish(msg)\n else:\n reject_count_lstm[magnetic_data.id] += 1\n rospy.logwarn(\"Reject lstm {} with error_{}={}\".format(BodyPart[MagneticId(magnetic_data.id).name], error.argmax(), error.max()))\n\n # Auto reset\n if reject_count_lstm[magnetic_data.id] > RESET_AFTER_N_REJECTIONS:\n reject_count_lstm[magnetic_data.id] = 0\n filter_lstm = [output_lstm for _ in MagneticId]\n \n # Clean up the memory after few seconds\n if time.time() - prev_time > 3:\n gc.collect()\n prev_time = time.time()\n print(\"Clean up\")\n\nif __name__ == '__main__':\n rate = rospy.Rate(300)\n\n rospack = rospkg.RosPack()\n base_path = rospack.get_path('ball_in_socket_estimator') + '/python/'\n\n # Search models and its corresponding body_parts.\n for i in range(len(model_lstm)):\n body_part = \"shoulder\" #BodyPart[MagneticId(i).name].value\n lstm_path = f'{base_path}/outputs_new/{body_part}_lstm_rot6D'\n\n if os.path.isdir(lstm_path):\n model_lstm[i] = LSTMRegressor.load_from_checkpoint(checkpoint_path=f'{lstm_path}/500epochs.ckpt')\n torch.set_grad_enabled(False)\n model_lstm[i].eval()\n print(\"Loading LSTM model \" + lstm_path + \" from disk\")\n load_data(lstm_path, i)\n\n rospy.Subscriber(\"/roboy/oxford/simulation/joint_targets\", JointState, target_data_callback, queue_size=1)\n rospy.Subscriber(\"/roboy/oxford/middleware/MagneticSensor\", MagneticSensor, magentic_data_callback, queue_size=1)\n\n rospy.spin()\n","repo_name":"Roboy/ball_and_socket_estimator","sub_path":"python/predict_lstm.py","file_name":"predict_lstm.py","file_ext":"py","file_size_in_byte":5731,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"77"} +{"seq_id":"43445277435","text":"#!/usr/bin/env python3\n\n\"\"\"\nUsage: make plots from data\n\n./plot.py \n\"\"\"\n\nimport sys\nimport csv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nvar_freq = []\n\nfor line in open(sys.argv[1]):\n if line[0] == \"#\":\n continue\n else:\n fields = line.rstrip(\"\\r\\n\").split(\"\\t\")\n info = fields[7]\n if \"AF=\" in info:\n freq = info.split(\"=\")\n freq2 = freq[1].split(\",\")\n var_freq.append(float(freq2[0]))\n#print(var_freq)\n\nvar_freq.sort()\n\nfig, ax = plt.subplots()\n\nax.hist(var_freq, bins = 100, color = \"green\")\nax.set_title(\"Allele Frequency Spectrum\")\nax.set_xlabel(\"Variant Bins\")\nax.set_ylabel(\"Frequency\")\n\nfig.savefig(\"plot.png\")\nplt.close(fig)\n ","repo_name":"natmurph16/qbb2018-answers","sub_path":"week4/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"29297862657","text":"import os\nimport board\nimport busio\nfrom digitalio import DigitalInOut, Direction, Pull\nfrom PIL import Image, ImageDraw, ImageFont\nimport adafruit_ssd1306\n\n\n\nclass Menu(object):\n \"\"\"\n docstring\n \"\"\"\n def __init__(self, txt_lst, screen_sz=(128, 64), selected=None):\n self.txt_lst = txt_lst\n self.width = screen_sz[0]\n self.height = screen_sz[1]\n self.selected = selected or 0\n self.screen_start = 0\n self.screen_end = 1\n self.canvas = Image.new('1', (self.width, \n self.height))\n self.drawing = ImageDraw.Draw(self.canvas)\n self.wipe_canvas()\n self.draw_text()\n \n\n def draw_text(self):\n \"\"\"\n Draw the text, skipping anything that is our of range of the available\n lines on the screen\n Draw a triangle next to the selected item\n \"\"\"\n start = 0\n space = 4\n font = ImageFont.truetype(\"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf\", 10)\n txt_ht = (self.drawing.textsize('A', font=font))[1]\n max_lines = self.height//(txt_ht + space)\n self.screen_end = max_lines - 1 + self.screen_start\n \n for index, line in enumerate(self.txt_lst):\n if self.screen_start > index:\n continue\n if index > self.screen_end:\n break\n self.drawing.text((10,start), line, font=font, fill=1)\n if index == self.selected:\n self.drawing.polygon([(0,start),\n (6,start + (txt_ht//2)),\n (0,start + txt_ht)],fill=1, outline=1)\n start = start + txt_ht + space\n\n def wipe_canvas(self):\n '''\n just draw a black square to clear the screen\n '''\n self.drawing.rectangle((0, 0, self.width, self.height), outline=0, fill=0)\n\n def inc_selected(self):\n '''\n Increment the selected item by one until max items\n adjust the list start and end attributes if scrolling\n '''\n if self.selected < len(self.txt_lst) - 1:\n self.selected += 1\n if self.selected > self.screen_end:\n self.screen_start += 1\n self.screen_end += 1\n self.wipe_canvas()\n self.draw_text()\n\n def dec_selected(self):\n \"\"\"\n Decrement the selected item by one until max items\n adjust the list start and end attributes if scrolling\n \"\"\"\n if self.selected > 0:\n self.selected -= 1\n if self.selected < self.screen_start:\n self.screen_start -= 1\n self.screen_end -= 1\n self.wipe_canvas()\n self.draw_text()\n\nclass Mode(object):\n \"\"\"\n docstring\n \"\"\"\n def __init__(self):\n self.mode = 'home'\n self.HOME = ['LOAD_SCHEDULE', 'NEW_SCHEDULE']\n self.menu = self.HOME\n\n def change(self, select):\n print(self.mode + ' : ' + select)\n if self.mode == 'home' and select == 'LOAD_SCHEDULE':\n self.menu = self._get_files()\n self.menu.append('Back')\n self.mode = 'disp_files'\n elif self.mode == 'disp_files' and select == 'Back':\n self.mode = 'home'\n self.menu = self.HOME\n elif self.mode == 'disp_files' and select != 'Back':\n self.mode = 'disp_schedule'\n self.menu = self._read_schedule(select)\n self.menu.extend(['START_SCHEDULE', 'Back'])\n elif self.mode == 'disp_schedule' and select == 'Back':\n self.mode = 'home'\n self.menu = self.HOME\n elif self.mode == 'disp_schedule' and select == 'START_SCHEDULE':\n print('starting schedule')\n self.mode = 'home'\n self.menu = self.HOME\n \n @staticmethod\n def _get_files():\n schedules = os.listdir('schedules')\n return schedules\n \n @staticmethod\n def _read_schedule(schedule_file):\n lines = []\n with open('schedules/' + schedule_file, \"r\") as f:\n for line in f:\n lines.append(line.rstrip())\n return lines\n\n\ndef main():\n # Create the I2C interface.\n i2c = busio.I2C(board.SCL, board.SDA)\n # Create the SSD1306 OLED class.\n disp = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c)\n\n # Clear display.\n disp.fill(0)\n disp.show()\n\n # Input pins:\n # button_A = DigitalInOut(board.D5)\n # button_A.direction = Direction.INPUT\n # button_A.pull = Pull.UP\n\n # button_B = DigitalInOut(board.D6)\n # button_B.direction = Direction.INPUT\n # button_B.pull = Pull.UP\n\n # button_L = DigitalInOut(board.D27)\n # button_L.direction = Direction.INPUT\n # button_L.pull = Pull.UP\n\n # button_R = DigitalInOut(board.D23)\n # button_R.direction = Direction.INPUT\n # button_R.pull = Pull.UP\n\n button_U = DigitalInOut(board.D17)\n button_U.direction = Direction.INPUT\n button_U.pull = Pull.UP\n U_pressed = False\n\n button_D = DigitalInOut(board.D22)\n button_D.direction = Direction.INPUT\n button_D.pull = Pull.UP\n D_pressed = False\n\n button_C = DigitalInOut(board.D4)\n button_C.direction = Direction.INPUT\n button_C.pull = Pull.UP\n C_pressed = False\n \n # Create blank image for drawing.\n # Make sure to create image with mode '1' for 1-bit color.\n width = disp.width\n height = disp.height\n\n\n mode = Mode()\n menu = Menu(mode.menu, screen_sz=(width, height))\n\n while True:\n if button_U.value: # button is released\n if U_pressed:\n menu.dec_selected()\n U_pressed = False\n else: # button pressed\n U_pressed = True\n \n if button_D.value:\n if D_pressed:\n menu.inc_selected()\n D_pressed = False\n else:\n D_pressed = True\n \n if button_C.value:\n if C_pressed:\n mode.change(menu.txt_lst[menu.selected])\n menu = Menu(mode.menu)\n C_pressed = False\n else:\n C_pressed = True\n\n \n disp.image(menu.canvas)\n disp.show()\n\n# run the main function only if this module is executed as the main script\n# (if you import this as a module then nothing is executed)\nif __name__==\"__main__\":\n # call the main function\n main()","repo_name":"pintbrewer/kilnUI","sub_path":"menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":6400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"4029904424","text":"import discord\nfrom discord.ext import commands\nfrom discord.app import slash_command\n\nclass Greetings(commands.Cog):\n def __init__(self, client):\n self.client = client\n self._last_member = None\n\n @commands.Cog.listener()\n async def on_member_join(self, member):\n channel = member.guild.system_channel\n if channel is not None:\n await channel.send(f'Welcome {member.mention}.')\n\n @slash_command()\n async def hello(self, ctx, *, member: discord.Member = None):\n \"\"\"Says hello\"\"\"\n member = member or ctx.author\n if self._last_member is None or self._last_member.id != member.id:\n await ctx.respond(f'Hello {member.name}~')\n else:\n await ctx.respond(f'Hello {member.name}... This feels familiar.')\n self._last_member = member\n\ndef setup(client):\n client.add_cog(Greetings(client))\n","repo_name":"TheReaper62/Embeded","sub_path":"modules/Greetings.py","file_name":"Greetings.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":"32391639724","text":"def solution(l):\n # l.sort()\n l = l[::-1]\n length = len(l)\n count = 0\n l_count = []\n for x in range(len(l)):\n l_count.append(0)\n\n x = 1\n while x < (length - 1):\n y = x + 1\n while y < length:\n if l[x] % l[y] == 0:\n l_count[x] = l_count[x] + 1\n y = y + 1\n x = x + 1\n x = 0\n while x < (length - 2):\n y = x + 1\n while y < (length - 1):\n if l[x] % l[y] == 0:\n count = count + l_count[y]\n y = y + 1\n x = x + 1\n return count\n\nl=[1,1,1]\nprint(solution(l))","repo_name":"dl1683/Daily-Coding-Challenge","sub_path":"AccessCodes.py","file_name":"AccessCodes.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"2347812569","text":"from prettytable import PrettyTable\nimport html\nimport shutil\nimport os\n\nclass table_html:\n def __init__(self, schema=None, image_dir=None):\n self.table = PrettyTable()\n self.headers = []\n if schema is not None:\n self._column_headers(schema)\n self._global_format_opts()\n \n def _global_format_opts(self):\n self.table.border = True\n self.table.format = True \n\n def _column_headers(self, schema):\n properties = schema['properties']\n for property in properties:\n prop_dict = properties[property]\n s_name = str(property)\n s_type = str(prop_dict['type'])\n self.headers.append([s_name, s_type])\n self.table.field_names = [name[0] for name in self.headers]\n\n def _generate_result_link(self, id):\n link = '
assay results'\n return link.format(id)\n \n def _generate_image_link(self, image_name):\n # TODO create thumbnail images rather than scaling the original\n link = '\\n'.format(image_name)\n link += '\"compound\\n'.format(image_name)\n link += ''\n return link\n\n def populate(self, data_list, preferred_id_field=0):\n for data in data_list:\n row_to_add = []\n\n # defaults to using compound_id if link required for assay_results\n id_for_link = data[self.headers[preferred_id_field][0]]\n \n # for each compound, check for elements to do something with\n for head in self.headers:\n if head[1] != 'array':\n if head[0] == 'image':\n # row_to_add.append(data[head[0]])\n row_to_add.append(self._generate_image_link(data[head[0]]))\n else:\n row_to_add.append(data[head[0]])\n else: # if array\n if head[0] == 'assay_results':\n row_to_add.append(self._generate_result_link(id_for_link))\n # what if array but not of assay_results?\n else:\n row_to_add.append(str(len(data[head[0]])))\n self.table.add_row(row_to_add)\n\n def get_string(self):\n return self.table.get_string()\n\n def get_html(self):\n return html.unescape(self.table.get_html_string())\n \n# god function\ndef generate_html_report(json_data, schema, image_dir=None):\n \"\"\"Created a tabulated report of the json data file\n contents as a html file\"\"\"\n\n # main pass/table\n toptab = table_html(schema, image_dir=image_dir)\n toptab.populate(json_data)\n\n # create build dir if doesn't exist already\n if not os.path.isdir('build'):\n os.mkdir('build')\n\n # write table html to file\n with open('build/report.html', 'w') as f:\n f.write('\\n\\t\\n')\n f.write(toptab.get_html())\n f.write('\\n\\t\\n')\n\n # if image_dir specified, copy to build dir\n if image_dir is not None:\n shutil.copytree(image_dir, 'build/images', dirs_exist_ok=True)\n\n # if any arrays found in header...\n for header in toptab.headers:\n if header[0] == 'assay_results':\n\n if not os.path.isdir('build/results'):\n os.mkdir('build/results')\n\n # loop pass for each set of results\n for compound in json_data:\n res_schema = schema['properties'][header[0]]\n res_data = compound[header[0]]\n results_tab = table_html(res_schema)\n results_tab.populate(res_data)\n c_id = compound['compound_id']\n\n with open('build/results/{}.html'.format(c_id), 'w') as f:\n f.write('\\n\\t\\n')\n f.write(results_tab.get_html())\n f.write('\\n\\t\\n')\n \n","repo_name":"arvinder-palaha/exscientia_coding_challenge","sub_path":"report/report_html.py","file_name":"report_html.py","file_ext":"py","file_size_in_byte":3964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"70953884409","text":"from fastapi import FastAPI\n\nfrom core import PortSeCore\n\n__author__ = 'danieluhm2004 '\n__copyright__ = 'Copyright 2020, Daniel Uhm'\n\napp = FastAPI(\n title='PortSe v2',\n description='Iptable based port forwarding to REST API',\n debug=True\n)\n\nif __name__ == '__main__':\n core = PortSeCore(app)\n core.start()\n","repo_name":"danieluhm2004/portse","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"38889555238","text":"# Boolean rules\n# Rules taken from https://sandbox.mc.edu/~bennet/cs110/boolalg/rules.html\n\n# The Idempotent Laws AA = A A+A = A\n# The Associative Laws (AB)C = A(BC) (A+B)+C = A+(B+C)\n# The Commutative Laws AB = BA A+B = B+A\n# The Distributive Laws A(B+C) = AB+AC A+BC = (A+B)(A+C)\n# The Identity Laws AF = F AT = A A+F = A A+T = T\n# The Complement Laws Anot(A) = F A+not(A) = T not(F) = T not(T) = F\n# The Involution Law not(not(A)) = A\n# DeMorgan's Law not(AB) = not(A)+not(B) not(A+B) = not(A)not(B)\n\ndef boolean_simplfy(expression: str, debug = False):\n\n # Remove the whitespace if there are any.\n expression = \"\".join(expression.split())\n\n if debug:\n print(f'Parsing: {expression}')\n print('Parsing expression for parenthesis')\n\n # Find pairs of parenthesis in the string\n try:\n\n completedParenthesesPairs = []\n pairsStack = []\n for index, symb in enumerate(expression):\n\n if debug:\n print(f'Index: {index}, Symbol: {symb}')\n \n if symb == '(':\n # Create a new parenthesis pair\n pairsStack.append([index, None])\n\n if debug:\n print(f'Found a Right Parentheses at index {index}')\n\n if symb == ')':\n # Check to see if there is a pair for the left parentheses to match with.\n if len(pairsStack) == 0:\n raise ValueError\n\n # Add the index to the pair list\n completedPair = pairsStack.pop()\n completedPair[1] = index\n completedParenthesesPairs.append(completedPair)\n\n if debug:\n print(f'Found a Left Parentheses at index {index}')\n\n # Check to see if all the parentheses have a pair\n if len(pairsStack) != 0:\n raise ValueError\n\n if debug:\n for pair in completedParenthesesPairs:\n print(pair)\n\n except ValueError:\n if debug:\n print(\"The expression has mismatched parentheses\")\n return None\n\n except Exception as err:\n if debug:\n print(\"Exception thrown while parsing the expression\")\n print(err)\n return None\n\n return completedParenthesesPairs\n\n","repo_name":"nguyjd/combinational_logic_creator","sub_path":"tests/boolean_simplify_tests/components_test/parenthesis_parsing/test_boolean_simplify.py","file_name":"test_boolean_simplify.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"15569275427","text":"# This involves nesting dictionaries.\n# This is another way in which the previous game can be organised. YOUR MISSION (If you choose to accept it):\n# Change the code to make it work.\n# Below is the complete program, but with the locations dictionary modified so that everything is in a single dictionary.\n# N.B: The code has some errors, thats what you need to fix!!!\n# You'll be changing just 4 lines of code. \n\nlocations = {\n 0: {\"desc\": \"You are sitting in front of a computer learning Python\",\n \"exits\": {},\n \"namedExits\":{}},\n 1: {\"desc\": \"You are standing at the end of a ROAD before a small brick building\",\n \"exits\": {\"W\": 2, \"E\" : 3, \"N\" : 5, \"S\" : 4, \"Q\" : 0},\n \"namedExits\": {\"2\": 2, \"3\": 3, \"5\": 5, \"4\": 4}},\n 2: {\"desc\": \"You are at the top of a HILL\",\n \"exits\": {\"N\": 5, \"Q\" : 0},\n \"namedExits\": {\"5\": 5}},\n 3: {\"desc\": \"You are inside a BUILDING, a well house for a small stream\",\n \"exits\": {\"W\": 1, \"Q\" : 0},\n \"namedExits\": {\"1\": 1}},\n 4: {\"desc\": \"You are in a VALLEY beside a stream\",\n \"exits\": {\"N\": 1, \"W\" : 2, \"Q\" : 0},\n \"namedExits\": {\"1\": 1, \"2\": 2}},\n 5: {\"desc\": \"You are in a FOREST\",\n \"exits\": {\"W\": 2, \"S\" : 1, \"Q\" : 0},\n \"namedExits\": {\"2\": 2, \"1\": 1}}\n}\nvocabulary = {\n \"QUIT\": \"Q\",\n \"NORTH\": \"N\",\n \"SOUTH\": \"S\",\n \"EAST\": \"E\",\n \"WEST\": \"W\",\n \"ROAD\": \"1\",\n \"HILL\": \"2\",\n \"BUILDING\": \"3\",\n \"VALLEY\": \"4\",\n \"FOREST\": \"5\"} \n\nloc = 1\nwhile True:\n availableExits = \", \".join(locations[loc][\"exits\"].keys())\n print(locations[loc][\"desc\"])\n# print(list(locations[loc][\"exits\"].keys())) # For checking purposes. \n\n \n\n if loc == 0:\n break \n else:\n allExits =locations[loc][\"exits\"].copy()\n allExits.update(locations[loc][\"namedExits\"])\n # exits[loc].update(namedExits) #using only this will cause an issue as .join in line 42 requires a string not int.\n\n direction = input(\"Available exits are \"+ availableExits + \" choose one only please \").upper() \n print()\n if len(direction) > 1: \n words = direction.split()\n for word in words:\n if word in vocabulary:\n direction = vocabulary[word]\n\n if direction in allExits: # we changed from exits[loc] to allExits\n loc = allExits[direction] \n else:\n print(\"You cannot go in that direction\")","repo_name":"ebosetalee/Python-Dictionary-and-Sets","sub_path":"Third_Dictionary_Challenge.py","file_name":"Third_Dictionary_Challenge.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"41852283696","text":"import wx\n\nfrom pyxenoverse.gui.ctrl.custom_check_box import CustomCheckBox\nfrom pyxenoverse.gui.ctrl.custom_radio_box import CustomRadioBox\nfrom pyxenoverse.gui.ctrl.dummy_ctrl import DummyCtrl\nfrom pyxenoverse.gui.ctrl.hex_ctrl import HexCtrl\n\n\nclass MultipleSelectionBox(wx.Panel):\n def __init__(self, parent, *args, **kwargs):\n super().__init__(parent)\n self.SetName(kwargs.get('name', 'SelectionBox'))\n cols = kwargs.pop('cols', 100)\n title = kwargs.pop('title', '')\n\n sizer = wx.StaticBoxSizer(wx.VERTICAL, self, title)\n item_sizer = wx.FlexGridSizer(rows=100, cols=cols, hgap=10, vgap=5)\n\n self.selections = []\n choices = kwargs.pop('choices', [])\n\n for name, items, multiple in choices:\n if not items and not multiple:\n self.selections.insert(0, DummyCtrl())\n continue\n kwargs['label'] = name or ''\n kwargs['choices'] = items or []\n if multiple:\n ctrl = CustomCheckBox(self, *args, **kwargs)\n else:\n ctrl = CustomRadioBox(self, *args, **kwargs)\n self.selections.insert(0, ctrl)\n item_sizer.Add(ctrl, 0, wx.EXPAND)\n self.hex_ctrl = HexCtrl(self, max=0xFFFF)\n self.hex_ctrl.Disable()\n sizer.Add(item_sizer, 0, wx.LEFT | wx.RIGHT, 10)\n sizer.Add(self.hex_ctrl, 0, wx.ALL, 10)\n\n self.Bind(wx.EVT_TEXT, self.on_text)\n self.Bind(wx.EVT_RADIOBOX, self.on_select)\n self.Bind(wx.EVT_CHECKBOX, self.on_select)\n\n self.SetSizer(sizer)\n self.SetAutoLayout(1)\n\n def GetValue(self):\n return self.hex_ctrl.GetValue()\n\n def SetValue(self, value):\n self.hex_ctrl.SetValue(value)\n self.on_text(None)\n\n def on_select(self, e):\n value = sum(ctrl.GetValue() << (4 * i) for i, ctrl in enumerate(self.selections))\n self.hex_ctrl.SetValue(value)\n e.Skip()\n\n def on_text(self, e):\n value = self.hex_ctrl.GetValue()\n for i, ctrl in enumerate(self.selections):\n ctrl.SetValue((value >> (4 * i)) & sum(1 << n for n in range(ctrl.GetLength())))\n if e:\n e.Skip()\n","repo_name":"KyonkoYuuki/pyxenoverse","sub_path":"pyxenoverse/gui/ctrl/multiple_selection_box.py","file_name":"multiple_selection_box.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"2282727906","text":"#-*- coding:utf-8 -*-\n\nimport Tkinter as tk\n\nroot = tk.Tk()\n\ntk.Label(root,text='月黑风高夜').pack()\n\nseparator = tk.Frame(height=20, # 设置frame的高度\n bd=10, # 指定frame边框宽度,默认为0\n relief=tk.SUNKEN, # 指定边框样式\n container=True, # 该窗口作为容器,用于嵌入其他应用程序,默认False\n padx=100, # 水平方向上的边距\n pady=100, # 垂直方向上的份额边距\n width=2, # 指定frame的狂度,默认为0\n )\nseparator.pack(fill=tk.X)\n\ntk.Label(root,text='杀人放火时').pack()\n\ntk.Button(root,text=\"Exit\",command=root.quit).pack()\n\nroot.mainloop()","repo_name":"aoyueRay/LearnTkinter","sub_path":"frame.py","file_name":"frame.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"37248822086","text":"# -*- coding: UTF-8 -*-\nimport os\nimport time\nimport logging\n\n\n# 将薛师兄代码里的数字转变为更加易懂的参数输入\ndef fault_injection(fault_type, **kwargs):\n logging.info(\"Ready to inject fault.\")\n # fault_type have 4 types: 'cpu', 'mem', 'disk', 'net'\n if fault_type == 'cpu':\n print(\"cpu error injection\")\n logging.info(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n # CPU Fault has 2 args: thread_num, duration\n if 'thread_num' not in kwargs or kwargs['thread_num'] is None:\n thread_num = '4'\n else:\n thread_num = kwargs['thread_num']\n if 'duration' not in kwargs or kwargs['duration'] is None:\n duration = '15'\n else:\n duration = kwargs['duration']\n # 切分为多进程\n pid = os.fork()\n # 子进程负责错误注入\n if pid == 0:\n # using linux command to inject faults.\n os.system(\"stress -c %s -t %s\" % (thread_num, duration))\n # 父进程负责返回注入结果并继续监听 Server 端口\n else:\n logging.info(\"stress -c %s -t %s\" % (thread_num, duration))\n info = [\n {'status': 'success'},\n {'fault_type': '%s' % fault_type},\n {'description': 'Your arguments of injection are thread_num=%s, duration=%s.' % (thread_num, duration)}\n ]\n return info\n\n elif fault_type == 'mem':\n logging.info(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n # Memory Fault has 3 args: thread_num, mem_size, duration\n if 'thread_num' not in kwargs or kwargs['thread_num'] is None:\n thread_num = '4'\n else:\n thread_num = kwargs['thread_num']\n if 'mem_size' not in kwargs or kwargs['mem_size'] is None:\n mem_size = '128M'\n else:\n mem_size = kwargs['mem_size']\n if 'duration' not in kwargs or kwargs['duration'] is None:\n duration = '15'\n else:\n duration = kwargs['duration']\n\n pid = os.fork()\n if pid == 0:\n os.system(\"stress --vm %s --vm-bytes %s --vm-keep -t %s\" % (thread_num, mem_size, duration))\n else:\n logging.info(\"stress --vm %s --vm-bytes %s --vm-keep -t %s\" % (thread_num, mem_size, duration))\n info = [\n {'status': 'success'},\n {'fault_type': '%s' % fault_type},\n {'description': 'Your arguments of injection are thread_num=%s, mem_size=%s, duration=%s.' % (thread_num, mem_size, duration)}\n ]\n return info\n\n # iostat -x -k -d 1\n elif fault_type == 'disk':\n logging.info(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n # args\n if 'io_times' not in kwargs or kwargs['io_times'] is None:\n io_times = '4'\n else:\n io_times = kwargs['io_times']\n if 'duration' not in kwargs or kwargs['duration'] is None:\n duration = '15'\n else:\n duration = kwargs['duration']\n\n pid = os.fork()\n if pid == 0:\n os.system(\"stress -i %s -t %s\" % (io_times, duration))\n else:\n logging.info(\"stress -i %s -t %s\" % (io_times, duration))\n info = [\n {'status': 'success'},\n {'fault_type': '%s' % fault_type},\n {'description': 'Your arguments of injection are io_times=%s, duration=%s.' % (io_times, duration)}\n ]\n return info\n\n elif fault_type == 'net':\n logging.info(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n if 'net_port' not in kwargs or kwargs['net_port'] is None:\n net_port = '100'\n else:\n net_port = kwargs['net_port']\n\n pid = os.fork()\n if pid == 0:\n os.system(\"iperf3 -s -p %s\" % net_port)\n else:\n logging.info(\"iperf3 -s -p %s\" % net_port)\n info = [\n {'status': 'success'},\n {'fault_type': '%s' % fault_type},\n {'description': 'Your arguments of injection are net_port=%s.' % net_port}\n ]\n return info\n\n # 若错误类型不在这4种之内,则返回 None\n else:\n error = [\n {'status': 'error'},\n {'description': 'fault_type must in the range of cpu, mem, dish and net. Your fault_type is %s.' % fault_type}\n ]\n return error\n\n pass\n\n\nif __name__ == '__main__':\n fault_injection('cpu')\n\n","repo_name":"iscas-microservice-team/microFaultInjection","sub_path":"func_pack.py","file_name":"func_pack.py","file_ext":"py","file_size_in_byte":4558,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"77"} +{"seq_id":"8877026297","text":"#!/usr/bin/env python3\n\nimport argparse\nimport json\nimport os\nimport re\nimport sys\n\n\nclass JobGenerator(object):\n def __init__(self, args):\n\n self.libreelec_dir = args.libreelec_dir\n self.output_dir = args.output_dir\n self.template_dir = \"job-templates\"\n self.dashboard_dir = \"dashboard-templates\"\n\n if not os.path.exists(self.libreelec_dir):\n print(f\"Path to LibreELEC.tv directory is invalid: {self.libreelec_dir}\")\n sys.exit()\n\n if os.path.exists(self.output_dir):\n print(f\"output directory already exists: {self.output_dir}\")\n sys.exit()\n\n os.mkdir(self.output_dir)\n\n def _parse_projects(self, valid_projects=[], invalid_projects=[]):\n\n projects = []\n\n for project in os.listdir(os.path.join(self.libreelec_dir, \"projects\")):\n\n # skip special add-ons only project\n if (len(invalid_projects) > 0) and project in invalid_projects:\n continue\n\n if (len(valid_projects) > 0) and project not in valid_projects:\n continue\n\n definition = {\"project\": project}\n\n if os.path.exists(\n os.path.join(self.libreelec_dir, \"projects\", project, \"devices\")\n ):\n\n # assume and project with \"devices\" folder uses arm arch\n definition[\"arch\"] = \"arm\"\n\n # it would sure be nice to have a build matrix\n if project == \"Generic\":\n definition[\"arch\"] = \"x86_64\"\n\n definition[\"devices\"] = []\n for device in os.listdir(\n os.path.join(self.libreelec_dir, \"projects\", project, \"devices\")\n ):\n definition[\"devices\"].append(device)\n else:\n # assume and project without \"devices\" folder uses x86_64 arch\n definition[\"arch\"] = \"x86_64\"\n\n projects.append(definition)\n\n return projects\n\n def _write_files(self, output_file, data, project, device, arch):\n\n data = data.replace(\n \"@NAME@\", (lambda x, y: x if len(x) > 0 else y)(device, project)\n )\n data = data.replace(\"@PROJECT@\", project)\n data = data.replace(\"@DEVICE@\", device)\n data = data.replace(\"@ARCH@\", arch)\n\n include_regions = []\n trigger_phrase = (\n trigger_phrase\n ) = f\".*jenkins build this for (?i)({project}|all).*\"\n if device != \"\":\n include_regions.append(os.path.join(\"projects\", project, \"(?!devices).*\"))\n include_regions.append(\n os.path.join(\"projects\", project, \"devices\", device, \".*\")\n )\n\n trigger_phrase = f\".*jenkins build this for (?i)({project}|{device}|all).*\"\n\n data = data.replace(\"@INCLUDE_REGIONS@\", \"\\\\n\".join(include_regions))\n data = data.replace(\"@TRIGGER_PHRASE@\", trigger_phrase)\n\n with open(os.path.join(self.output_dir, output_file), \"w\") as f:\n f.write(data)\n\n def _process_template(self, template, projects):\n\n job_list = []\n\n template_data = \"\"\n with open(os.path.join(self.template_dir, template)) as f:\n template_data = f.read()\n\n for object in projects:\n project = object[\"project\"]\n arch = object[\"arch\"]\n if \"devices\" in object:\n for device in object[\"devices\"]:\n job_list.append(device)\n output_file = \"_\".join(\n [device.replace(\"-\", \"_\"), template.replace(\".in\", \"\")]\n )\n self._write_files(output_file, template_data, project, device, arch)\n else:\n job_list.append(project)\n output_file = \"_\".join(\n [project.replace(\"-\", \"_\"), template.replace(\".in\", \"\")]\n )\n self._write_files(output_file, template_data, project, \"\", arch)\n\n return job_list\n\n def _process_dashboard(self, dashboard, jobs):\n\n dashboard_data = \"\"\n\n with open(os.path.join(self.dashboard_dir, dashboard)) as f:\n dashboard_data = f.read()\n\n job_list = []\n for job in jobs:\n job_list.append(f\" name('{job}')\")\n\n dashboard_data = dashboard_data.replace(\"@JOBS@\", \"\\n\".join(job_list))\n\n output_file = dashboard.replace(\".in\", \"\")\n with open(os.path.join(self.output_dir, output_file), \"w\") as f:\n f.write(dashboard_data)\n\n def _process_images(self):\n\n projects = self._parse_projects(valid_projects=[], invalid_projects=[\"ARM\"])\n\n print(\"Projects for builds:\")\n print(json.dumps(projects, indent=4))\n print(\"\")\n\n # process builds\n template = \"builds.groovy.in\"\n jobs = self._process_template(template, projects)\n\n # process dashboard\n dashboard = \"builds.groovy.in\"\n self._process_dashboard(dashboard, jobs)\n\n def _process_addon_builds(self):\n\n projects = self._parse_projects([\"ARM\", \"Generic\", \"RPi\"], invalid_projects=[])\n\n print(\"Projects for add-ons:\")\n print(json.dumps(projects, indent=4))\n print(\"\")\n\n # process builds\n template = \"addons.groovy.in\"\n jobs = self._process_template(template, projects)\n\n # process dashboard\n dashboard = \"addons.groovy.in\"\n self._process_dashboard(dashboard, [f\"{x}-Add-ons\" for x in jobs])\n\n def Run(self):\n\n self._process_images()\n\n self._process_addon_builds()\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(\n description=\"Generate jenkins dsl builds from templates\"\n )\n\n parser.add_argument(\n \"--libreelec-dir\", default=\"LibreELEC.tv\", help=\"Path to LibreELEC.tv folder\"\n )\n\n parser.add_argument(\"--output-dir\", default=\"output\", help=\"Path to output folder\")\n\n args = parser.parse_args()\n\n generator = JobGenerator(args)\n\n generator.Run()\n","repo_name":"lrusak/LibreELEC-jenkins-jobs","sub_path":"jenkins-job-generator.py","file_name":"jenkins-job-generator.py","file_ext":"py","file_size_in_byte":6036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"11919531921","text":"class Solution:\n def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n boxTypes = sorted(boxTypes, key = lambda x: x[1], reverse = True)\n \n n = len(boxTypes)\n res = 0 \n \n for i in range(n):\n res = res + max(0, min(boxTypes[i][0], truckSize)) * boxTypes[i][1]\n truckSize = truckSize - boxTypes[i][0]\n \n return res\n","repo_name":"tzxdtc/codeCamp","sub_path":"greedy/Maximum Units on a Truck.py","file_name":"Maximum Units on a Truck.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"21336845365","text":"# Import Module\r\nfrom tkinter import *\r\n \r\n# create root window\r\nroot = Tk()\r\n \r\n# root window title and dimension\r\nroot.title(\"Jeroen's CIDR tool 1.1\")\r\n# Set geometry (widthxheight)\r\nroot.geometry('400x300')\r\n \r\n# Adding labels and entries to the root window\r\nintro = Label(root, text = \"Welcome to CIDR subnetting tool!\")\r\nintro.grid(row = 0, columnspan = 15)\r\n\r\nlbl0 = Label(root, text = \"Please enter your IP and mask bits: \")\r\nlbl0.grid(column = 0, row = 1)\r\n\r\nip1 = Entry(root, width = 3)\r\nip1.grid(column = 1, row = 1)\r\n\r\nlbl1 = Label(root, text = \".\")\r\nlbl1.grid(column = 2, row = 1)\r\n\r\nip2 = Entry(root, width = 3)\r\nip2.grid(column = 3, row = 1)\r\n\r\nlbl2 = Label(root, text = \".\")\r\nlbl2.grid(column = 4, row = 1)\r\n\r\nip3 = Entry(root, width = 3)\r\nip3.grid(column = 5, row = 1)\r\n\r\nlbl3 = Label(root, text = \".\")\r\nlbl3.grid(column = 6, row = 1)\r\n\r\nip4 = Entry(root, width = 3)\r\nip4.grid(column = 7, row = 1)\r\n\r\nlbl4 = Label(root, text = \"/\")\r\nlbl4.grid(column = 8, row = 1)\r\n\r\nsmask = Entry(root, width = 2)\r\nsmask.grid(column = 9, row = 1)\r\n\r\nlbl4 = Label(root, text = \" \")\r\nlbl4.grid(column = 10, row = 1)\r\n\r\nempty = Label(root, text = \"\")\r\nempty.grid(column = 0, row = 2)\r\n\r\nfullipt = Label(root)\r\nsubnetmaskt = Label(root)\r\nnetworkadresst = Label(root)\r\nbroadcastadresst = Label(root)\r\nhostnumbert = Label(root)\r\nfullip = Label(root)\r\nsubnetmask = Label(root)\r\nnetworkadress = Label(root)\r\nbroadcastadress = Label(root)\r\nhostnumber = Label(root)\r\n\r\n\r\n# CIDR functions:\r\n\r\n# Converting mask bits into subnet mask\r\ndef submask(mask):\r\n range1 = [25,26,27,28,29,30,31]\r\n range2 = [17,18,19,20,21,22,23,24]\r\n range3 = [9,10,11,12,13,14,15,16]\r\n range4 = [1,2,3,4,5,6,7,8]\r\n if mask in range1: \r\n snm1 = 255\r\n snm2 = 255\r\n snm3 = 255\r\n if mask == 25:\r\n snm4 = 128\r\n elif mask == 26:\r\n snm4 = 192\r\n elif mask == 27:\r\n snm4 = 224\r\n elif mask == 28:\r\n snm4 = 240\r\n elif mask == 29:\r\n snm4 = 248\r\n elif mask == 30:\r\n snm4 = 252\r\n elif mask == 31:\r\n snm4 = 254\r\n elif mask in range2:\r\n snm1 = 255\r\n snm2 = 255\r\n snm4 = 0\r\n if mask == 17:\r\n snm3 = 128\r\n elif mask == 18:\r\n snm3 = 192\r\n elif mask == 19:\r\n snm3 = 224\r\n elif mask == 20:\r\n snm3 = 240\r\n elif mask == 21:\r\n snm3 = 248\r\n elif mask == 22:\r\n snm3 = 252\r\n elif mask == 23:\r\n snm3 = 254\r\n elif mask == 24:\r\n snm3 = 255\r\n elif mask in range3:\r\n snm1 = 255\r\n snm3 = 0\r\n snm4 = 0\r\n if mask == 9:\r\n snm2 = 128\r\n elif mask == 10:\r\n snm2 = 192\r\n elif mask == 11:\r\n snm2 = 224\r\n elif mask == 12:\r\n snm2 = 240\r\n elif mask == 13:\r\n snm2 = 248\r\n elif mask == 14:\r\n snm2 = 252\r\n elif mask == 15:\r\n snm2 = 254\r\n elif mask == 16:\r\n snm2 = 255\r\n elif mask in range4:\r\n snm2 = 0\r\n snm3 = 0\r\n snm4 = 0\r\n if mask == 1:\r\n snm1 = 128\r\n elif mask == 2:\r\n snm1 = 192\r\n elif mask == 3:\r\n snm1 = 224\r\n elif mask == 4:\r\n snm1 = 240\r\n elif mask == 5:\r\n snm1 = 248\r\n elif mask == 6:\r\n snm1 = 252\r\n elif mask == 7:\r\n snm1 = 254\r\n elif mask == 8:\r\n snm1 = 255\r\n return snm1,snm2,snm3,snm4\r\n\r\n# Calculating Network address from ip adress and subnetmask with an AND operator\r\ndef netwadr(mask,snm1,snm2,snm3,snm4):\r\n if mask <= 8:\r\n nwa2 = 0\r\n nwa3 = 0\r\n nwa4 = 0\r\n nwa1 = int(ip1.get()) & snm1\r\n elif mask <= 16:\r\n nwa1 = int(ip1.get())\r\n nwa3 = 0\r\n nwa4 = 0\r\n nwa2 = int(ip2.get()) & snm2\r\n elif mask <= 24:\r\n nwa1 = int(ip1.get())\r\n nwa2 = int(ip2.get())\r\n nwa4 = 0\r\n nwa3 = int(ip3.get()) & snm3\r\n else:\r\n nwa1 = int(ip1.get())\r\n nwa2 = int(ip2.get())\r\n nwa3 = int(ip3.get())\r\n nwa4 = int(ip4.get()) & snm4\r\n return nwa1, nwa2, nwa3, nwa4\r\n\r\n# Calculating Broadcast address from subnet mask and ip adress with an OR operator\r\ndef bcadr(mask,snm1,snm2,snm3,snm4):\r\n if mask <= 8:\r\n bca2 = 255\r\n bca3 = 255\r\n bca4 = 255\r\n bca1 = int(ip1.get()) | (255 - snm1)\r\n elif mask <= 16:\r\n bca1 = int(ip1.get())\r\n bca3 = 255\r\n bca4 = 255\r\n bca2 = int(ip2.get()) | (255 - snm2)\r\n elif mask <= 24:\r\n bca1 = int(ip1.get())\r\n bca2 = int(ip2.get())\r\n bca4 = 255\r\n bca3 = int(ip3.get()) | (255 - snm3)\r\n else:\r\n bca1 = int(ip1.get())\r\n bca2 = int(ip2.get())\r\n bca3 = int(ip3.get())\r\n bca4 = int(ip4.get()) | (255 - snm4)\r\n return bca1, bca2, bca3, bca4\r\n\r\n# Calculating hosts with a formula\r\ndef hosts(mask):\r\n host = 2 ** (32 - mask) - 2\r\n return host\r\n\r\n# function to display entries in text when button is clicked\r\n# Also added a check to display 'Invalid IP' in red text if any of the numbers are bigger than 255 \r\n# or no number at all\r\n# Also calls all CIDR functions to display outcome after button is clicked\r\ndef clicked():\r\n # Emptying all labels so when error message appears it's clean\r\n fullipt.config(text = \"\")\r\n subnetmaskt.config(text= \"\")\r\n networkadresst.config(text = \"\")\r\n broadcastadresst.config(text= \"\")\r\n hostnumbert.config(text = \"\")\r\n fullip.config(text = \"\")\r\n subnetmask.config(text= \"\")\r\n networkadress.config(text = \"\")\r\n broadcastadress.config(text= \"\")\r\n hostnumber.config(text = \"\")\r\n \r\n # Try for checking if input is valid\r\n try:\r\n if int(ip1.get()) > 255 or int(ip2.get()) > 255 or int(ip3.get()) > 255 or int(ip4.get()) > 255:\r\n fullip.configure(text = \"Invalid IP or bit mask number\" , fg = \"red\")\r\n fullip.grid(column = 0, row = 3, columnspan= 7)\r\n elif int(smask.get()) < 0 or int(smask.get()) > 31:\r\n fullip.configure(text = \"Invalid IP or bit mask number\" , fg = \"red\")\r\n fullip.grid(column = 0, row = 3, columnspan= 7)\r\n else:\r\n\r\n fullipt.configure(text = \"Your IP is: \", fg = \"black\")\r\n fullipt.grid(column = 0, row = 3, columnspan= 7, sticky = \"w\")\r\n fullip.configure(text = ip1.get()+\".\"+ip2.get()+\".\"+ip3.get()+\".\"+ip4.get(), fg = \"black\")\r\n fullip.grid(column = 4, row = 3, columnspan= 7, sticky = \"w\")\r\n \r\n mask = int(smask.get())\r\n snm1,snm2,snm3,snm4 = submask(mask)\r\n \r\n subnetmaskt.configure(text = \"Subnet mask is: \", fg = \"black\")\r\n subnetmaskt.grid(column = 0, row = 4, columnspan = 7, sticky = \"w\")\r\n subnetmask.configure(text = str(snm1)+\".\"+str(snm2)+\".\"+str(snm3)+\".\"+str(snm4), fg = \"black\")\r\n subnetmask.grid(column = 4, row = 4, columnspan = 7, sticky = \"w\")\r\n \r\n nwa1,nwa2,nwa3,nwa4 = netwadr(mask,snm1,snm2,snm3,snm4)\r\n \r\n networkadresst.configure(text = \"Network address is: \", fg = \"black\")\r\n networkadresst.grid(column = 0, row = 5, columnspan = 7, sticky = \"w\")\r\n networkadress.configure(text = str(nwa1)+\".\"+str(nwa2)+\".\"+str(nwa3)+\".\"+str(nwa4), fg = \"black\")\r\n networkadress.grid(column = 4, row = 5, columnspan = 7, sticky = \"w\")\r\n \r\n bca1,bca2,bca3,bca4 = bcadr(mask,snm1,snm2,snm3,snm4)\r\n \r\n broadcastadresst.configure(text = \"Broadcast address is: \", fg = \"black\")\r\n broadcastadresst.grid(column = 0, row = 6, columnspan = 7, sticky = \"w\")\r\n broadcastadress.configure(text = str(bca1)+\".\"+str(bca2)+\".\"+str(bca3)+\".\"+str(bca4), fg = \"black\")\r\n broadcastadress.grid(column = 4, row = 6, columnspan = 7, sticky = \"w\")\r\n \r\n host = hosts(mask)\r\n \r\n hostnumbert.configure(text = \"Maximum hosts per subnet: \", fg = \"black\")\r\n hostnumbert.grid(column = 0, row = 7, columnspan= 7, sticky = \"w\")\r\n hostnumber.configure(text = str(host) , fg = \"black\")\r\n hostnumber.grid(column = 4, row = 7, columnspan= 7, sticky = \"w\")\r\n\r\n except ValueError:\r\n fullip.configure(text = \"Invalid IP or bit mask number\" , fg = \"red\")\r\n fullip.grid(column = 0, row = 3, columnspan= 7)\r\n \r\n# Adding a button with blue text inside\r\nbtn = Button(root, text = \"Go!!!\" , fg = \"blue\", command = clicked)\r\n\r\n# Set button grid\r\nbtn.grid(column = 11, row = 1)\r\n\r\n# Execute Tkinter\r\nroot.mainloop()\r\n","repo_name":"Jerpen80/CIDRtoolGUI","sub_path":"CIDRtoolGUI.py","file_name":"CIDRtoolGUI.py","file_ext":"py","file_size_in_byte":8775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"27372411814","text":"from locust import task, HttpUser, constant\nfrom locust.event import EventHook\n\nsend_email_notifications = EventHook()\nsend_text_notifications = EventHook()\n\n\ndef email(i, j, req_id, message=None, **kwargs):\n print(\"Sending {} in the email for the request {}.\".format(message, req_id))\n\n\ndef sms_text(i, j, req_id, message=None, **kwargs):\n print(\"Sending {} in the SMS for the request {}.\".format(message, req_id))\n\n\nsend_email_notifications.add_listener(email)\nsend_text_notifications.add_listener(sms_text)\n\n\nclass LoadTest(HttpUser):\n host = \"https://onlineboutique.dev\"\n wait_time = constant(1)\n\n def on_start(self):\n print(\"Starting...\")\n\n def on_stop(self):\n print(\"Stopping...\")\n\n @task\n def home_page(self):\n with self.client.get(\"/\", name=\"T00_HomePage\", catch_response=True) as response:\n if response.status_code == 200:\n send_email_notifications.fire(i=1, j=2, req_id=1, message=\"success\")\n send_text_notifications.fire(i=1, j=2, req_id=2, message=\"success\")\n else:\n send_email_notifications.fire(i=1, j=2, req_id=1, message=\"failure\")\n send_text_notifications.fire(i=1, j=2, req_id=2, message=\"failure\")\n\n with self.client.get(\"/test\", name=\"T01_FailedHomePage\", catch_response=True) as response:\n if response.status_code == 200:\n send_email_notifications.fire(i=1, j=2, req_id=3, message=\"success\")\n send_text_notifications.fire(i=1, j=2, req_id=4, message=\"success\")\n else:\n send_email_notifications.fire(i=1, j=2, req_id=3, message=\"failure\")\n send_text_notifications.fire(i=1, j=2, req_id=4, message=\"failure\")\n","repo_name":"goel4ever/locust-sandbox","sub_path":"src/event_hook_custom.py","file_name":"event_hook_custom.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"33347676539","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, print_function, division\nimport itertools\n\n\nimport numpy as np\n\n\nfrom numcodecs.compat import PY2\nfrom numcodecs.pickles import Pickle\nfrom numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array,\n check_backwards_compatibility, greetings)\n\n\ncodecs = [\n Pickle(protocol=0),\n Pickle(protocol=1),\n Pickle(protocol=2),\n]\nif not PY2: # pragma: py2 no cover\n codecs.append(Pickle(protocol=3))\n codecs.append(Pickle(protocol=4))\n\n\n# object array with strings\n# object array with mix strings / nans\n# object array with mix of string, int, float\n# ...\narrays = [\n np.array(['foo', 'bar', 'baz'] * 300, dtype=object),\n np.array([['foo', 'bar', np.nan]] * 300, dtype=object),\n np.array(['foo', 1.0, 2] * 300, dtype=object),\n np.arange(1000, dtype='i4'),\n np.array(['foo', 'bar', 'baz'] * 300),\n np.array(['foo', ['bar', 1.0, 2], {'a': 'b', 'c': 42}] * 300, dtype=object),\n np.array(greetings * 100),\n np.array(greetings * 100, dtype=object),\n]\n\n\ndef test_encode_decode():\n for arr, codec in itertools.product(arrays, codecs):\n check_encode_decode_array(arr, codec)\n\n\ndef test_config():\n codec = Pickle(protocol=-1)\n check_config(codec)\n for codec in codecs:\n check_config(codec)\n\n\ndef test_repr():\n check_repr(\"Pickle(protocol=-1)\")\n\n\ndef test_backwards_compatibility():\n check_backwards_compatibility(Pickle.codec_id, arrays, codecs)\n","repo_name":"xlandscape/CmfContinuous-Component","sub_path":"module/bin/python/Lib/site-packages/numcodecs/tests/test_pickles.py","file_name":"test_pickles.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"27346945587","text":"import os\nimport random\nimport time\nimport argparse\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader\n\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\n\nfrom solution.shufflenet import shufflenet_g3_wd4\nfrom solution.dataloader import *\nfrom solution.loss import *\nfrom solution.scheduler import *\nfrom solution.evaluate import *\nfrom solution.metric import *\nfrom solution.utils import *\n\n\ndef train(params, model, train_loader, val_loader, device):\n best_val_f1 = params[\"best_val_f1\"]\n criterion = F1_Focal_Loss(f1rate=0.6, gamma=2.0, weight=None)\n optimizer = torch.optim.AdamW(model.parameters(), lr=params[\"LR_start\"])\n scheduler = CosineAnnealingWarmUpRestarts(optimizer, T_0=40, T_mult=2, eta_max=params[\"LR_max\"], T_up=5, gamma=0.5)\n\n print(\"Start training..\")\n for epoch in range(params[\"EPOCHS\"]):\n epoch+=1\n avg_loss = 0\n batch_count = len(train_loader)\n\n for step, (imgs, labels) in enumerate(train_loader):\n start = time.time()\n imgs = imgs.to(device).float()\n labels = labels.to(device)\n\n output = model(imgs)\n loss = criterion(output, labels)\n\n optimizer.zero_grad()\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), params[\"clip\"])\n optimizer.step()\n\n avg_loss+=loss.item()/batch_count\n print(f\"\\rEpoch:{epoch:3d} step:{step+1:3d}/{batch_count} time:{time.time() - start:.3f} LR:{scheduler.get_lr()[0]:.6f}\", end='')\n scheduler.step()\n if epoch % params[\"val_per_step\"]==0:\n val_loss, val_acc, val_f1, val_score, eval_time = valid_fn(model, val_loader, criterion, macs, device)\n print(f\" loss:{avg_loss:.4f} ({eval_time:.2f}s) vloss:{val_loss:.4f} vAcc:{val_acc:.4f} vF1:{val_f1:.4f} vScore:{val_score:.4f}\")\n if best_val_f1 < val_f1:\n best_val_f1 = val_f1\n else:\n print(f\" loss:{avg_loss:.4f}\")\n print(\"Finish training\")\n print(f\"best_val_f1: {best_val_f1}\")\n \n \n \ndef evaluate(params, model, val_loader, device):\n print(\"eval...\")\n criterion = F1_Focal_Loss(f1rate=0.6, gamma=2.0, weight=None) \n val_loss, val_acc, val_f1, val_score, eval_time = valid_fn(model, val_loader, criterion, params[\"macs\"], device)\n print(f\"({eval_time:.2f}s) vloss:{val_loss:.4f} vAcc:{val_acc:.4f} vF1:{val_f1:.4f} vScore:{val_score:.4f}\") \n \n \n \n \nif __name__ == \"__main__\":\n ####### hyper parameters ######\n params= {\n \"SEED\" : 111,\n \"BATCH_SIZE\" : 64,\n \"EPOCHS\" : 200,\n \"LR_start\" : 5e-5,\n \"LR_max\" : 2e-4,\n \"clip\" : 30,\n \"val_per_step\" : 1,\n \"best_val_f1\" : 0,\n \"input_size\" : 80,\n \"data_dir\" : 'input/data',\n }\n ###############################\n \n parser = argparse.ArgumentParser(description=\"Train model.\")\n parser.add_argument(\"--customized_model\", default=True, type=bool)\n parser.add_argument(\"--eval\", default=True, type=bool)\n args = parser.parse_args()\n \n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n print (f\"cuda_is_available: {torch.cuda.is_available()}\")\n \n torch.manual_seed(params[\"SEED\"])\n torch.cuda.manual_seed(params[\"SEED\"])\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n np.random.seed(params[\"SEED\"])\n random.seed(params[\"SEED\"])\n \n train_transform = A.Compose([\n A.Resize(params[\"input_size\"], params[\"input_size\"]),\n A.RandomRotate90(),\n A.HorizontalFlip(p=0.5),\n A.ShiftScaleRotate(rotate_limit=0, p=0.6),\n ToTensorV2()\n ])\n test_transform = A.Compose([\n A.Resize(params[\"input_size\"], params[\"input_size\"]),\n ToTensorV2()\n ])\n train_dataset = TrainSet(data_dir=params[\"data_dir\"], mode='train', transform=train_transform)\n val_dataset = TrainSet(data_dir=params[\"data_dir\"], mode='val', transform=test_transform)\n train_loader = DataLoader(dataset=train_dataset, batch_size=params[\"BATCH_SIZE\"], shuffle=True, num_workers=2, drop_last=True)\n val_loader = DataLoader(dataset=val_dataset, batch_size=params[\"BATCH_SIZE\"], shuffle=False, num_workers=2)\n \n if args.customized_model:\n model = shufflenet_g3_wd4(num_classes=9, pretrained=False, lastConv=True, is_custom=True)\n model.load_state_dict(torch.load('pretrained/ShuffleNet_final.pt')['model'])\n else:\n model = shufflenet_g3_wd4(num_classes=9, pretrained=True, lastConv=False)\n model.to(device)\n params[\"macs\"], par = calc_macs(model, (3,params[\"input_size\"],params[\"input_size\"]), return_params=True)\n print('Model MACs : ',params[\"macs\"])\n print('Model Params : ',par)\n \n \n if args.eval:\n evaluate(params, model, val_loader, device)\n else:\n train(params, model, train_loader, val_loader, device)","repo_name":"kws02352/Model_Compression_Boostcamp","sub_path":"test_demo.py","file_name":"test_demo.py","file_ext":"py","file_size_in_byte":4989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"73795689208","text":"from __future__ import absolute_import\n\nfrom django import forms\nfrom django.contrib import messages\nfrom django.core.urlresolvers import reverse\nfrom django.db import IntegrityError\nfrom django.http import HttpResponseRedirect\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom sentry.models import AuditLogEntry, AuditLogEntryEvent, Team\nfrom sentry.web.frontend.base import TeamView\n\n\nclass EditTeamForm(forms.ModelForm):\n slug = forms.SlugField(\n label=_('Short name'),\n help_text=_('A unique ID used to identify this team.'),\n )\n\n class Meta:\n fields = ('name', 'slug',)\n model = Team\n\n def clean_slug(self):\n value = self.cleaned_data.get('slug')\n if not value:\n return\n\n qs = Team.objects.filter(\n slug=value,\n organization=self.instance.organization,\n ).exclude(id=self.instance.id)\n if qs.exists():\n raise forms.ValidationError(\"A team with that slug already exists.\")\n\n return value\n\n\nclass TeamSettingsView(TeamView):\n required_scope = 'team:write'\n\n def get_form(self, request, team):\n return EditTeamForm(request.POST or None, instance=team)\n\n def handle(self, request, organization, team):\n form = self.get_form(request, team)\n if form.is_valid():\n try:\n team = form.save()\n except IntegrityError:\n form.errors['__all__'] = ['There was an error while saving your changes. Please try again.']\n\n if form.is_valid():\n AuditLogEntry.objects.create(\n organization=organization,\n actor=request.user,\n ip_address=request.META['REMOTE_ADDR'],\n target_object=team.id,\n event=AuditLogEntryEvent.TEAM_EDIT,\n data=team.get_audit_log_data(),\n )\n\n messages.add_message(request, messages.SUCCESS,\n _('Changes to your team were saved.'))\n\n return HttpResponseRedirect(reverse('sentry-manage-team', args=[organization.slug, team.slug]))\n\n if request.is_superuser():\n can_remove_team = True\n else:\n can_remove_team = request.access.has_team_scope(team, 'team:delete')\n\n context = {\n 'form': form,\n 'can_remove_team': can_remove_team,\n }\n\n return self.respond('sentry/teams/manage.html', context)\n","repo_name":"NetEaseGame/Sentry","sub_path":"src/sentry/web/frontend/team_settings.py","file_name":"team_settings.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"77"} +{"seq_id":"44671887785","text":"# --- Day 12: Passage Pathing ---\r\n\r\nfrom aoc_helper import load_input\r\nimport re\r\n\r\n\r\ndef find_next(path, lst):\r\n paths = []\r\n last = path[-1]\r\n firsts = [x[0] for x in lst]\r\n for i in range(firsts.count(last)):\r\n for x in lst:\r\n if x[0] == path[-1]:\r\n path.append(x[1])\r\n paths.append(path)\r\n return paths\r\n\r\n\r\nlinelist = load_input(\"day12_example1.txt\")\r\nlinelist = [x.split(\"-\") for x in linelist]\r\n\r\na = [x[0] for x in linelist]\r\nb = [x[1] for x in linelist]\r\n\r\npath = [\"start\", \"A\"]\r\npath = find_next(path, linelist)\r\npath = find_next(path, linelist)\r\n","repo_name":"lbreede/advent-of-code","sub_path":"python/2021/day_12.py","file_name":"day_12.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"} +{"seq_id":"69809752889","text":"# Ajouter une classe fusée, sensible à tous les champs gravitationnel\n# Programmer la trajectoire de la fusée\n# Apprentissage pour faire atterrir la fusée sur mars (TensorFlow?)\n\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport numpy as np\n# from scipy import io as sio\nimport math\nfrom pylab import *\n\n# ------------------------------\n# CLASSES\n# ------------------------------\nclass body:\n\t\"\"\"A planet\"\"\"\n\tdef __init__(self, N_t):\n\t\tself.name = \"planet\"\n\t\tself.x = np.zeros((int(N_t), 1), dtype=float)\n\t\tself.y = np.zeros((int(N_t), 1), dtype=float)\n\t\tself.vx = np.zeros((int(N_t), 1), dtype=float)\n\t\tself.vy = np.zeros((int(N_t), 1), dtype=float)\n\t\tself.ax = np.zeros((int(N_t), 1), dtype=float)\n\t\tself.ay = np.zeros((int(N_t), 1), dtype=float)\n\t\tself.m = 0.0\n\tdef euler(self, x_s, y_s, m_s, dt):\n\t\tr \t\t\t = math.sqrt((self.x[t-1, 0]-x_s)**2+(self.y[t-1, 0]-y_s)**2)\n\t\tF \t\t\t = -(G*self.m*m_s)/(r**2)\n\t\tself.ax[t,0] = F/self.m*(self.x[t-1,0]-x_s)/r\n\t\tself.ay[t,0] = F/self.m*(self.y[t-1,0]-y_s)/r\n\t\tself.vx[t,0] = self.vx[t-1,0] + dt*self.ax[t-1,0]\n\t\tself.vy[t,0] = self.vy[t-1,0] + dt*self.ay[t-1,0]\n\t\tself.x[t,0] \t = self.x[t-1,0] + dt*self.vx[t-1,0]\n\t\tself.y[t,0] = self.y[t-1,0] + dt*self.vy[t-1,0]\n\tdef verlet(self, x_s, y_s, m_s, dt):\n\t\tr \t\t\t = math.sqrt((self.x[t-1, 0]-x_s)**2+(self.y[t-1, 0]-y_s)**2)\n\t\tF \t\t\t = -(G*self.m*m_s)/(r**2)\n\t\tax0 \t\t\t = F/self.m*(self.x[t-1,0]-x_s)/r\n\t\tay0\t\t\t = F/self.m*(self.y[t-1,0]-y_s)/r\n\t\tself.x[t,0] \t = self.x[t-1,0] + dt*self.vx[t-1,0] + 0.5*dt**2*ax0\n\t\tself.y[t,0] \t = self.y[t-1,0] + dt*self.vy[t-1,0] + 0.5*dt**2*ay0\n\t\tr \t\t\t = math.sqrt((self.x[t, 0]-x_s)**2+(self.y[t, 0]-y_s)**2)\n\t\tF \t\t\t = -(G*self.m*m_s)/(r**2)\n\t\tself.ax[t,0] = F/self.m*(self.x[t,0]-x_s)/r\n\t\tself.ay[t,0] = F/self.m*(self.y[t,0]-y_s)/r\n\t\tself.vx[t,0]\t = self.vx[t-1,0] + 0.5*dt*(ax0+self.ax[t,0])\n\t\tself.vy[t,0]\t = self.vy[t-1,0] + 0.5*dt*(ay0+self.ay[t,0])\n\n# ------------------------------\n# CONSTANTES\n# ------------------------------\n# Numerical constants\nN_t \t \t = 100000\t\t\t\t\t\t\t\t# [-] \t\t Iteration number\ndt \t \t = 3600.0*24.0\t\t\t\t\t\t\t# [s] \t\t Time step (1 day)\nua \t \t = 149597870700\t\t\t\t\t\t# [m] \t\t Unité astronomique (distance Terre-Soleil)\num \t\t\t = 1.989e30\t\t\t\t\t\t\t# [kg]\t\t Unité massique (masse du Soleil)\nme\t\t\t = 5.972e24\t\t\t\t\t\t\t# [kg]\t\t Masse terrestre\n# Physic constants\nG \t \t = 6.67408e-11 \t\t\t\t\t\t# [m3/kg/s2] Gravitational constant\n# Planets initialization\nearth1 = body(N_t)\nearth1.m \t = 100*me\nearth1.x[0,0] = ua/2\n\nearth2 \t = body(N_t)\nearth2.m \t = me\nearth2.x[0,0] = -ua/2\t\n\nearth1.vy[0,0]= -math.sqrt(-G*earth2.m*earth2.x[0,0]/(-earth2.x[0,0]+earth1.x[0,0])**2)\nearth2.vy[0,0]= math.sqrt(G*earth1.m*earth1.x[0,0]/(-earth2.x[0,0]+earth1.x[0,0])**2)\n\n# ------------------------------\n# CALCULS DE TRAJECTOIRE\n# ------------------------------\nfor t in range(1, int(N_t)):\n\tearth1.verlet(earth2.x[t-1,0], earth2.y[t-1,0], earth2.m, dt)\n\tearth2.verlet(earth1.x[t-1,0], earth1.y[t-1,0], earth1.m, dt)\n\n# ------------------------------\n# ANIMATION\n# ------------------------------\nplt.style.use('dark_background')\nfig = plt.figure()\nax = plt.axes(xlim=(-1, 1), ylim=(-1, 6))\n\nplt.xlabel('x [ua]')\nplt.ylabel('y [ua]')\nplanet1, = plt.plot([], [], 'bo')\nplanet2, = plt.plot([], [], 'ro')\n\ndef init():\n\tplanet1.set_data([], [])\n\tplanet2.set_data([], [])\n\treturn planet1, planet2\ndef animate(i):\n\tx = earth1.x[50*(i),0]/ua\n\ty = earth1.y[50*(i),0]/ua\n\tplanet1.set_data(x, y)\n\tx = earth2.x[50*(i),0]/ua\n\ty = earth2.y[50*(i),0]/ua\n\tplanet2.set_data(x, y)\n\treturn planet1, planet2\n\nanim = animation.FuncAnimation(fig, animate, init_func=init, frames=int(N_t), interval=1, blit=True)\nplt.show()\n\n# ------------------------------\n# AFFICHAGE\n# ------------------------------\nplt.style.use('dark_background')\n\nsubplot(121)\nplt.plot([x_e / ua for x_e in earth1.x], [y_e / ua for y_e in earth1.y], color=\"blue\", label=\"body 1\")\nplt.plot([x_e / ua for x_e in earth2.x], [y_e / ua for y_e in earth2.y], color=\"red\", label=\"body 2\")\nplt.legend(loc='upper left')\nplt.axis('equal')\nplt.xlabel('x [ua]')\nplt.ylabel('y [ua]')\n\nsubplot(222)\nt = np.arange(0.0,dt*len(earth1.vy),dt)\nplt.plot([t_e / (dt) for t_e in t], [y_e / 1e-3 for y_e in earth1.vx], color=\"blue\", label=\"body 1\")\nplt.plot([t_e / (dt) for t_e in t], [y_e / 1e-3 for y_e in earth2.vx], color=\"red\", label=\"body 2\")\nplt.legend(loc='upper left')\nplt.xlabel('t [days]')\nplt.ylabel('v_x [km/s]')\n\nsubplot(224)\nt = np.arange(0.0,dt*len(earth1.vy),dt)\nplt.plot([t_e / (dt) for t_e in t], [y_e / 1e-3 for y_e in earth1.vy], color=\"blue\", label=\"body 1\")\nplt.plot([t_e / (dt) for t_e in t], [y_e / 1e-3 for y_e in earth2.vy], color=\"red\", label=\"body 2\")\nplt.legend(loc='upper left')\nplt.xlabel('t [days]')\nplt.ylabel('v_y [km/s]')\n\nplt.show()\n","repo_name":"FluidElytra/orbits","sub_path":"orbits.py","file_name":"orbits.py","file_ext":"py","file_size_in_byte":4839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"29950015549","text":"import tensorflow as tf\nfrom tensorflow import keras\nfrom PIL import Image, ImageDraw, ImageFont\nimport numpy as np\nimport cv2\n\nfrom helpers import YoloConfig\nfrom yolo3.model import yolo_eval, yolo_body, tiny_yolo_body\n\nfont = ImageFont.load_default()\n\nSTANDARD_COLORS = [\n 'AliceBlue', 'Chartreuse', 'Aqua', 'Aquamarine', 'Azure', 'Beige', 'Bisque',\n 'BlanchedAlmond', 'BlueViolet', 'BurlyWood', 'CadetBlue', 'AntiqueWhite',\n 'Chocolate', 'Coral', 'CornflowerBlue', 'Cornsilk', 'Crimson', 'Cyan',\n 'DarkCyan', 'DarkGoldenRod', 'DarkGrey', 'DarkKhaki', 'DarkOrange',\n 'DarkOrchid', 'DarkSalmon', 'DarkSeaGreen', 'DarkTurquoise', 'DarkViolet',\n 'DeepPink', 'DeepSkyBlue', 'DodgerBlue', 'FireBrick', 'FloralWhite',\n 'ForestGreen', 'Fuchsia', 'Gainsboro', 'GhostWhite', 'Gold', 'GoldenRod',\n 'Salmon', 'Tan', 'HoneyDew', 'HotPink', 'IndianRed', 'Ivory', 'Khaki',\n 'Lavender', 'LavenderBlush', 'LawnGreen', 'LemonChiffon', 'LightBlue',\n 'LightCoral', 'LightCyan', 'LightGoldenRodYellow', 'LightGray', 'LightGrey',\n 'LightGreen', 'LightPink', 'LightSalmon', 'LightSeaGreen', 'LightSkyBlue',\n 'LightSlateGray', 'LightSlateGrey', 'LightSteelBlue', 'LightYellow', 'Lime',\n 'LimeGreen', 'Linen', 'Magenta', 'MediumAquaMarine', 'MediumOrchid',\n 'MediumPurple', 'MediumSeaGreen', 'MediumSlateBlue', 'MediumSpringGreen',\n 'MediumTurquoise', 'MediumVioletRed', 'MintCream', 'MistyRose', 'Moccasin',\n 'NavajoWhite', 'OldLace', 'Olive', 'OliveDrab', 'Orange', 'OrangeRed',\n 'Orchid', 'PaleGoldenRod', 'PaleGreen', 'PaleTurquoise', 'PaleVioletRed',\n 'PapayaWhip', 'PeachPuff', 'Peru', 'Pink', 'Plum', 'PowderBlue', 'Purple',\n 'Red', 'RosyBrown', 'RoyalBlue', 'SaddleBrown', 'Green', 'SandyBrown',\n 'SeaGreen', 'SeaShell', 'Sienna', 'Silver', 'SkyBlue', 'SlateBlue',\n 'SlateGray', 'SlateGrey', 'Snow', 'SpringGreen', 'SteelBlue', 'GreenYellow',\n 'Teal', 'Thistle', 'Tomato', 'Turquoise', 'Violet', 'Wheat', 'White',\n 'WhiteSmoke', 'Yellow', 'YellowGreen'\n]\n\ndef letterbox_image(image, size):\n '''resize image with unchanged aspect ratio using padding'''\n iw, ih = image.size\n w, h = size\n scale = min(w/iw, h/ih)\n nw = int(iw*scale)\n nh = int(ih*scale)\n\n image = image.resize((nw,nh), Image.BICUBIC)\n new_image = Image.new('RGB', size, (128,128,128))\n new_image.paste(image, ((w-nw)//2, (h-nh)//2))\n return new_image\n\n\ndef preprocess_image(image_array, config):\n\n ih, iw, _c = image_array.shape\n h, w = config.input_shape\n\n # if not random:\n # resize image\n scale = min(w/iw, h/ih)\n nw = int(iw*scale)\n nh = int(ih*scale)\n dx = (w-nw)//2\n dy = (h-nh)//2\n\n image = cv2.resize(image_array, (nw, nh), interpolation=cv2.INTER_CUBIC)\n new_image = np.ones(shape=(h,w,3), dtype=np.uint8)*128\n new_image[dy:dy+nh,dx:dx+nw,:] = image\n return new_image, scale, dy, dx\n\n\ndef annotate_image(image, bboxes, scores, labels, threshold=0.5, label_dict=None):\n image = Image.open(image)\n Imagedraw = ImageDraw.Draw(image)\n # thickness = (image.size[0] + image.size[1]) // 300\n\n for box, label, score in zip(bboxes, labels, scores):\n if score < threshold:\n continue\n\n top,left,bottom,right = box\n\n top = max(0, np.floor(top + 0.5).astype('int32'))\n left = max(0, np.floor(left + 0.5).astype('int32'))\n bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))\n right = min(image.size[0], np.floor(right + 0.5).astype('int32'))\n # print(label, (left, top), (right, bottom))\n\n label_to_display = label\n if isinstance(label_dict, dict):\n label_to_display = label_dict[label]\n\n caption = \"{}|{:.3f}\".format(label_to_display, score)\n #draw_caption(draw, b, caption)\n\n colortofill = STANDARD_COLORS[label]\n Imagedraw.rectangle([left,top,right,bottom], fill=None, outline=colortofill, width=3)\n\n # for i in range(thickness):\n # Imagedraw.rectangle([left + i, top + i, right - i, bottom - i], fill=None, outline=colortofill)\n\n display_str_heights = font.getsize(caption)[1]\n # Each display_str has a top and bottom margin of 0.05x.\n total_display_str_height = (1 + 2 * 0.05) * display_str_heights\n\n if top > total_display_str_height:\n text_bottom = top\n else:\n text_bottom = bottom + total_display_str_height\n\n text_width, text_height = font.getsize(caption)\n margin = np.ceil(0.05 * text_height)\n Imagedraw.rectangle([(left, text_bottom-text_height-2*margin), (left+text_width,text_bottom)], fill=colortofill)\n\n Imagedraw.text((left+margin, text_bottom-text_height-margin),caption,fill='black',font=font)\n\n return image\n\ndef freeze_model(model_path, config, num_classes, max_boxes=20, score_threshold=.6,iou_threshold=.5):\n # model_path = os.path.expanduser(self.model_path)\n # assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.'\n\n # Load model, or construct model and load weights.\n num_anchors = len(config.anchors)\n # num_classes = len(self.class_names)\n # is_tiny_version = num_anchors==6 # default setting\n yolo_model = keras.models.load_model(model_path, compile=False)\n\n boxes, scores, classes = yolo_eval(\n \tyolo_model.outputs, \n \tconfig.anchors,\n num_classes, \n config.input_shape,\n anchor_mask=config.anchor_mask,\n max_boxes=config.max_boxes,\n score_threshold=score_threshold, \n iou_threshold=iou_threshold)\n\n prediction_model = keras.models.Model(yolo_model.input, [boxes, scores, classes])\n\n return prediction_model\n\ndef detect_image(model, image, config):\n \n\n boxed_image, scale, dy, dx = preprocess_image(np.array(image), config)\n\n image_data = boxed_image.astype(keras.backend.floatx())\n\n #print(image_data.shape)\n image_data /= 255.\n image_data = np.expand_dims(image_data, 0) # Add batch dimension.\n\n boxes, scores, classes = model.predict(image_data)\n\n boxes[:,0] = boxes[:,0]-dy\n boxes[:,2] = boxes[:,2]-dy\n\n boxes[:,1] = boxes[:,1]-dx\n boxes[:,3] = boxes[:,3]-dx\n\n return boxes/scale, scores, classes\n","repo_name":"pk00095/tf-yolo","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":6077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"22069380740","text":"\"\"\"Implementation of the T5 Model for Response and Question Generation.\n\n(DataParallel Mode)\n\"\"\"\n\nfrom lib2to3.pgen2 import token\nimport math\nimport os\n\nimport torch\nfrom transformers import Adafactor, T5ForConditionalGeneration, T5Tokenizer\n\nfrom src.re_qa_model import (HyperParameters, clear_cache, load_module,\n set_random_seed)\n\n\ndef save(model: torch.nn.Module, path: str) -> None:\n \"\"\"Save the model to task at the specified path.\"\"\"\n torch.save(model.state_dict(), path)\n\n\n# MODEL_NAME = \"t5-base\"\n\n\nclass T5QA(object):\n \"\"\"Wrapper class around the T5 Model.\"\"\"\n\n def __init__(self, cfg: HyperParameters):\n self.config = cfg\n\n MODEL_NAME = self.config.model_name\n\n set_random_seed(cfg.seed)\n\n # Check the gpu actually exists.\n cfg.gpu = cfg.gpu and torch.cuda.is_available()\n self.device = torch.device(\"cuda\" if cfg.gpu else \"cpu\")\n\n if cfg.mode == \"train\":\n tokenizer = T5Tokenizer.from_pretrained(MODEL_NAME)\n\n # Construct model\n model = torch.nn.DataParallel(\n T5ForConditionalGeneration.from_pretrained(MODEL_NAME)\n )\n model.to(self.device)\n\n # Configurations suggested by the paper.\n self.optimizer = Adafactor(\n model.parameters(),\n lr=cfg.learning_rate,\n eps=(1e-30, 1e-3),\n clip_threshold=1.0,\n decay_rate=-0.8,\n beta1=None,\n weight_decay=0.0,\n relative_step=False,\n scale_parameter=False,\n warmup_init=False,\n )\n\n if not os.path.exists(cfg.model_path):\n os.makedirs(cfg.model_path)\n self.model_path = os.path.join(cfg.model_path, \"model\")\n\n elif cfg.mode in [\"test\", \"inference\"]:\n tokenizer = T5Tokenizer.from_pretrained(MODEL_NAME)\n model = T5ForConditionalGeneration.from_pretrained(MODEL_NAME)\n model.to(self.device)\n\n self.model_path = os.path.join(cfg.model_path, \"model\")\n load_module(model, self.model_path, cfg.checkpoint)\n\n self.model = model\n self.tokenizer = tokenizer\n\n def save(self, checkpoint_name: str):\n \"\"\"Save the encoder model to the specified path name.\"\"\"\n path = self.model_path + \"_\" + checkpoint_name\n save(self.model, path + \"_model\")\n\n def relation_extraction_predict(self, batch):\n clear_cache()\n # disable dropout\n self.model.eval()\n\n loss_fct = torch.nn.CrossEntropyLoss(ignore_index=-100, reduction=\"none\")\n if self.config.gpu:\n loss_fct = loss_fct.to(self.device)\n\n input_ids = batch[\"input_ids\"]\n input_mask = batch[\"attention_mask\"]\n target_mask = batch[\"target_attention_mask\"]\n labels = batch[\"labels\"]\n if self.config.gpu:\n input_ids = input_ids.to(self.device)\n input_mask = input_mask.to(self.device)\n target_mask = target_mask.to(self.device)\n labels = labels.to(self.device)\n\n output = self.model(\n input_ids=input_ids,\n attention_mask=input_mask,\n decoder_attention_mask=target_mask,\n decoder_input_ids=self.model._shift_right(labels),\n labels=None,\n )\n\n log_p = -loss_fct(\n output.logits.view(-1, output.logits.size(-1)),\n labels.view(-1),\n )\n\n # b: batch size * num_unseen_relations\n # sz: sequence size\n # v: vocab size\n b, sz, v = output.logits.size()\n log_p = log_p.view(b, sz)\n good_log_p = log_p.masked_fill_(labels == -100, 0.0)\n answer_log_p = torch.sum(good_log_p, dim=1).squeeze().cpu().detach().numpy()\n\n for index in range(b):\n relation_log_p = answer_log_p[index]\n output_batch = {\n \"relation_log_p\": relation_log_p,\n }\n yield output_batch\n\n def predict(self, batch):\n clear_cache()\n # disable dropout\n self.model.eval()\n\n input_ids = batch[\"input_ids\"]\n input_mask = batch[\"attention_mask\"]\n if self.config.gpu:\n input_ids = input_ids.to(self.device)\n input_mask = input_mask.to(self.device)\n\n predictions = self.model.generate(\n input_ids=input_ids,\n attention_mask=input_mask,\n )\n\n # all special tokens including will be removed\n predictions_str = self.tokenizer.batch_decode(\n predictions, skip_special_tokens=True\n )\n input_str = self.tokenizer.batch_decode(input_ids, skip_special_tokens=True)\n for index in range(len(predictions_str)):\n pred_str = predictions_str[index]\n pred_str = pred_str if pred_str != \"\" else \"\"\n output_batch = {\n \"predictions_str\": pred_str,\n \"input_str\": input_str[index],\n }\n yield output_batch\n\n def train(self, batch):\n # Free memory in GPU, very important!\n clear_cache()\n # Turn on training mode which enables dropout.\n self.model.train()\n self.optimizer.zero_grad()\n\n input_ids = batch[\"input_ids\"]\n input_mask = batch[\"attention_mask\"]\n target_mask = batch[\"target_attention_mask\"]\n labels = batch[\"labels\"]\n if self.config.gpu:\n input_ids = input_ids.to(self.device)\n input_mask = input_mask.to(self.device)\n target_mask = target_mask.to(self.device)\n labels = labels.to(self.device)\n\n output = self.model(\n input_ids=input_ids,\n attention_mask=input_mask,\n decoder_attention_mask=target_mask,\n labels=labels,\n )\n\n # mean loss from multiple GPUs\n loss = output.loss.mean()\n loss_value = loss.item()\n\n # is loss nan? don't backpropagate!\n if math.isnan(loss):\n return {\"loss_value\": loss_value}\n\n # BackProp\n loss.backward()\n\n # Optimize\n self.optimizer.step()\n\n return {\"loss_value\": loss_value}\n","repo_name":"fyshelab/QA-ZRE","sub_path":"src/question_response_generation/t5_model.py","file_name":"t5_model.py","file_ext":"py","file_size_in_byte":6235,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"1657727986","text":"import pandas as pd\nfrom torch_geometric.data import Batch, HeteroData\nimport plotly.express as px\nfrom plotly.graph_objects import FigureWidget\n\nclass GraphPlot:\n def __init__(self,\n planes: list[str],\n classes: list[str]):\n self._planes = planes\n self._classes = classes\n self._labels = pd.CategoricalDtype(classes, ordered=True)\n self._cmap = { c: px.colors.qualitative.Plotly[i] for i, c in enumerate(classes) }\n self._data = None\n self._df = None\n\n def to_dataframe(self, data: HeteroData):\n def to_categorical(arr):\n return pd.Categorical.from_codes(codes=arr, dtype=self._labels)\n if isinstance(data, Batch):\n raise Exception('to_dataframe does not support batches!')\n dfs = []\n for p in self._planes:\n plane = data[p].to_dict()\n df = pd.DataFrame(plane['id'], columns=['id'])\n df['plane'] = p\n df[['wire','time']] = plane['pos']\n df['y_filter'] = plane['y_semantic'] != -1\n mask = df.y_filter.values\n df['y_semantic'] = to_categorical(plane['y_semantic'])\n df['y_instance'] = plane['y_instance'].numpy()\n if 'x_semantic' in plane.keys():\n df['x_semantic'] = to_categorical(plane['x_semantic'].argmax(dim=-1).detach())\n df[self._classes] = plane['x_semantic'].detach()\n if 'x_filter' in plane.keys():\n df['x_filter'] = plane['x_filter'].detach()\n dfs.append(df)\n df = pd.concat(dfs)\n md = data['metadata']\n df['run'] = md.run.item()\n df['subrun'] = md.subrun.item()\n df['event'] = md.event.item()\n return df\n\n def plot(self,\n data: HeteroData,\n target: str = 'hits',\n how: str = 'none',\n filter: str = 'none',\n width: int = None,\n height: int = None) -> FigureWidget:\n\n if data is not self._data:\n self._data = data\n self._df = self.to_dataframe(data)\n\n # no colour\n if target == 'hits':\n opts = {\n 'title': 'Graph hits'\n }\n\n # semantic labels\n elif target == 'semantic':\n if how == 'true':\n opts = {\n 'title': 'True semantic labels',\n 'labels': { 'y_semantic': 'Semantic label' },\n 'color': 'y_semantic',\n 'color_discrete_map': self._cmap\n }\n elif how == 'pred':\n opts = {\n 'title': 'Predicted semantic labels',\n 'labels': { 'x_semantic': 'Semantic label' },\n 'color': 'x_semantic',\n 'color_discrete_map': self._cmap\n }\n elif how in self._classes:\n opts = {\n 'title': f'Predicted semantic label strength for {how} class',\n 'labels': { how: f'{how} probability' },\n 'color': how,\n 'color_continuous_scale': px.colors.sequential.Reds\n }\n else:\n raise Exception('for semantic labels, \"how\" must be one of \"true\", \"pred\" or the name of a class.')\n\n # instance labels\n elif target == 'instance':\n if how == 'true':\n opts = {\n 'title': 'True instance labels',\n 'labels': { 'y_instance': 'Instance label' },\n 'color': 'y_instance'\n }\n elif how == 'pred':\n opts = {\n 'title': 'Predicted instance labels',\n 'labels': { 'x_instance': 'Instance label' },\n 'color': 'x_instance'\n }\n else:\n raise Exception('for instance labels, \"how\" must be one of \"true\" or \"pred\".')\n\n # filter labels\n elif target == 'filter':\n if how == 'true':\n opts = {\n 'title': 'True filter labels',\n 'labels': { 'y_filter': 'Filter label' },\n 'color': 'y_filter',\n 'color_continuous_scale': px.colors.sequential.Reds\n }\n elif how == 'pred':\n opts = {\n 'title': 'Predicted filter labels',\n 'labels': { 'x_filter': 'Filter label' },\n 'color': 'x_filter',\n 'color_continuous_scale': px.colors.sequential.Reds\n }\n else:\n raise Exception('for filter labels, \"how\" must be one of \"true\" or \"pred\".')\n\n else:\n raise Exception('\"target\" must be one of \"hits\", \"semantic\", \"instance\" or \"filter\".')\n\n if filter == 'none':\n df = self._df\n elif filter == 'true':\n df = self._df[self._df.y_filter.values]\n opts['title'] += ' (filtered by truth)'\n elif filter == 'pred':\n df = self._df[self._df.x_filter > 0.5]\n opts['title'] += ' (filtered by prediction)'\n else:\n raise Exception('\"filter\" must be one of \"none\", \"true\" or \"pred.')\n\n fig = px.scatter(df, x='wire', y='time', facet_col='plane',\n width=width, height=height, **opts)\n fig.update_xaxes(matches=None)\n for a in fig.layout.annotations:\n a.text = a.text.replace('plane=', '')\n return FigureWidget(fig)","repo_name":"vhewes/pynuml","sub_path":"pynuml/plot/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":5589,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"77"} +{"seq_id":"70659300728","text":"\n# coding: utf-8\n\n# In[ ]:\n\n\nfrom jove.DotBashers import is_consistent_nfa\nfrom jove.TransitionSelectors import *\nfrom jove.SysConsts import *\nfrom jove.SystemImports import *\nfrom jove.ShrinkStates import *\nfrom jove.Def_DFA import mk_dfa # used in nfa2dfa\n\n\n# # Definitions of NFA routines\n\n# __We will follow Kozen and endow an NFA with multiple start states __\n# \n# This will allow the NFA to be more naturally handled. For instance, the reverse of a DFA is an NFA. When we reverse a DFA, all its final states become initial states of the NFA (that models the reversed language). There are 2 ways to handle this:\n# \n# 1. Introduce a fake new initial state and jump from it via $\\varepsilon$ onto (what were the final state of the DFA).\n# \n# 2. Don't introduce the fake new initial state, but rather allow the NFA to start from all of F being really its start state.\n# \n# We prefer the latter.\n# \n# __So now, following Kozen, we have__\n# \n# \n# An NFA is a quintuple $(Q,\\Sigma,\\delta,Q_0,F)$, where:\n# \n# * $Q$ is a _finite nonempty_ set of states.\n# \n# * $\\Sigma$ is a _finite nonempty_ alphabet containing _symbols_.\n# \n# * $\\delta$ is a (partial)\n# \ttransition function, containing a set of _transitions_. The transitions take\n# a pair from $Q\\times \\Sigma$ and return a __subset__ of states in $Q$. All this is succinctly\n# captured by writing\n# $\\delta: Q\\times \\Sigma \\rightarrow 2^Q$. \n# Here we use $2^Q$ to denote the powerset of $Q$.\n# \n# \n# * $Q_0\\subseteq Q$, is __a set of initial states__. Notice that we change from q0 (or $q_0$) which is what you find books such as Sipser and Linz using.\n# \n# \n# * $F\\subseteq Q$ is a _finite_ (and _possibly empty_) set of\n# \tfinal (or _accepting_) states. These are shown as double-circled nodes in the graph of a DFA. \n# \n# > There is no other change. I.e. $\\delta$ remains the same as before.\n# > It is that when an NFA starts, it can find itself in a set of start states.\n# > Most NFAs start from a __singleton__ Q0, which is then, effectively, an NFA\n# that matches most books say.\n# \n# Some terminology:\n# \n# > We call $Q$,$\\Sigma$, $\\delta$, $Q_0$, and $F$ the **_traits_** of the NFA.\n# \n# > We will call an NFA **_structurally consistent_** or simply **\"consistent\"** if its traits pass the aforesaid checks.\n# \n# \n# Here is how the checks will be broken down:\n# \n# * The supplied $\\delta$ function will be checked to see if it has allowed domain and range points. \n# - The domain points must be a subset of $Q\\times \\Sigma$\n# - The range points must be a subset of $2^Q$\n# We do no insist that the supplied $\\delta$ be total.\n# \n# * $Q_0\\subseteq Q$, is _the_ initial state.\n# \n# * $F\\subseteq Q$ is a _finite_ (and _possibly empty_) set of\n# \tfinal (or _accepting_) states. \n# \n# We will often use the state set({}) to be the equivalent of a black-hole state for an NFA.\n\n# # Making NFA\n\n# In[ ]:\n\n\ndef mk_nfa(Q, Sigma, Delta, Q0, F):\n \"\"\"Check for structural consistency of the given NFA traits.\n If the check passes, make and return an NFA.\n \"\"\"\n newNFA = {\"Q\":Q, \"Sigma\":Sigma, \"Delta\":Delta, \"Q0\":Q0, \"F\":F}\n assert(\n is_consistent_nfa(newNFA)\n ), \"NFA given to mk_nfa is not consistent. Plz check its components.\"\n return(newNFA)\n\n\n# In[ ]:\n\n\n\ndef totalize_nfa(N):\n \"\"\"In : NFA N\n Out: Totalized NFA\n Given a partially specified NFA, make it total by \n transitioning to state set({}) wherever the incoming \n Delta has gaps. This is done for an NFA only for things \n like printing.\n \"\"\"\n assert(\n is_consistent_nfa(N)\n ), \"NFA given to totalize_nfa is not consistent.\"\n Sigma_w_Eps = (N[\"Sigma\"] | {\"\"}) # Extended Alphabet\n add_delta = { (q,c) : set({}) \n for q in N[\"Q\"] \n for c in Sigma_w_Eps \n if (q,c) not in N[\"Delta\"] }\n #\n add_delta.update(N[\"Delta\"])\n #\n return {\"Q\" : N[\"Q\"],\n \"Sigma\": N[\"Sigma\"],\n \"Delta\": add_delta,\n \"Q0\" : N[\"Q0\"],\n \"F\" : N[\"F\"]}\n\n\n# In[ ]:\n\n\ndef apply_h_dfa(D, h):\n \"\"\"Given a DFA D and a homomorphism h on Sigma* (as a lambda from chars to\n chars) where Sigma is D's alphabet, return an NFA with the homomorphism\n applied to D (essentially to D's Sigma and Delta).\n \"\"\"\n deltaL = list(\n map(lambda x: ((x[0][0], h(x[0][1])), x[1]), D[\"Delta\"].items()))\n # If we have two targets for same key, make a set of the targets\n NFADelta = dict([(x, {y for (z,y) in deltaL if z==x}) for (x,w) in deltaL]) \n return mk_nfa(\n D[\"Q\"], \n set(map(h,D[\"Sigma\"])),\n NFADelta,\n {D[\"q0\"]},\n D[\"F\"]) \n\n\n# # Stepping and Running NFA\n# \n# Now that we've defined NFA and allied actions such as consistency checking and printing, let's write functions to step and run them.\n# \n# * How the state transition function $\\delta$ \"works\"\n# - captured in step_nfa\n\n# In[ ]:\n\n\ndef step_nfa(N, q, c):\n \"\"\"In : N (consistent NFA)\n q (state in N)\n c (symbol in N's sigma or \"\")\n Out: The set of states reached via N's Delta.\n EClosure is NOT performed.\n If the move is not defined, return {}.\n \"\"\" \n assert(\n c in (N[\"Sigma\"] | {\"\"})\n ), \"c given to step_nfa not in Sigma.\"\n assert(\n q in N[\"Q\"]\n ), \"q given to step_nfa not in Q.\"\n \n \n # We have to run it wrt the total version of the NFA. \n # Since that is expensive to do each time, special-case this check. \n if (q,c) in N[\"Delta\"].keys():\n return N[\"Delta\"][(q,c)]\n else:\n # If a move is undefined, it is a transition to the empty set\n return set({}) \n\n\n# ## Now we define the $\\hat{\\delta}$ function that runs an NFA on a string\n# \n# * This is captured in run_nfa\n# \n# * This is more elaborate than with a DFA because we need to account for Epsilon moves\n# * So we will define routines to compute the E-closure of a state\n# \n# - The set of states reachable by traversing Epsilon edges\n# \n# * Our algorithm is this:\n# \n# * Eclose the given set of states S\n# - If given string s is \"\", we are done (retn Eclosed set of states)\n# - Else take step via s[0]; Eclose it to get S'; run s[1:] on S'\n\n# In[ ]:\n\n\ndef run_nfa(N, S, s, chatty=False):\n \"\"\"In : N (consistent NFA)\n S (SET of states S belonging to N's states)\n s (string over N's alphabet)\n Out: SET of states reached after processing s.\n Run the NFA starting with a SET of states S on string,\n with EClosure wherever necessary. Return set of states reached.\n \"\"\" \n # First EClose the given set of states S.\n S = Eclosure(N, S)\n if s==\"\":\n # run_nfa returns S if nothing to process\n return S\n else:\n # else one step via s[0]; return Eclosure of the resulting states\n return run_nfa(N, ec_step_nfa(N, S, s[0], chatty), s[1:], chatty)\n\n\n# In[ ]:\n\n\ndef ec_step_nfa(N, S, c, chatty=False):\n \"\"\"Helper for run_nfa\n ---\n In : N (consistent NFA)\n S (EClosed set of states)\n c (character in N's alphabet; does not equal \"\")\n chatty (Boolean): Verbose-mode optional parameter\n Return Eclosure of all states one \"c\" step away from S. \n \"\"\"\n post_c_state_sets = list(map(lambda st: step_nfa(N, st, c), S))\n \n # Take union of state sets contained in post_c_states\n # basis case set({}) added to make reduction succeed \n post_c_states = reduce(lambda x,y: set(x) | set(y), \n post_c_state_sets, \n set({}))\n \n # Eclose from post-c-states \n Eclosed_post_c_states = Eclosure(N, post_c_states)\n \n # Return final set of states after second Eclosure \n if chatty:\n print(\"States reached = \", Eclosed_post_c_states)\n return Eclosed_post_c_states\n\ndef Eclosure(N, S):\n \"\"\"In : N (consistent NFA)\n S (set of states of NFA to be Eclosed)\n Out: Eclosure of S (set of states).\n \"\"\"\n return Echelp(N, S, set({}))\n\ndef Echelp(Nfa, Allsofar, Previous):\n \"\"\"Helper for Eclosure\n ---\n In : Nfa (consistent NFA)\n Allsofar (set of states reached so far)\n Previous (set of states reached previously) \n len(N[\"Delta\"].items()) is the longest chain in the NFA;\n We will end up iterating that much. \n \"\"\"\n # Fixpoint reached; return Allsofar\n if (Allsofar == Previous):\n return Allsofar\n else:\n # When we apply step_nfa, we get state sets; \n # form a list of those.\n post_eps_state_sets = list(map(lambda q: \n step_nfa(Nfa, q, \"\"), \n Allsofar))\n \n # Now OR-reduce 'em; basis case of set({}) \n # added to make reduction succeed \n post_eps_states = reduce(lambda x, y: set(x) | set(y), \n post_eps_state_sets,\n set({}))\n \n # Recurse till fixpoint reached\n return Echelp(Nfa = Nfa, \n Allsofar = set(post_eps_states) | \n set(Allsofar), \n Previous = Allsofar)\n\n\n# Now we define NFA acceptance. We provide a silent version and a chatty (verbose) version called accepts_nfav that tells you HOW the acceptance was concluded.\n\n# In[ ]:\n\n\ndef accepts_nfa(N, s, chatty=False):\n \"\"\"NFA acceptance.\n Input : N : given NFA\n s : given string\n chatty : Boolean (prints accepting path,\n which is the state-sets encountered).\n \"\"\"\n Q0 = N[\"Q0\"]\n if (run_nfa(N, Q0, s, chatty) & N[\"F\"]) != set({}):\n if chatty:\n print(\"NFA accepts '\" + s + \n \"' by reaching \" + \n str(run_nfa(N, Q0, s, False)))\n return True\n else:\n if chatty:\n print(\"NFA rejects '\" + s + \"'\")\n return False\n\n\n# # NFA to DFA conversion\n# \n# This is one of the most important of NFA-related operations. It will have a lot in common with running NFA where the computation of EClosure was involved in every step.\n# \n# \n\n# In[ ]:\n\n\ndef nfa2dfa(N, STATENAME_MAXSIZE=20): #--default state size kept\n \"\"\"In : N (consistent NFA), and optional STATENAME_MAXSIZE\n for the generated DFA states\n Out: A consistent DFA that is language-equivalent to N.\n \"\"\"\n assert(\n is_consistent_nfa(N)\n ), \"nfa2dfa was given an inconsistent NFA.\"\n # EClose the starting state of the NFA\n EC = Eclosure(N, N[\"Q0\"])\n return n2d(Frontier=[EC], Visited=[EC], Delta=dict({}), Nfa=N,\n STATENAME_MAXSIZE=STATENAME_MAXSIZE)\n\n\n# In[ ]:\n\n\ndef n2d(Frontier, Visited, Delta, Nfa, STATENAME_MAXSIZE=20):\n \"\"\"Helper for nfa2dfa.\n ---\n In : Frontier (list of state sets; initially Eclosed Q0)\n Visited (list of visited state sets; initially Eclosed Q0)\n Delta (the DFA transition function being formed)\n Nfa (the NFA being converted)\n STATENAME_MAXSIZE : number\n Helper to nfa2dfa. Given a (BFS) frontier, a Visited\n set of states, the Delta being formed, and NFA Nfa, see\n if all new moves are in Visited: \n do last gasp of Delta update; make and return a DFA;\n else: extend Frontier, Visited, Delta; recurse.\n \"\"\"\n All_c_Moves = [ ((Q,c),ec_step_nfa(Nfa,Q,c)) \n for Q in Frontier \n for c in Nfa[\"Sigma\"] ]\n New_c_Moves = list(filter(lambda QcQ: trTrg(QcQ) not in Visited, \n All_c_Moves)) \n if New_c_Moves == []:\n # Add last-gasp c-moves that curl back!\n last_gasp_c_moves = dict([ ((mkSSnam(Qfrom),c),mkSSnam(Qto)) \n for ((Qfrom, c), Qto) in All_c_Moves ])\n Delta.update(last_gasp_c_moves)\n \n # DFA states are visited states\n DFA_Q = { mkSSnam(Q) for Q in Visited }\n \n # Retain alphabet\n DFA_Sigma = Nfa[\"Sigma\"]\n \n # Delta is ready to go\n DFA_Delta = Delta\n \n # DFA starts at Eclosure of Nfa's Q0 set of states\n DFA_q0 = mkSSnam(Eclosure(Nfa, Nfa[\"Q0\"]))\n \n # DFA's final states are those in visited that contain an NFA \n # F-state but don't retain any empty sets, in case the NFA given \n # has no F-states!\n # This is another corner-case (i.e. don't shove-in black hole \n # states!)\n DFA_F = set(map(lambda Q: mkSSnam(Q), \n filter(lambda Q: (Nfa[\"F\"]&Q) != set({}), \n Visited)))\n \n # Make the DFA; send it to the DFA-shrink to bask ugly long \n # state names...\n return shrink_dfastates(mk_dfa(DFA_Q, \n DFA_Sigma, \n DFA_Delta, \n DFA_q0, \n DFA_F),\n STATENAME_MAXSIZE=STATENAME_MAXSIZE)\n else:\n newFrontier = list(map(lambda QcQ: trTrg(QcQ), New_c_Moves)) \n newVisited = Visited + newFrontier\n \n # Even though the NFA has not closed back on itself, we MUST \n # accommodate for the \"curl-backs\" along the way !! Thus, run it\n # over All_c_Moves which may include \"partial revisits along the \n # way\". We MUST pick up those curl-backs!\n NewMovesDelta = dict([ ((mkSSnam(Qfrom),c),mkSSnam(Qto)) \n for ((Qfrom, c), Qto) in All_c_Moves ]) \n Delta.update(NewMovesDelta)\n return n2d(newFrontier, newVisited, Delta, Nfa,\n STATENAME_MAXSIZE=STATENAME_MAXSIZE)\n \n#---NFA to DFA\n\n\n# # Brzozowski's DFA Minimization\n# \n# Picking up from our earlier discussions, to minimize a DFA using Brzozowski's algorithm, here are the steps:\n# \n# * Make sure that the given DFA has no unreachable states\n# * Reverse the DFA\n# * Determinize it\n# * Reverse that DFA\n# * Determinize it\n# \n# Thus we need to write a routine to reverse a DFA. We already have a way to ensure that a DFA does not have unreachable states (in another Jupyter notebook; we won't bother to include it here, and trust the user to always provide such DFA only).\n# \n# We can observe that if a DFA has black-hole states, then those states won't matter in the reversed machine (reversed NFA). Thus, we can work with __partial__ dfa (i.e., DFA that are partially consistent).\n\n# ## DFA reversal\n\n# In[ ]:\n\n\ndef inSets(D,trg,ch):\n \"\"\"Helper for rev_dfa\n ---\n In : D = partially consistent dfa,\n trg = a target state in D[\"q\"]\n ch = a member of D[\"Sigma\"]\n Out: a set of states. { q s.t. Delta[q,ch] == trg }\n \"\"\"\n return { q for q in D[\"Q\"] if D[\"Delta\"][(q,ch)] == trg }\n\ndef rev_dfa(D):\n \"\"\"In : D = a partially consistent DFA without any unreachable states.\n Out: A consistent NFA whose language is D's language reversed.\n \"\"\"\n # 1. Given that NFAs start from a SET of states, we already have that\n # info. No need to add any transitions from \"a new initial state\" \n # etc\n \n # 2. Now add the inSets of each state as the NFA next set of states\n NDict = { (q,ch) : inSets(D,q,ch) \n for q in D[\"Q\"] \n for ch in D[\"Sigma\"] }\n \n # Notice that we retain D[\"Q\"] and start from Q0 = D[\"F\"]\n # going backwards along NDict toward F_dfa = { D[\"q0\"] }\n return mk_nfa(D[\"Q\"], D[\"Sigma\"], NDict, D[\"F\"], {D[\"q0\"]})\n\n\n# In[ ]:\n\n\ndef min_dfa_brz(D):\n \"\"\"Minimize a DFA as per Brzozowski's algorithm.\n \"\"\"\n return nfa2dfa(rev_dfa(nfa2dfa(rev_dfa(D))))\n\n\n# In[ ]:\n\n\nprint('''You may use any of these help commands:\nhelp(mk_nfa)\nhelp(totalize_nfa)\nhelp(step_nfa)\nhelp(run_nfa)\nhelp(ec_step_nfa)\nhelp(Eclosure)\nhelp(Echelp)\nhelp(accepts_nfa)\nhelp(nfa2dfa)\nhelp(n2d)\nhelp(inSets)\nhelp(rev_dfa)\nhelp(min_dfa_brz)\n''')\n\n","repo_name":"ganeshutah/Jove","sub_path":"jove/Def_NFA.py","file_name":"Def_NFA.py","file_ext":"py","file_size_in_byte":16498,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"77"} +{"seq_id":"6336826903","text":"#!/usr/bin/env python3\n\n\"\"\"Determine scores for assignments.\"\"\"\n\nfrom argparse import ArgumentParser\nfrom configparser import ConfigParser, ExtendedInterpolation\nfrom glob import glob\nfrom os import listdir\nfrom os.path import join\nimport sys\n\n\ndef print_student(config, score, boni, mali):\n print(\"base: {}\".format(config['base'].getint('base_score')))\n for i in mali:\n print(i)\n for i in boni:\n print(i)\n print(\"=> {}\".format(score))\n\n\ndef score_student(config, student_id):\n folder = glob(config['base']['folder_template'].format(student_id))[0]\n score, boni, mali = get_file_stats(config, join(folder, 'notes.txt'))\n print_student(config, score, boni, mali)\n\n\ndef get_file_stats(config, file):\n basescore = config['base'].getint('base_score')\n maxscore = config['base'].getint('max_score')\n score = basescore\n boni, mali = set(), set()\n with open(file) as f:\n for l in f:\n if l.startswith('-'):\n name = l.split()[1]\n value = config['mali'].getfloat(name)\n if value is None:\n sys.exit(\"unknown malus: {} ({})\".format(name, file))\n mali.add(\"{} (-{})\".format(name, value))\n score -= value\n elif l.startswith('+'):\n name = l.split()[1]\n value = config['boni'].getfloat(name)\n if value is None:\n sys.exit(\"unknown bonus: {}\".format(name))\n boni.add(\"{} ({})\".format(name, value))\n score += value\n score = max(0, score) # there are no negative scores\n score = min(maxscore, score) # limit the maximum amount of points\n return score, boni, mali\n\n\ndef stat_categories():\n boni, mali = {}, {}\n for d in listdir('.'):\n with open(join(d, 'notes.txt')) as f:\n for l in f:\n if l.startswith('-'):\n name = l.split()[1]\n if not name in mali.keys():\n mali[name] = 0\n mali[name] += 1\n elif l.startswith('+'):\n name = l.split()[1]\n if not name in boni.keys():\n boni[name] = 0\n boni[name] += 1\n return boni, mali\n\n\ndef determine_categories():\n boni, mali = stat_categories()\n return boni.keys(), mali.keys()\n\n\ndef print_stats(config):\n scores = []\n basescore = config['base'].getint('base_score')\n for d in listdir('.'):\n score, _, _ = get_file_stats(config, join(d, 'notes.txt'))\n scores.append(score)\n print('average: {:.1f}'.format(sum(scores)/float(len(scores))))\n print('above {}: {}'.format(basescore,\n sum(i > basescore for i in scores)))\n print('failed: {}'.format(sum(i < basescore/float(2) for i in scores)))\n\n boni, mali = stat_categories()\n print()\n print(\"=== mali count:\")\n for category, count in mali.items():\n print(\"{}: {}\".format(category, count))\n print()\n print(\"=== boni count:\")\n for category, count in boni.items():\n print(\"{}: {}\".format(category, count))\n\n\ndef print_csv(config):\n for d in listdir('.'):\n score, _, _ = get_file_stats(config, join(d, 'notes.txt'))\n print(\"{},{}\".format(d, score))\n\n\ndef print_failed(config):\n basescore = config['base'].getint('base_score')\n for d in listdir('.'):\n score, boni, mali = get_file_stats(config, join(d, 'notes.txt'))\n if score < basescore/float(2):\n print(d)\n print_student(config, score, boni, mali)\n\n\ndef set_categories(config):\n boni, mali = determine_categories()\n config['boni'] = {i: '1' for i in boni}\n config['mali'] = {i: '1' for i in mali}\n\n\ndef update_categories(config):\n boni, mali = determine_categories()\n for i in boni:\n if i not in config['boni'].keys():\n config['boni'][i] = '1'\n for i in mali:\n if i not in config['mali'].keys():\n config['mali'][i] = '1'\n\n\nif __name__ == '__main__':\n argparser = ArgumentParser(description=\"determine scores for assignments\")\n argparser.add_argument('config', help=\"config file for the assignment\")\n argparser.add_argument('-s',\n help='set boni, mali and write to config',\n action='store_true')\n argparser.add_argument('-u',\n help='update boni, mali and write to config',\n action='store_true')\n argparser.add_argument('-f',\n help='list failed students',\n action='store_true')\n argparser.add_argument('-c',\n help='export csv',\n action='store_true')\n argparser.add_argument('student_id',\n help=\"id of the student to score\",\n nargs='?')\n args = argparser.parse_args()\n\n config = ConfigParser(interpolation=ExtendedInterpolation())\n config.read(args.config)\n\n if args.s:\n set_categories(config)\n with open(args.config, 'w') as f:\n config.write(f)\n elif args.u:\n update_categories(config)\n with open(args.config, 'w') as f:\n config.write(f)\n elif args.f:\n print_failed(config)\n elif args.c:\n print_csv(config)\n elif args.student_id:\n score_student(config, args.student_id)\n else:\n print_stats(config)\n","repo_name":"poettler-ric/scripts","sub_path":"assignment_scores.py","file_name":"assignment_scores.py","file_ext":"py","file_size_in_byte":5502,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"71638286969","text":"# -*- coding: utf-8 -*-\n\nimport pandas as pd\nfrom dateutil.parser import parse\nimport requests\nimport io\nimport pymysql\nfrom datetime import timedelta\nfrom cfg import ph\n\nchem_types = ['PM2.5', 'PM10', 'SO2', 'NO2', 'CO', 'O3']\nchem_units = ['ug/m^3', 'ug/m^3', 'ug/m^3', 'ug/m^3', 'mg/m^3', 'ug/m^3']\n\n\ndef url2df(file_date):\n url = 'http://183.129.229.233:12345/' + 'aq_{}.csv'.format(file_date)\n html = requests.get(url).content\n air = pd.read_csv(io.StringIO(html.decode('utf-8')))\n air.rename(columns={'站点名': 'site_name', '城市': 'city_name'}, inplace=True)\n\n con = pymysql.connect(host='localhost', port=3306, user='root', passwd='95279527', db='database', charset='utf8')\n cursor = con.cursor()\n\n # Get site_list and city_list\n cursor.execute('SELECT city_id, site_id, site_name FROM forecast_site_list')\n rows = cursor.fetchall()\n con.commit()\n sites = pd.DataFrame(list(rows), columns=['city_id', 'site_id', 'site_name'])\n\n cursor.execute('SELECT city_id, city_name FROM forecast_city_list')\n rows = cursor.fetchall()\n con.commit()\n cities = pd.DataFrame(list(rows), columns=['city_id', 'city_name'])\n cities['city_name'] = cities['city_name'].apply(lambda x: x.strip()[:-1])\n cursor.close()\n con.close()\n\n sites = pd.merge(sites, cities, on='city_id', how='left')\n\n air = pd.merge(air, sites, on=['city_name', 'site_name'], how='inner')\n air.rename(columns={'观测时间': 'observed_time', 'pm2.5': 'PM2.5', 'pm10': 'PM10', 'o3': 'O3', 'no2': 'NO2', 'co': 'CO',\n 'so2': 'SO2'}, inplace=True)\n air = air[['site_id', 'observed_time'] + chem_types]\n\n # format air data\n file_date_col = pd.DataFrame([parse(file_date).strftime('%Y-%m-%d %H:%M:%S') for _ in range(air.shape[0])],\n columns=['file_date'])\n new_air = pd.DataFrame([])\n for ix, chem_type in enumerate(chem_types):\n chem_type_col = pd.DataFrame([chem_type for _ in range(air.shape[0])], columns=['chem_type'])\n chem_unit_col = pd.DataFrame([chem_units[ix] for _ in range(air.shape[0])], columns=['chem_unit'])\n air_1type = air[['site_id', 'observed_time', chem_type]].copy().reset_index(drop=True)\n air_1type.rename(columns={chem_type: 'chem_value'}, inplace=True)\n air_1type = pd.concat((air_1type, file_date_col, chem_type_col, chem_unit_col), axis=1)\n if new_air.size == 0:\n new_air = air_1type\n else:\n new_air = pd.concat((new_air, air_1type), axis=0, ignore_index=True)\n\n new_air = new_air[['site_id', 'file_date', 'chem_type', 'chem_unit', 'observed_time', 'chem_value']]\n\n new_air['chem_value'].replace({'_': None, '—': None}, inplace=True)\n\n return new_air\n\n\ndef values2db(file_date):\n\n \"\"\"\n Parse and save metsite file to database\n :param file_path: local file path\n \"\"\"\n con = pymysql.connect(host='localhost', port=3306, user='root', passwd='95279527', db='database', charset='utf8')\n cursor = con.cursor()\n air = url2df(file_date)\n values = air.values\n for i in range(values.shape[0]):\n cursor.execute('INSERT INTO observation_chem_site(site_id, file_date, chem_type, chem_unit, observed_time, chem_value) VALUES (%s, %s, %s, %s, %s, %s)', tuple(values[i]))\n con.commit()\n cursor.close()\n con.close()\n\n print('File of {}'.format(file_date) + ' done!')\n\n\nif __name__ == '__main__':\n file_date = ph.start_date\n file_dates = [(parse(file_date) + timedelta(days=i)).strftime('%Y%m%d') for i in range(100)]\n for fd in file_dates:\n # url2df(file_date)\n values2db(fd)\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Dongkun-Wang/Master-Project","sub_path":"Virtual Attention/database/observation_chem.py","file_name":"observation_chem.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"39438589688","text":"import random\nfrom tkinter import *\nimport pandas\n\nBACKGROUND_COLOR = \"#B1DDC6\"\ncurrent_card = {}\n\n# ------------------------------------- READ CSV ------------------------------------- #\ntry:\n data = pandas.read_csv(\"data/words_to_learn.csv\")\n to_learn = data.to_dict(orient=\"records\")\nexcept FileNotFoundError:\n data = pandas.read_csv(\"data/french_words.csv\")\n to_learn = data.to_dict(orient=\"records\")\n\n\n# ------------------------------------ FLIP CARD ------------------------------------ #\ndef next_card():\n global current_card, timer\n window.after_cancel(timer)\n current_card = random.choice(to_learn)\n canvas.itemconfig(card_title, text=\"French\", fill=\"black\")\n canvas.itemconfig(card_word, text=current_card[\"French\"], fill=\"black\")\n timer = window.after(3000, english_card)\n canvas.itemconfig(flash_card, image=card_front_img)\n\n\ndef english_card():\n canvas.itemconfig(flash_card, image=card_back_img)\n canvas.itemconfig(card_title, fill=\"white\", text=\"English\")\n canvas.itemconfig(card_word, fill=\"white\", text=current_card[\"English\"])\n\n\n# ---------------------------------- CREATE NEW CSV ---------------------------------- #\ndef is_known():\n to_learn.remove(current_card)\n to_learn_df = pandas.DataFrame(to_learn)\n to_learn_df.to_csv(\"data/words_to_learn.csv\", index=False)\n next_card()\n\n\n# ------------------------------------- UI SETUP ------------------------------------- #\nwindow = Tk()\nwindow.title(\"Flashy\")\nwindow.config(padx=50, pady=50, bg=BACKGROUND_COLOR)\ntimer = window.after(3000, english_card)\n\ncanvas = Canvas(width=800, height=526)\ncanvas.config(bg=BACKGROUND_COLOR, highlightthickness=0)\ncard_front_img = PhotoImage(file=\"images/card_front.png\")\nflash_card = canvas.create_image(400, 263, image=card_front_img)\ncard_back_img = PhotoImage(file=\"images/card_back.png\")\ncard_title = canvas.create_text(400, 150, text=\"Title\", font=(\"Ariel\", 40, \"italic\"))\ncard_word = canvas.create_text(400, 263, text=\"Word\", font=(\"Ariel\", 60, \"bold\"))\ncanvas.grid(row=0, column=0, columnspan=2)\n\nright_button = Button()\nright_image = PhotoImage(file=\"images/right.png\")\nright_button.config(image=right_image, highlightthickness=0, command=is_known)\nright_button.grid(row=1, column=1)\n\nwrong_button = Button()\nwrong_image = PhotoImage(file=\"images/wrong.png\")\nwrong_button.config(image=wrong_image, highlightthickness=0, command=next_card)\nwrong_button.grid(row=1, column=0)\n\nnext_card()\n\nwindow.mainloop()\n","repo_name":"Aris-Kazis/Flash-Card-App","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"21869624025","text":"# Write a program to read through the mbox-short.txt\n# and figure out who has sent the greatest number of mail messages.\n# The program looks for 'From ' lines and\n# takes the second word of those lines as the person who sent the mail.\n# The program creates a Python dictionary that maps the sender's\n# mail address to a count of the number of times they appear in the file.\n# After the dictionary is produced, the program reads through\n# the dictionary using a maximum loop to find the most prolific committer.\n\nfile_handler = open(\"mbox-short.txt\")\n\nmail_count = dict()\n\nfor line in file_handler:\n if not line.startswith(\"From:\") and line.startswith(\"From\"):\n words = line.split()\n mail_count[words[1]] = mail_count.get(words[1], 0) + 1\n\nmax_mail_count = None\nmax_mail_sender = None\n\nfor mail_sender, number_of_mail in mail_count.items():\n if max_mail_count is None or max_mail_count < number_of_mail:\n max_mail_count = number_of_mail\n max_mail_sender = mail_sender\n\nprint(max_mail_sender, max_mail_count)\n","repo_name":"rajib80/python-playground","sub_path":"dictionary-exercise/dictionary-exercise.py","file_name":"dictionary-exercise.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"19803486138","text":"from itertools import permutations\nimport re\n\nclass KnightsoftheDinnerTable:\n def __init__(self, input) -> None:\n self._list = {}\n self._people = ['self']\n self._lookup = {}\n for l in input:\n parts = re.split(' ', l.strip())\n n = int(re.findall('-?\\d+',l)[0])\n if 'lose' in l:\n n = n*-1\n\n if parts[0] not in self._people:\n self._people.append(parts[0])\n\n if parts[len(parts)-1].rstrip('.') not in self._people:\n self._people.append(parts[len(parts)-1].rstrip('.'))\n\n self._lookup[parts[0], parts[len(parts)-1].rstrip('.')] = n\n\n perm = permutations(self._people)\n for p in perm:\n self._list[p] = 0\n \n for idx, person in enumerate(p):\n if idx + 1 < len(p):\n self._list[p] += self.lookup(person, p[idx+1])\n self._list[p] += self.lookup(p[idx+1], person)\n else:\n self._list[p] += self.lookup(person, p[0])\n self._list[p] += self.lookup(p[0], person)\n\n \n print(max(self._list.values()))\n\n def lookup(self, a, b):\n if a == 'self': return 0\n if b == 'self': return 0\n return self._lookup[a, b]","repo_name":"jphillips05/adventofcode","sub_path":"Python/2015/day13.py","file_name":"day13.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"42065743221","text":"\"\"\"Author: Bas Volkers, MVI.\"\"\"\nfrom typing import Tuple, Dict\n\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import QDialog\nfrom python_qt_binding import loadUi\n\n\nclass SameVersionsPopUpWindow(QDialog):\n \"\"\"A pop-up window to set the same version for all subgaits.\n\n Args:\n parent: The parent widget to connect to the pop-up.\n ui_file (str): The absolute path to the UI-file for the pop-up.\n \"\"\"\n\n def __init__(self, parent, ui_file):\n super(SameVersionsPopUpWindow, self).__init__(parent=parent, flags=Qt.Window)\n loadUi(ui_file, self)\n\n self.buttonBox.accepted.connect(self.ok)\n self.buttonBox.rejected.connect(self.cancel)\n\n # Store the previous pre and postfix per gait\n self._previous_map: Dict[str, Tuple[str, str]] = {}\n\n self.prefix = \"\"\n self.postfix = \"\"\n self.current_gait = \"\"\n\n def show_pop_up(self, gait: str):\n \"\"\"Reset and show pop up.\"\"\"\n self.prefix = \"\"\n self.postfix = \"\"\n self.current_gait = gait\n\n self.prefix_input.clear()\n self.postfix_input.clear()\n if gait in self._previous_map:\n self.prefix_input.setText(self._previous_map[gait][0])\n self.postfix_input.setText(self._previous_map[gait][1])\n\n return super(SameVersionsPopUpWindow, self).exec_()\n\n def cancel(self):\n \"\"\"Close without applying the values.\"\"\"\n self.reject()\n\n def ok(self):\n \"\"\"Save value while closing.\"\"\"\n self.prefix = self.prefix_input.text()\n self.postfix = self.postfix_input.text()\n\n self._previous_map[self.current_gait] = (self.prefix, self.postfix)\n self.current_gait = \"\"\n\n self.accept()\n","repo_name":"project-march/ProjectMarch","sub_path":"ros2/src/visualization/march_rqt_gait_version_tool/march_rqt_gait_version_tool/same_versions_pop_up.py","file_name":"same_versions_pop_up.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"77"} +{"seq_id":"29865084130","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"PAT\")\n\n\nprocess.load('FWCore/MessageService/MessageLogger_cfi')\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 100\n\nprocess.options = cms.untracked.PSet(\n Rethrow = cms.untracked.vstring('ProductNotFound'),\n wantSummary = cms.untracked.bool(True)\n)\n\n# source\nprocess.source = cms.Source(\"PoolSource\", \n fileNames=cms.untracked.vstring( )\n \n)\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )\n\n\n\n\n# this is the equivalent of the JSON file \nprocess.source.lumisToProcess = cms.untracked.VLuminosityBlockRange(\n\n# from: /afs/cern.ch/cms/CAF/CMSCOMM/COMM_DQM/certification/Collisions10/7TeV/StreamExpress/Cert_132440-140399_7TeV_StreamExpress_Collisions10_CMSSWConfig.txt\n\n)\n\n\n\n\n## Load additional processes\nprocess.load(\"Configuration.StandardSequences.Geometry_cff\")\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")\n## global tags:\nprocess.GlobalTag.globaltag = cms.string('GR_R_36X_V11A::All') ## GF changed here\nprocess.load(\"Configuration.StandardSequences.MagneticField_cff\")\nprocess.load('Configuration.StandardSequences.Services_cff')\n\n\n################################################################################################\n### P r e p a r a t i o n o f t h e P A T O b j e c t s f r o m A O D ###\n################################################################################################\n\n## pat sequences to be loaded:\n#process.load(\"PhysicsTools.PFCandProducer.PF2PAT_cff\")\nprocess.load(\"PhysicsTools.PatAlgos.patSequences_cff\")\n#process.load(\"PhysicsTools.PatAlgos.triggerLayer1.triggerProducer_cff\")\n##\n#\n## %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n## MET creation <=== WARNING: YOU MAY WANT TO MODIFY THIS PART OF THE CODE %%%%%%%%%%%%%\n## specify the names of the MET collections that you need here %%%%\n## #%%\n## if you don't specify anything the default MET is the raw Calo MET #%%\nprocess.caloMET = process.patMETs.clone( #%%\n metSource = cms.InputTag(\"met\",\"\",\"RECO\"),\n addTrigMatch = cms.bool(False),\n addMuonCorrections = cms.bool(False),\n addGenMET = cms.bool(False),\n )\nprocess.tcMET = process.patMETs.clone( #%%\n metSource = cms.InputTag(\"tcMet\",\"\",\"RECO\"),\n addTrigMatch = cms.bool(False),\n addMuonCorrections = cms.bool(False),\n addGenMET = cms.bool(False),\n )\nprocess.pfMET = process.patMETs.clone( #%%\n metSource = cms.InputTag(\"pfMet\",\"\",\"RECO\"),\n addTrigMatch = cms.bool(False),\n addMuonCorrections = cms.bool(False),\n addGenMET = cms.bool(False),\n )\n## specify here what you want to have on the plots! <===== MET THAT YOU WANT ON THE PLOTS %%%%%%%\nmyMetCollection = 'caloMET'\nmyPfMetCollection = 'pfMET'\nmyTcMetCollection = 'tcMET'\n\n## specify here what you want to have on the plots! <===== MET THAT YOU WANT ON THE PLOTS %%%%%%%\n## myDesiredMetCollection = 'layer1RawCaloMETs'\n## modify the sequence of the MET creation: #%%\nprocess.makePatMETs = cms.Sequence(process.caloMET*process.tcMET*process.pfMET)\n\n ## GF changed here: more than one pat done here\n## %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n## modify the final pat sequence: keep only electrons + METS (muons are needed for met corrections)\nprocess.load(\"RecoEgamma.EgammaIsolationAlgos.egammaIsolationSequence_cff\")\n#process.patElectronIsolation = cms.Sequence(process.egammaIsolationSequence)\n\nprocess.patElectrons.isoDeposits = cms.PSet()\nprocess.patElectrons.userIsolation = cms.PSet()\nprocess.patElectrons.addElectronID = cms.bool(True)\nprocess.patElectrons.electronIDSources = cms.PSet(\n simpleEleId95relIso= cms.InputTag(\"simpleEleId95relIso\"),\n simpleEleId90relIso= cms.InputTag(\"simpleEleId90relIso\"),\n simpleEleId85relIso= cms.InputTag(\"simpleEleId85relIso\"),\n simpleEleId80relIso= cms.InputTag(\"simpleEleId80relIso\"),\n simpleEleId70relIso= cms.InputTag(\"simpleEleId70relIso\"),\n simpleEleId60relIso= cms.InputTag(\"simpleEleId60relIso\"),\n simpleEleId95cIso= cms.InputTag(\"simpleEleId95cIso\"),\n simpleEleId90cIso= cms.InputTag(\"simpleEleId90cIso\"),\n simpleEleId85cIso= cms.InputTag(\"simpleEleId85cIso\"),\n simpleEleId80cIso= cms.InputTag(\"simpleEleId80cIso\"),\n simpleEleId70cIso= cms.InputTag(\"simpleEleId70cIso\"),\n simpleEleId60cIso= cms.InputTag(\"simpleEleId60cIso\"), \n )\n##\nprocess.patElectrons.addGenMatch = cms.bool(False)\nprocess.patElectrons.embedGenMatch = cms.bool(False)\nprocess.patElectrons.usePV = cms.bool(False)\n##\nprocess.load(\"ElectroWeakAnalysis.WENu.simpleEleIdSequence_cff\")\n ## GF changed here: \n# you have to tell the ID that it is data\nprocess.simpleEleId95relIso.dataMagneticFieldSetUp = cms.bool(True)\nprocess.simpleEleId90relIso.dataMagneticFieldSetUp = cms.bool(True)\nprocess.simpleEleId85relIso.dataMagneticFieldSetUp = cms.bool(True)\nprocess.simpleEleId80relIso.dataMagneticFieldSetUp = cms.bool(True)\nprocess.simpleEleId70relIso.dataMagneticFieldSetUp = cms.bool(True)\nprocess.simpleEleId60relIso.dataMagneticFieldSetUp = cms.bool(True)\nprocess.simpleEleId95cIso.dataMagneticFieldSetUp = cms.bool(True)\nprocess.simpleEleId90cIso.dataMagneticFieldSetUp = cms.bool(True)\nprocess.simpleEleId85cIso.dataMagneticFieldSetUp = cms.bool(True)\nprocess.simpleEleId80cIso.dataMagneticFieldSetUp = cms.bool(True)\nprocess.simpleEleId70cIso.dataMagneticFieldSetUp = cms.bool(True)\nprocess.simpleEleId60cIso.dataMagneticFieldSetUp = cms.bool(True)\n#\n\nprocess.patElectronIDs = cms.Sequence(process.simpleEleIdSequence)\nprocess.makePatElectrons = cms.Sequence(process.patElectronIDs*process.patElectrons)\n# process.makePatMuons may be needed depending on how you calculate the MET\nprocess.makePatCandidates = cms.Sequence(process.makePatElectrons+process.makePatMETs)\nprocess.patDefaultSequence = cms.Sequence(process.makePatCandidates)\n##\n## ################################################################################\n##\n## the filter to select the candidates from the data samples\n##\n##\n## WARNING: you may want to modify this item:\nHLT_process_name = \"HLT\" # \n# trigger path selection\n\n\n# this path was introduced at run 140058\nHLT_path_name = \"HLT_Ele15_SW_L1R\"\n# trigger filter name\nHLT_filter_name = \"hltPeppeRePeppeZeZZe\"\n# HLT_filter_name = \"hltL1NonIsoHLTNonIsoSingleElectronLWEt15PixelMatchFilter\"\n\n#\n# keep this for runs <140058 when HLT_Ele15_SW_L1R was not present. Following was prescaled starting from run 141956\nHLT_path_name_extra = \"HLT_Ele15_LW_L1R\"\nHLT_filter_name_extra = \"hltPeppeRePeppeZeZZe\"\n\nprocess.z1legFilter =cms.EDFilter('WenuCandidateFilter',\n ### the input collections needed:\n electronCollectionTag = cms.untracked.InputTag(\"patElectrons\",\"\",\"PAT\"),\n metCollectionTag = cms.untracked.InputTag(myMetCollection,\"\",\"PAT\"),\n pfMetCollectionTag = cms.untracked.InputTag(myPfMetCollection,\"\",\"PAT\"),\n tcMetCollectionTag = cms.untracked.InputTag(myTcMetCollection,\"\",\"PAT\"),\n triggerCollectionTag = cms.untracked.InputTag(\"TriggerResults\",\"\",HLT_process_name),\n triggerEventTag = cms.untracked.InputTag(\"hltTriggerSummaryAOD\",\"\",HLT_process_name),\n hltpath = cms.untracked.string(HLT_path_name),\n hltpathFilter = cms.untracked.InputTag(HLT_filter_name,\"\",HLT_process_name),\n ebRecHits = cms.untracked.InputTag(\"reducedEcalRecHitsEB\"),\n eeRecHits = cms.untracked.InputTag(\"reducedEcalRecHitsEE\"),\n PrimaryVerticesCollection = cms.untracked.InputTag(\"offlinePrimaryVertices\"),\n ### here the preselection is applied\n # fiducial cuts:\n BarrelMaxEta = cms.untracked.double(1.4442),\n EndCapMinEta = cms.untracked.double(1.566),\n EndCapMaxEta = cms.untracked.double(2.5),\n # demand ecal driven electron:\n useEcalDrivenElectrons = cms.untracked.bool(True),\n # demand offline spike cleaning with the Swiss Cross criterion:\n useSpikeRejection = cms.untracked.bool(True),\n spikeCleaningSwissCrossCut = cms.untracked.double(0.95),\n # demand geometrically matched to an HLT object with ET>15GeV\n useTriggerInfo = cms.untracked.bool(True), # GF >>>>>>>>>>>> changed here on Tue Aug 3 19:16:55 CEST 2010\n electronMatched2HLT = cms.untracked.bool(False), # GF \n electronMatched2HLT_DR = cms.untracked.double(0.2), # GF \n useHLTObjectETCut = cms.untracked.bool(False), # GF \n hltObjectETCut = cms.untracked.double(15.),\n useExtraTrigger = cms.untracked.bool(True), # GF >>>>>>>>>> Wed Aug 4 11:52:45 CDT 2010\n vHltpathExtra = cms.untracked.vstring(HLT_path_name_extra),\n vHltpathFilterExtra = cms.untracked.VInputTag(HLT_filter_name_extra),\n # ET Cut in the SC\n ETCut = cms.untracked.double(15.), # GF : changed here Wed Aug 4 11:52:45 CDT 2010\n METCut = cms.untracked.double(0.),\n # reject events with a 2nd electron with ET > 20 that passes the WP95%\n vetoSecondElectronEvents = cms.untracked.bool(False),\n storeSecondElectron = cms.untracked.bool(False),\n ETCut2ndEle = cms.untracked.double(20.),\n vetoSecondElectronIDType = cms.untracked.string(\"simpleEleId80relIso\"), # GF\n vetoSecondElectronIDSign = cms.untracked.string(\"=\"),\n vetoSecondElectronIDValue = cms.untracked.double(7.),\n # Other parameters of the code - leave them as they are\n useValidFirstPXBHit = cms.untracked.bool(False),\n useConversionRejection = cms.untracked.bool(False),\n useExpectedMissingHits = cms.untracked.bool(False),\n maxNumberOfExpectedMissingHits = cms.untracked.int32(1),\n # calculate some new cuts\n calculateValidFirstPXBHit = cms.untracked.bool(True),\n calculateConversionRejection = cms.untracked.bool(True),\n calculateExpectedMissingHits = cms.untracked.bool(True),\n # we are dealing with DATA\n dataMagneticFieldSetUp = cms.untracked.bool(True),\n dcsTag = cms.untracked.InputTag(\"scalersRawToDigi\"),\n )\n\n####################################################################################\nprocess.z1lPath = cms.Path(process.patDefaultSequence*process.z1legFilter)\n\n\nprocess.z1lOutputModule = cms.OutputModule( \"PoolOutputModule\",\n fileName = cms.untracked.string(\"\"),\n maxSize = cms.untracked.int32(300000),\n SelectEvents = cms.untracked.PSet(\n SelectEvents = cms.vstring('z1lPath',),\n )\n )\n\nprocess.outpath = cms.EndPath(process.z1lOutputModule)\n","repo_name":"alexeyfinkel/ZShape","sub_path":"HFZeeVBTF/test/skimOnly_Zoneleg_prodDATA_cfg.py","file_name":"skimOnly_Zoneleg_prodDATA_cfg.py","file_ext":"py","file_size_in_byte":12693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"37581704138","text":"import argparse\nimport os\nimport PIL.ImageFilter\nimport PIL.Image\nimport sys\n\ndef blur_letterbox(\n image,\n new_width=None,\n new_height=None,\n blurring=None,\n ):\n\n (iw, ih) = image.size\n new_width = new_width or iw\n new_height = new_height or ih\n\n if blurring is None:\n blurring = (new_width * new_height) * 0.00001\n print('Using bluriness', blurring)\n\n background = image.resize(fit_over_bounds(iw, ih, new_width, new_height), PIL.Image.ANTIALIAS)\n background = background.filter(PIL.ImageFilter.GaussianBlur(radius=blurring))\n foreground = image.resize(fit_into_bounds(iw, ih, new_width, new_height), PIL.Image.ANTIALIAS)\n\n background_offsets = offsets(background, new_width, new_height)\n foreground_offsets = offsets(foreground, new_width, new_height)\n\n final = PIL.Image.new(mode=image.mode, size=(new_width, new_height))\n final.paste(background, (background_offsets))\n final.paste(foreground, (foreground_offsets))\n return final\n\ndef fit_into_bounds(iw, ih, fw, fh):\n '''\n Given the w+h of the image and the w+h of the frame,\n return new w+h that fits the image into the frame\n while maintaining the aspect ratio and leaving blank space\n everywhere else\n '''\n ratio = min(fw/iw, fh/ih)\n\n w = int(iw * ratio)\n h = int(ih * ratio)\n\n return (w, h)\n\ndef fit_over_bounds(iw, ih, fw, fh):\n '''\n Given the w+h of the image and the w+h of the frame,\n return new w+h that covers the entire frame\n while maintaining the aspect ratio\n '''\n ratio = max(fw/iw, fh/ih)\n\n w = int(iw * ratio)\n h = int(ih * ratio)\n\n return (w, h)\n\ndef listget(li, index, fallback=None):\n try:\n return li[index]\n except IndexError:\n return fallback\n\ndef offsets(image, new_width, new_height):\n '''\n Calculate the horizontal and vertical offsets\n needed to center the image in the given box\n '''\n horizontal = int((new_width - image.size[0]) / 2)\n vertical = int((image.size[1] - new_height) / 2) * -1\n return (horizontal, vertical)\n\n\ndef main(argv):\n parser = argparse.ArgumentParser(add_help=False)\n parser.add_argument('filename')\n parser.add_argument('-w', '--width', dest='width', default=None)\n parser.add_argument('-h', '--height', dest='height', default=None)\n parser.add_argument('-b', '--blurring', dest='blurring', default=None)\n\n args = parser.parse_args(argv)\n if args.width is None and args.height is None:\n print('Need a new width or height')\n return\n\n int_or_none = lambda x: int(x) if x else x\n (base, extension) = os.path.splitext(args.filename)\n new_name = base + '_blur' + extension\n image = PIL.Image.open(args.filename)\n image = blur_letterbox(\n image,\n int_or_none(args.width),\n int_or_none(args.height),\n int_or_none(args.blurring)\n )\n image.save(new_name)\n\nif __name__ == '__main__':\n raise SystemExit(main(sys.argv[1:]))\n","repo_name":"voussoir/else","sub_path":"BlurredLetterbox/blurredletterbox.py","file_name":"blurredletterbox.py","file_ext":"py","file_size_in_byte":2985,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"77"} +{"seq_id":"10248197194","text":"\nimport random\nimport numpy as np\nimport time\n\ndef create_starting_map(x_len,y_len, num_alive): \n \n mapp = np.zeros((y_len, x_len))\n placed_ones = 0\n pos_alive = []\n\n if x_len * y_len < num_alive:\n num_alive = x_len*y_len\n\n while placed_ones < num_alive:\n x = random.randint(0,x_len-1)\n y = random.randint(0,y_len-1)\n\n if mapp[y,x] == 0:\n mapp[y,x] = 1\n placed_ones += 1 \n pos_alive.append([y,x])\n return mapp, pos_alive\n\ndef live_die_born(mapp, alive_pos):\n y = mapp.shape[0] #gives lenght y\n x = mapp.shape[1] #gives lengh x\n\n next_map = mapp\n still_alive = []\n chance_realiven = []\n\n for element in alive_pos:\n alive_neighbours = 0\n element_top_corner = [element[0]-1, element[1]-1]\n\n for e in range(3):\n for i in range(3):\n \n if element_top_corner in alive_pos and element_top_corner != element:\n alive_neighbours += 1\n\n if element_top_corner not in alive_pos: #and 0<=element_top_corner[0]<=(y-1) and 0<=element_top_corner[1]<=(x-1):\n if element_top_corner[0] >= 0 and element_top_corner[1] >= 0:\n if element_top_corner[0] < y and element_top_corner[1] 3:\n next_map[element[0],element[1]] = 0\n\n for element in chance_realiven:\n count = chance_realiven.count(element)\n if count ==3 and next_map[element[0], element[1]] == 0:\n still_alive.append(element)\n next_map[element[0],element[1]] = 1\n \n return next_map, still_alive\n\n\nstart_map, position = create_starting_map(5,7, 20)\nrun = True\nprint(\"first generation:\")\nprint(start_map)\n\nwhile run:\n next_gen, alive_coord = live_die_born(start_map, position)\n\n start_map = next_gen\n position = alive_coord\n print(\"next generation:\")\n print(start_map)\n time.sleep(5)\n\n\n \n\n","repo_name":"Hanna6k/game_of_life","sub_path":"game_of_life_01.py","file_name":"game_of_life_01.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"1628181074","text":"import re\n\ndef p1(data):\n return len([line for line in data if sum(sorted(line)[:2]) > max(line)])\n\n\ndef p2(data):\n t = 0\n for l1, l2, l3 in zip(data[0::3], data[1::3], data[2::3]):\n t += 1 if sum(sorted([l1[0], l2[0], l3[0]])[:2]) > max([l1[0], l2[0], l3[0]]) else 0\n t += 1 if sum(sorted([l1[1], l2[1], l3[1]])[:2]) > max([l1[1], l2[1], l3[1]]) else 0\n t += 1 if sum(sorted([l1[2], l2[2], l3[2]])[:2]) > max([l1[2], l2[2], l3[2]]) else 0\n return t\n\nif __name__ == '__main__':\n with open('input.txt', 'r') as f:\n data = [list(map(int, re.split(r'\\D+', line)[1:-1])) for line in f.readlines()]\n print(f'Part 1 : {p1(data)}')\n print(f'Part 2 : {p2(data)}')\n","repo_name":"Inkkonu/AdventOfCode","sub_path":"aoc2016/Day03.py","file_name":"Day03.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"40172755293","text":"import pandas as pd\nimport numpy as np\nimport torch\nimport random\nfrom mlp import P2PEngine\nfrom data import P2PEnvironment\nimport matplotlib.pyplot as plt\nfrom time import time\nimport seaborn as sns\nfrom plots import *\n\ndef get_cumsum(data):\n mean = (np.nancumsum(data[:,:-1], axis=1)/range(1, config['num_epoch']-1)).mean(axis=0)\n std = (np.nancumsum(data[:,:-1], axis=1)/range(1, config['num_epoch']-1)).std(axis=0)\n \n return mean, std\n\ndef plot_data(data,labels,file_name):\n fig, ax = plt.subplots()\n if \"match\" in file_name:\n ax.set_title(\"Matching regret by epoch\")\n ax.set_xlabel(\"Epoch\")\n ax.set_ylabel(\"Matching regret\")\n else:\n ax.set_title(\"Regret by epoch\")\n ax.set_xlabel(\"Epoch\")\n ax.set_ylabel(\"Regret\")\n \n results = [get_cumsum(i) for i in data]\n results_mean, results_std = zip(*results)\n results_mean = np.stack(results_mean)\n results_std = np.stack(results_std)\n\n with sns.axes_style(\"darkgrid\"):\n epochs = list(range(101))\n for i in range(len(data)):\n ax.plot(range(1, config['num_epoch']-1), results_mean[i,:], label=labels[i], c=nbc_palette[i])\n ax.fill_between(range(1, config['num_epoch']-1), results_mean[i,:]-results_std[i,:], results_mean[i,:]+results_std[i,:] ,alpha=0.3, facecolor=nbc_palette[i])\n ax.legend()\n fig.savefig(file_name)\n\nconfig = eval(open(\"config.txt\").read())\n\ndef generate_array(config):\n return np.zeros((config['num_trial'], config['num_epoch']-1))\n\n# Matrices storing information on each epoch \nregret_p2p = generate_array(config)\nregret_bandit = generate_array(config)\nregret_mask = generate_array(config)\nregret_all_data = generate_array(config)\n\nregret_match_p2p = generate_array(config)\nregret_match_bandit = generate_array(config)\nregret_match_mask = generate_array(config)\nregret_match_all_data = generate_array(config)\n\n\ndef run_one_round(engine,regret_matrix, match_matrix):\n action, _time = engine.p2p_an_epoch(data_loader, test_feature, epoch_id=epoch)\n matches = engine.get_matches(action,test_label,env._m)\n ro, rb = env.get_reward(action)\n match_reward = env.get_match_reward(matches)\n engine.update_bandit(ro,rb)\n regret_matrix[trial_idx, epoch-1] = (ro.sum()+rb.sum())-best_reward.sum()\n match_matrix[trial_idx, epoch-1] = best_match_reward - match_reward\n \n return ro, rb, match_reward\n\nfor trial_idx in range(config['num_trial']):\n env = P2PEnvironment(config, seed=trial_idx * 10)\n engine_p2p = P2PEngine(env, config, pure_bandit=False, predict_mask=False)\n engine_mask = P2PEngine(env, config, pure_bandit=False, predict_mask=True)\n engine_all_data = P2PEngine(env, config, pure_bandit=False, predict_mask=True,use_all_data=True)\n engine_bandit = P2PEngine(env, config, pure_bandit=True, predict_mask=False) \n\n start_time = time()\n \n for epoch in range(1, config['num_epoch']):\n data_loader = env.get_data_loader()\n test_feature, test_label = env.get_new_data(epoch)\n \n best_action = engine_p2p.p2p_known_mu(test_label, env._m)\n best_reward_optimization, best_reward_bandit = env.get_reward(best_action)\n best_reward = best_reward_optimization + best_reward_bandit\n best_matches = engine_p2p.get_matches(best_action,test_label, env._m)\n best_match_reward = env.get_match_reward(best_matches)\n \n run_one_round(engine_bandit, regret_bandit, regret_match_bandit)\n run_one_round(engine_p2p, regret_p2p, regret_match_p2p)\n run_one_round(engine_mask, regret_mask, regret_match_mask)\n run_one_round(engine_all_data, regret_all_data, regret_match_all_data)\n\n env.add_to_data_loader()\n\n if epoch == config['num_epoch'] - 1:\n end_time = time()\n print('Epoch {} starts !'.format(epoch))\n print('-' * 80)\n \n file_basename = 'runs/n{}m{}d{}capacity{}range{}task{}ns{}trial{}regret_'.format(config['points_per_iter'], \n config['feature_dim'], config['label_dim'],config['mean_volunteer_attributes'][0],config['mean_volunteer_attributes'][1],config['mean_task_attributes'][0],config['num_sources'],trial_idx)\n \n for algorithm, dataset in zip(['p2p','bandit','mask','alldata'], \n [regret_p2p,regret_bandit,regret_mask,regret_all_data]):\n file_name = file_basename + algorithm + \".npy\"\n np.save(file_name,dataset)\n\nnbc_palette = [[0,0,0], [230/255,159/255,0], [86/255,180/255,233/255], [0,158/255,115/255],\n [213/255,94/255,0], [0,114/255,178/255],[213/255,94/255,0/255],[204/255,121/255,167/255]]\nsns.palplot(sns.color_palette(nbc_palette))\n\nfile_name = 'figures/n{}m{}d{}capacity{}range{}task{}ns{}_regret.png'.format(config['points_per_iter'], \n config['feature_dim'], config['label_dim'],config['mean_volunteer_attributes'][0],config['mean_volunteer_attributes'][1],config['mean_task_attributes'][0],config['num_sources'])\ndata = [regret_p2p,regret_mask,regret_all_data,regret_bandit]\nlabels = ['PROOF', 'PROOF+Mask','PROOF+Mask+All Data','Vanilla OFU']\nplot_data(data,labels,file_name)\n\nfile_name = 'figures/n{}m{}d{}capacity{}range{}task{}ns{}_match.png'.format(config['points_per_iter'], \n config['feature_dim'], config['label_dim'],config['mean_volunteer_attributes'][0],config['mean_volunteer_attributes'][1],config['mean_task_attributes'][0],config['num_sources'])\ndata = [regret_match_p2p,regret_match_mask,regret_match_all_data,regret_match_bandit]\nlabels = ['PROOF', 'PROOF+Mask','PROOF+Mask+All Data','Vanilla OFU']\nplot_data(data,labels,file_name)\n","repo_name":"naveenr414/food-rescue","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"74148243447","text":"# -*- coding: UTF-8 -*-\n\nimport math\nimport random\n\n\ndef fizzBuzz(n):\n '''\n 412. Fizz Buzz(reviw)\n 写一个程序,输出从 1 到 n 数字的字符串表示。\n\n 1. 如果 n 是3的倍数,输出“Fizz”;\n\n 2. 如果 n 是5的倍数,输出“Buzz”;\n\n 3.如果 n 同时是3和5的倍数,输出 “FizzBuzz”。\n '''\n\n res = []\n for i in range(1, n + 1):\n if i >= 5 and i % 3 == 0 and i % 5 == 0:\n res.append(\"FizzBuzz\")\n continue\n if i >= 3 and i % 3 == 0:\n res.append(\"Fizz\")\n continue\n if i >= 4 and i % 5 == 0:\n res.append(\"Buzz\")\n continue\n res.append(str(i))\n return res\n\n\ndef countPrimes(n): # TODO 应该再复习\n '''\n 204\t.计数质数\n 埃拉托斯特尼筛法(ieve of Eratosthenes)中,\n 我们从 2开始遍历到 根号n ,每次遍历从根号n 赋值到 n,先找到第一个质数2,\n 然后将其所有的倍数全部标记出来,然后到下一个质数3,\n 标记其所有倍数,一次类推,直到根号n,此时数组中未被标记的数字就是质数。\n 我们需要一个n-1长度的bool型数组来记录每个数字是否被标记,长度为n-1的原因是题目说是小于n的质数个数,并不包括n。\n 然后我们用两个for循环来实现埃拉托斯特尼筛法,难度并不是很大,代码如下所示:\n '''\n if n == 1 or n == 0:\n return 0\n bool = [True for i in range(n - 1)]\n bool[0] = False\n sqrts = math.ceil(math.sqrt(n))\n for i in range(2, int(sqrts)): # 从2到根号n向下取整\n if bool[i - 1]:\n for j in range(i * i, n, i): # i的倍数全部都标记\n bool[j - 1] = False\n res = 0\n for i in range(n - 1):\n if bool[i]:\n res += 1\n return res\n\n\ndef isPowerOfThree(n):\n if n <= 0:\n return False\n maxint = 0x7fffffff\n k = int(math.log(maxint, 3))\n\n b = 3 ** k\n\n return b % n == 0\n\n\ndef romanToInt(s):\n '''\n\n 13.罗马数字转整数\n 思路:正常情况下左边罗马数字比右边罗马数字大,这种情况下正常加\n 当出现特殊情况的时候,左边比右边数字小,但是之前已经加上之前的小值了,所以还要将多出来的值减去\n '''\n map = {\"I\": 1, \"V\": 5, \"X\": 10, \"L\": 50, \"C\": 100, \"D\": 500, \"M\": 1000}\n result = 0\n for i in range(len(s)):\n if i == 0 or map[s[i]] <= map[s[i - 1]]:\n result += map[s[i]]\n else:\n result += (map[s[i]] - 2 * map[s[i - 1]])\n return result\n\n\ndef hammingWeight(n):\n '''\n 191.位1的个数\n '''\n # new_n = bin(n)[2:].zfill(31)\n # print(new_n)\n # new_n = list(new_n)\n # return new_n.count('1')\n if n == 0:\n return 0\n res = 1\n while n > 2:\n res += n % 2\n n = math.floor(n / 2)\n return res\n\n\ndef reverseBits(n):\n '''\n 190.颠倒二进制位\n 依次将n的末尾位给result的末尾位,并且result向左移31次\n '''\n # l = list('{0:032b}'.format(n))\n # l = list(map(int, l))\n # l.reverse()\n # l = list(map(str, l))\n # s = ''.join(l)\n # return int(s, 2)\n res = 0\n for i in range(32):\n tmp = n & 1\n n = n >> 1\n res = (res << 1) | tmp\n return res\n\n\ndef generate(numRows):\n '''\n review\n 帕斯卡三角形\n 用两个数组保存临时结果\n 数组长度比层数多2\n 两边置0方便计算\n '''\n res = [[1]]\n dp = [0 for i in range(numRows + 2)]\n dp[1] = 1\n new_dp = [0 for i in range(numRows + 2)]\n for i in range(1, numRows):\n for j in range(1, i + 2):\n new_dp[j] = dp[j] + dp[j - 1]\n dp = new_dp[:]\n res.append(dp[1:i + 2])\n return res\n\n\ndef isValid(s):\n '''\n 20.有效的括号\n 用一个栈来保存对应的左括号,如果遇到右括号的时候从栈中弹出一个\n 因为是按顺序排列的左括号 弹出来的一定是相应的右括号\n 如果 不相等 就说明 括号没有对称\n '''\n stack = []\n dp = [\"(\", \"[\", \"{\"]\n fdp = [\")\", \"]\", \"}\"]\n for i in range(len(s)):\n if s[i] in dp:\n stack.append(dp.index(s[i]))\n elif len(stack) == 0:\n return False\n elif stack.pop() != fdp.index(s[i]):\n return False\n return True if len(stack) == 0 else False\n\n\ndef missingNumber(nums):\n '''\n 缺失的数字\n '''\n t = 0\n tmp = 0\n for i in range(len(nums)):\n t += i\n tmp += nums[i]\n t += len(nums)\n\n return t - tmp\n\n\n'''\n颠倒二进制位\n'''\n\n\ndef hammingDistance(x, y):\n '''\n 461.汉明距离(review)\n :param x:\n :param y:\n :return:\n '''\n # l1 = list('{0:032b}'.format(x))\n # l1 = list(map(int, l1))\n # l2 = list('{0:032b}'.format(y))\n # l2 = list(map(int, l2))\n #\n # res = 0\n #\n # for i in range(32):\n # if l1[i] != l2[i]: def canJump\n # res += 1\n #\n # return res\n res = 0\n for i in range(32):\n if (x & (1 << i)) ^ (y & (1 << i)):\n res += 1\n return res\n\n # 解法二\n # res = 0\n # num = bin(x ^ y)\n #\n # for i in range(2, len(num)):\n # if num[i] == \"1\":\n # res += 1\n # return res\n\n\nclass Solution(object):\n '''\n 384. 打乱数组(review)\n 打乱一个没有重复元素的数组。\n '''\n\n def __init__(self, nums):\n self.nums = nums\n \"\"\"\n :type nums: List[int]\n \"\"\"\n\n def reset(self):\n return self.nums\n \"\"\"\n Resets the array to its original configuration and return it.\n :rtype: List[int]\n \"\"\"\n\n def shuffle(self):\n \"\"\"\n Returns a random shuffling of the array.\n :rtype: List[int]\n \"\"\"\n p = self.nums[:]\n random.shuffle(p)\n return p\n\n # r = []\n # tmp = self.nums[:]\n # while tmp:\n # ran = int(random.uniform(0, len(tmp)))\n # r.append(tmp[ran])\n # tmp.remove(tmp[ran])\n # return r\n\n\ndef sortColors(nums):\n '''\n 75.颜色分类(review)\n :param nums:\n :return:\n '''\n\n lo, cur, hi = 0, 0, len(nums) - 1\n while cur <= hi:\n if nums[cur] == 0:\n nums[lo], nums[cur] = nums[cur], nums[lo]\n cur += 1\n lo += 1\n elif nums[cur] == 1:\n cur += 1\n else:\n nums[cur], nums[hi] = nums[hi], nums[cur]\n hi -= 1\n\nif __name__ == '__main__':\n print(sortColors([1, 0, 2, 2, 1, 0]))\n","repo_name":"fuyao-w/PYAlgorithmsAndDataStructures","sub_path":"mathquestion/MathQuestionOne.py","file_name":"MathQuestionOne.py","file_ext":"py","file_size_in_byte":6593,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"27504630581","text":"\"\"\"\nBasic example of regressor using Sibyl\n\n@author: Francesco Baldisserri\n@creation date: 24/07/2020\n\"\"\"\n\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\n\nfrom sibyl import predictor as pred\n\n\ndef main():\n X, y = datasets.fetch_california_housing(return_X_y=True) # No encoding needed since OmniEncoder recognizes discrete, continuous and categoricals\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n predrgr = pred.SibylRegressor()\n predrgr.search(X_train, y_train) # RandomizedGridSearchCV available but also fit method is available\n print(f\"Test score: {predrgr.score(X_test, y_test):.4f}\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"sirbradflies/Sibyl","sub_path":"sibyl/example_automl.py","file_name":"example_automl.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"36790257789","text":"#coding:utf-8\nimport pigpio\nimport RPi.GPIO as GPIO\nimport time\npin_servo = 27\n# 終端機需輸入(才能執行pigpiod)\n# sudo systemctl enable pigpiod\npwm = pigpio.pi()\npwm.set_mode(pin_servo, pigpio.OUTPUT)\npwm.set_PWM_frequency(pin_servo, 50) # 50Hz frequency\ndef destroy():\n pwm.set_PWM_dutycycle(pin_servo, 0)\n pwm.set_PWM_frequency(pin_servo, 0)\n# 輸入0 ~ 180度即可\n# 別超過180度\ndef setDirection(angle):\n # 0 = 停止轉動\n # 500 = 0度\n # 1500 = 90度\n # 2500 = 180度\n duty = 500 + (angle / 180) * 2000\n pwm.set_servo_pulsewidth(pin_servo, duty)\n print(\"角度=\", angle, \"-> duty=\", duty)\nsetDirection(100)\ntime.sleep(5)\nsetDirection(130)\n#time.sleep(5)\n#setDirection(100)\n","repo_name":"edwards414/Score-Michine-project","sub_path":"project/ctrl/motor/servo_motor.py","file_name":"servo_motor.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"} +{"seq_id":"30617294210","text":"'''\nEntity module.\n'''\nimport pygame\n\nclass Entity(pygame.sprite.Sprite):\n '''\n Base class which will be used for all entities in the game.\n '''\n\n def __init__(self, x, y, width, height, window, colour):\n '''\n Parameters:\n x : x-position of the players shuttle.\n y : x-position of the players shuttle.\n window : The pygame window.\n height : The height of the object.\n width : The width of the object.\n colour : RGB colour.\n '''\n pygame.sprite.Sprite.__init__(self)\n\n self.window = window\n self.colour = colour\n self.height = height\n \n self.rect = pygame.Rect(x, y, width, height)\n\n\n def draw_self(self):\n '''\n Draws object to window.\n '''\n pygame.draw.rect(self.window, self.colour, self.rect)\n","repo_name":"JosephReps/QPong","sub_path":"entity.py","file_name":"entity.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":"36084444832","text":"from PyQt5 import QtCore\nimport urllib.parse as parse\nfrom Structs import RequestSettings, MarkerSizes\nimport requests\nimport polyline\n\n\nclass Request:\n \"\"\"\n Class to encapsulate the requests of a resource and\n the creation of the corresponding urls used as resource.\n \"\"\"\n\n # static member variables\n # API base urls\n DB_BASE_URL = 'https://open-api.bahn.de/bin/rest.exe/'\n MAPS_BASE_URL = 'https://api.mapbox.com/styles/v1/mapbox/{0}/static/'\n EncodedSeparator = '%3A'\n\n # API-Properties key-words for Deutsche Bahn API\n UrlLang = '&lang='\n UrlDate = '&date='\n UrlTime = '&time='\n UrlId = '&id='\n UrlAuthKey = 'authKey='\n UrlLocationName = 'location.name?'\n UrlDepBoard = 'departureBoard?'\n UrlArrBoard = 'arrivalBoard?'\n UrlInput = '&input='\n\n # format strings for time and date\n DATE_FORMAT = 'yyyy-M-d'\n TIME_FORMAT = 'h:m'\n\n @staticmethod\n def formatColor(col):\n \"\"\"\n Formats given color to be able to use it in web-url\n :param col:\n :return: str\n \"\"\"\n return col.name().replace('#', '')\n\n @staticmethod\n def getResultFromServer(url: str) -> str:\n \"\"\"\n Establishes connection to the given url, reads and returns\n the result of this resource.\n :type url: str\n :rtype str\n \"\"\"\n\n return requests.get(url).content\n\n @staticmethod\n def getXMLStringConnectionDetails(url: str) -> str:\n \"\"\"\n Returns the result of the given url resource.\n Used for requesting the connection details from the reference link.\n :type url str\n :rtype str\n \"\"\"\n\n return Request.getResultFromServer(url)\n\n @staticmethod\n def getXMLStringStationRequest(loc: str, settings: RequestSettings) -> str:\n \"\"\"\n Creates url for requesting all locations that match to the given\n location loc.\n Request these locations and returns the XML-String.\n :type loc str\n :type settings RequestSettings\n :rtype str\n \"\"\"\n\n url = Request.createStationRequestURL(loc, settings)\n return Request.getResultFromServer(url)\n\n @staticmethod\n def getXMLStringConnectionRequest(date: QtCore.QDate, time: QtCore.QTime, identifier: int,\n isDeparture: bool, settings: RequestSettings) -> (str, str):\n \"\"\"\n Creates url for requesting connections from date,time,\n identifier (corresponding to a location) and a boolean departure\n flag variable.\n Request the connections and returns the XML-String.\n :type date QtCore.QDate\n :type time Qt.Core.QTime\n :type identifier int\n :type isDeparture bool\n :type settings RequestSettings\n :rtype (str,str)\n \"\"\"\n\n url = Request.createConnectionRequestURL(date, time, identifier, isDeparture, settings)\n return Request.getResultFromServer(url), url\n\n @staticmethod\n def regetXMLStringConnectionRequest(url: str, isDeparture: bool):\n if isDeparture:\n new_url = url.replace(Request.UrlArrBoard, Request.UrlDepBoard)\n else:\n new_url = url.replace(Request.UrlDepBoard, Request.UrlArrBoard)\n return Request.getResultFromServer(new_url), new_url\n\n @staticmethod\n def getMapWithLocations(coordinates: [tuple], markerIndex: int, settings: RequestSettings) -> str:\n \"\"\"\n Creates MabBox url for corresponding map with given coordinates and settings.\n Returns the raw requested data\n :type coordinates [tuple]\n :type markerIndex int\n :type settings RequestSettings\n :rtype str\n \"\"\"\n url = Request.createMapURL(coordinates, markerIndex, settings)\n return Request.getResultFromServer(url)\n\n @staticmethod\n def createConnectionRequestURL(date: QtCore.QDate, time: QtCore.QTime, identifier: int, isDeparture: bool,\n settings: RequestSettings) -> str:\n \"\"\"\n Builds and returns the url for requesting connection from date,time,\n identifier (corresponding to a location) and a boolean departure\n flag variable.\n :type date QtCore.QDate\n :type time Qt.Core.QTime\n :type identifier int\n :type isDeparture bool\n :type settings RequestSettings\n :rtype str\n\n \"\"\"\n # build date-String\n dateString = date.toString(Request.DATE_FORMAT)\n # build and encode timeString\n timeString = time.toString(Request.TIME_FORMAT).replace(\":\", Request.EncodedSeparator)\n\n base = '{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}'\n # build last part of url\n lastPart = base.format(Request.UrlAuthKey, settings.DBKey, Request.UrlLang, settings.LANGUAGE, Request.UrlId,\n str(identifier), Request.UrlDate, dateString, Request.UrlTime, timeString\n )\n # build complete url\n base = '{0}{1}{2}'\n if isDeparture:\n return base.format(Request.DB_BASE_URL, Request.UrlDepBoard, lastPart)\n else:\n return base.format(Request.DB_BASE_URL, Request.UrlArrBoard, lastPart)\n\n @staticmethod\n def createStationRequestURL(loc: str, settings: RequestSettings) -> str:\n \"\"\"\n Builds and returns the url for requesting all locations that match to the\n given location loc.\n :type loc str\n :type settings RequestSettings\n :rtype str\n \"\"\"\n\n base = '{0}{1}{2}{3}{4}x{5}{6}{7}'\n return base.format(Request.DB_BASE_URL, Request.UrlLocationName, Request.UrlAuthKey, settings.DBKey,\n Request.UrlLang, settings.LANGUAGE, Request.UrlInput, parse.quote(loc.replace(\" \", \"\"))\n )\n\n @staticmethod\n def createMapURL(coordinates: [tuple], markerIndex: int, settings: RequestSettings) -> str:\n \"\"\"\n Builds and returns the url for requesting the map with coordinates and settings.\n Use size, path- and marker color from settings.\n Create full path with all coordinates, for each coordinate add marker with\n default size except the specified markerIndex, these coordinate gets an other\n color specified in settings\n :type coordinates [tuple]\n :type markerIndex int\n :type settings RequestSettings\n :rtype str\n \"\"\"\n\n res = Request.MAPS_BASE_URL.format(settings.MapTypes[settings.MAPTYPE])\n poly = polyline.encode([(y, x) for x, y in coordinates])\n path = 'path-{0}+{1}-{2}({3}),'.format(settings.PATH_SIZE, Request.formatColor(settings.PATH_COLOR),\n settings.PATH_OPACITY, poly)\n endpart = '/auto/{0}x{1}?access_token={2}'.format(str(settings.width), str(settings.height), settings.MapBoxKey)\n res += path + Request.createFullCoordinateString(markerIndex, coordinates, settings) + endpart\n return res\n\n @staticmethod\n def createFullCoordinateString(markerIndex: int, cords: [tuple], settings) -> str:\n \"\"\"\n Takes a list of geographical locations and returns a string\n that is formatted for use in MabBox static api\n :type markerIndex int\n :type cords [tuple]\n :type settings RequestSettings\n :rtype str\n \"\"\"\n\n col = Request.formatColor(settings.MARKER_COLOR)\n if settings.labelType == \"None\":\n res = ''.join(map(lambda j:\n Request.createCoordinateString(col, MarkerSizes[settings.MARKER_SIZE],\n cords[j]),\n [i for i in range(len(cords)) if i != markerIndex]))\n return res + (Request.createCoordinateString(Request.formatColor(settings.MARKER_COLOR_SPECIAL),\n MarkerSizes[settings.MARKER_SIZE_SPECIAL],\n cords[markerIndex]))[:-1]\n labels = list(range(1, len(cords) + 1))\n if settings.labelType == \"alphabetic\":\n offset = 96\n labels = list(map(lambda k: chr(k + offset), labels))\n res = ''.join(map(\n lambda j: Request.createCoordinateStringLabel(col, labels[j], MarkerSizes[settings.MARKER_SIZE], cords[j]),\n [i for i in range(len(cords)) if i != markerIndex]))\n return res + (Request.createCoordinateStringLabel(Request.formatColor(settings.MARKER_COLOR_SPECIAL),\n labels[markerIndex],\n MarkerSizes[settings.MARKER_SIZE_SPECIAL],\n cords[markerIndex]))[:-1]\n\n @staticmethod\n def createCoordinateStringLabel(col: str, label, size: str, loc: tuple) -> str:\n \"\"\"\n Takes a geographical location and returns a string\n that is formatted for use in MapBox static api request.\n :type col str\n :type label str\n :type size: str\n :type loc tuple\n :rtype str\n \"\"\"\n\n # single marker formatted as pin-size-name+color(lon,lat)\n return 'pin-{0}-{1}+{2}{3},'.format(size, label, col, str(loc).replace(' ', ''))\n\n @staticmethod\n def createCoordinateString(col: str, size: str, loc: tuple) -> str:\n \"\"\"\n Takes a geographical location and returns a string\n that is formatted for use in MapBox static api request.\n :type col str\n :type size: str\n :type loc tuple\n :rtype str\n \"\"\"\n\n # single marker formatted as pin-size-name+color(lon,lat)\n return 'pin-{0}+{1}{2},'.format(size, col, str(loc).replace(' ', ''))\n","repo_name":"Aimmig/dbTrainConnection","sub_path":"src/Request.py","file_name":"Request.py","file_ext":"py","file_size_in_byte":9825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"25082985098","text":"import csv\nimport requests\nfrom email.message import EmailMessage\nimport smtplib\n\nfrom email.mime.text import MIMEText\n\nfrom Validation import*\n\nSENDER = input(\"Please Enter your mail ID : \")\nPASSWORD = input(\"Please Enter your mail password : \")\n\ndef send_email(subject):\n try:\n with open(\"sample.csv\") as file:\n reader = csv.reader(file)\n next(reader)\n \n for Message , addr , Phone , Country , Schedule in reader:\n email_address = addr\n response = requests.get(\n \"https://isitarealemail.com/api/email/validate\",\n params = {'email': email_address})\n\n status = response.json()['status'] \n if status == \"valid\":\n print(\"******************************************\")\n print(f\"{addr} : email is valid\") \n msg = EmailMessage()\n html = '''\n \n \n \n \n \n \n
\n \n

'''+Message+'''

\n \n \n
\n \n \n '''\n Message = MIMEText(html , \"html\")\n\n msg.set_content(Message)\n msg[\"Subject\"] = subject\n msg[\"From\"] = SENDER\n msg[\"To\"] = addr\n server = smtplib.SMTP_SSL(\"smtp.gmail.com\", 465)\n server.login(SENDER, PASSWORD) \n server.send_message(msg)\n server.quit()\n print(f'Sent to {addr}')\n elif status == \"invalid\":\n print(f\"{addr} : email is invalid\")\n else:\n print(\"email was unknown\")\n checkValidefields(Phone)\n Check_message_content(Message)\n print(f\"Country of candidate {Country}\")\n print(f\"Email will send on {Schedule}\")\n print(\"************************************************************\")\n \n print(\"Successful Sent Email\")\n \n\n \n except:\n print(\"Email Sent Failed : Please check all requirement \")\n\n\n\n\nsend_email(subject=\"Screen-Magic\")\n\n","repo_name":"Shashi-Chaurasia/My_Python_SendEmail_Code","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"9251509263","text":"from urllib.parse import quote_plus, unquote_plus\nimport random\nimport time\nimport re\n\nimport scrapy\nimport scrapetube\nfrom fuzzywuzzy import process\nfrom scrapy.http import HtmlResponse\n\nfrom spider.items import Meme\nfrom .helpers import Utils, Invalids\n\n\nclass MemeSpider(scrapy.Spider):\n name = \"memes\"\n allowed_domains = [\"youtube.com\", \"google.com\", \"html.duckduckgo.com\"]\n\n def __init__(self, count=200, **kwargs):\n videos = list(\n scrapetube.get_channel(\"UCaHT88aobpcvRFEuy4v5Clg\", limit=count, sleep=0.2)\n )\n self.start_urls = [\n \"https://youtube.com/oembed?url=https://youtube.com/watch?v=\" + v[\"videoId\"]\n for v in videos\n ]\n\n super().__init__(**kwargs)\n\n def parse(self, response: HtmlResponse):\n string = response.json()[\"title\"].replace(\"“\", '\"').replace(\"”\", '\"')\n\n title = Utils.regex.sub(\"\", string).strip()\n words = re.findall('\"([^\"]*)\"', string)\n meme = None\n\n if len(words) > 0:\n meme = quote_plus(\n \"\".join([s.split(\"_\")[0] for s in words[0]]).strip().lower()\n ).strip()\n else:\n meme = quote_plus(Utils.tokenize(title).lower()).strip()\n\n yield scrapy.Request(\n f\"https://knowyourmeme.com/search?context=entries&sort=relevance&q={meme}+category_name%3Ameme\",\n callback=self.parse_kym_url,\n headers={\"User-Agent\": \"Mozilla/5.0\"},\n dont_filter=True,\n meta={\"meme\": meme, \"youtube_id\": response.url.split(\"?v=\")[1]},\n )\n\n def parse_kym_url(self, response: HtmlResponse):\n meme = unquote_plus(response.meta[\"meme\"].replace(\"+\", \" \").strip().title())\n results = response.xpath(\n '//tbody[@class=\"entry-grid-body infinite\"]//a/text()'\n ).getall()\n\n while \"\\n\" in results:\n results.remove(\"\\n\")\n\n matches = process.extract(meme, results, limit=len(results))\n\n try:\n meme = max(matches, key=lambda x: x[-1])[0]\n url = (\n \"https://knowyourmeme.com/memes/\"\n + meme.replace(\"(\", \"\")\n .replace(\")\", \"\")\n .replace(\" \", \"-\")\n .replace(\"/-\", \"\")\n .replace(\",\", \"\")\n .replace(\"’\", \"\")\n .replace(\"!\", \"\")\n .replace(\"'\", \"\")\n .lower()\n )\n\n yield scrapy.Request(\n f\"https://google.com/complete/search?client=chrome&q={quote_plus(meme)}\",\n callback=self.parse_acc_google,\n headers={\"User-Agent\": \"Mozilla/5.0\"},\n dont_filter=True,\n meta={\n \"meme\": meme,\n \"url\": url,\n \"youtube_id\": response.meta[\"youtube_id\"],\n },\n )\n time.sleep(0.5)\n except Exception:\n yield scrapy.Request(\n f\"https://google.com/search?q={meme}+know+your+meme\",\n callback=self.parse_kym_google,\n headers={\"User-Agent\": \"Mozilla/5.0\"},\n dont_filter=True,\n meta={\"meme\": meme, \"youtube_id\": response.meta[\"youtube_id\"]},\n )\n time.sleep(0.5)\n\n def parse_acc_google(self, response: HtmlResponse):\n keywords = response.json()[1]\n\n yield scrapy.Request(\n response.meta[\"url\"],\n callback=self.parse_kym_table,\n headers={\"User-Agent\": \"Mozilla/5.0\"},\n dont_filter=True,\n meta={\n \"meme\": response.meta[\"meme\"],\n \"url\": response.meta[\"url\"],\n \"keywords\": keywords,\n \"youtube_id\": response.meta[\"youtube_id\"],\n },\n )\n\n def parse_kym_google(self, response: HtmlResponse):\n try:\n url = (\n [\n url\n for url in response.xpath(\"//a/@href\").getall()\n if \"knowyourmeme.com/memes\" in url\n ][0]\n .split(\"?q=\")[1]\n .split(\"&sa\")[0]\n )\n\n yield scrapy.Request(\n url,\n callback=self.parse_kym_table,\n dont_filter=True,\n meta={\n \"meme\": response.meta[\"meme\"],\n \"youtube_id\": response.meta[\"youtube_id\"],\n },\n headers={\"User-Agent\": \"Mozilla/5.0\"},\n )\n time.sleep(1.7)\n except Exception:\n print(\n f'Yielding limited info as nothing was found for {response.meta[\"meme\"]} :('\n )\n\n item = Meme()\n\n item[\"title\"] = response.meta[\"meme\"]\n item[\"youtube_id\"] = response.meta[\"youtube_id\"]\n item[\"types\"] = \"None\"\n item[\"status\"] = \"None\"\n item[\"year\"] = \"None\"\n item[\"image\"] = \"None\"\n item[\"other\"] = \"None\"\n\n yield item\n\n def parse_kym_table(self, response: HtmlResponse):\n details = response.xpath('//div[@class = \"details\"]//text()').getall()\n\n while \"\\n\" in details:\n details.remove(\"\\n\")\n details = [d.replace(\"\\n\", \"\") for d in details]\n\n try:\n if details[2] == Invalids.RESEARCH[0]:\n del details[2]\n del details[2]\n except IndexError:\n pass\n\n item = Meme()\n item[\"title\"] = response.meta[\"meme\"]\n item[\"youtube_id\"] = response.meta[\"youtube_id\"]\n try:\n item[\"keywords\"] = response.meta[\"keywords\"]\n except KeyError:\n item[\"keywords\"] = \"None\"\n\n types = \"None\"\n try:\n types = details[-(len(details) - details.index(\"Type:\") - 1) :]\n except ValueError:\n pass\n item[\"types\"] = types\n\n item[\"status\"] = details[1]\n item[\"origin\"] = details[3]\n item[\"year\"] = details[5]\n\n try:\n item[\"image\"] = random.choice(\n response.xpath(\n '//img[@class=\" kym-image image-auto-link\"]/@data-src'\n ).getall()\n )\n except IndexError:\n item[\"image\"] = Utils.QUESTION_MARK\n\n try:\n item[\"other\"] = random.choice(response.xpath(\"//iframe/@src\").getall())\n except IndexError:\n item[\"other\"] = Utils.QUESTION_MARK\n\n print(item.__dict__)\n\n yield item\n time.sleep(1.7)\n","repo_name":"memealchemy/broom","sub_path":"spider/spiders/memes.py","file_name":"memes.py","file_ext":"py","file_size_in_byte":6560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"24926825212","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\nfrom bs4 import BeautifulSoup #Sayfaya dahil ediyoruz\nimport requests\n\nhttp_request = requests.get(\"https://www.twitter.com/talhaklc\")\ncontent = BeautifulSoup(http_request.content,\"html.parser\")\n\ni=1\nfor tweets in content.find(id=\"stream-items-id\").find_all(\"div\",\"js-tweet-text-container\"): #sayfanın kaynak koduna baktığınızda gördüğünüz yapıya göre burayı belirliyoruz\n print(\"{} ) {}\".format(str(i),tweets.get_text().strip().encode(\"utf-8\"))) \n i+=1\n","repo_name":"talhaklc/Python-KullaniciTwitCekme","sub_path":"twitcekme.py","file_name":"twitcekme.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"tr","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"39050656767","text":"\"\"\"\nReturns Apple's, Google's, and Facebook's stocks from 2019 in Json format\n\nData is acquired through the Financial Modeling Prep API\n\"\"\"\n\nimport requests\n\ndef fetch_2019_data():\n\n\t#Connect to API and get historical data from January 1st 2019 - current date\n\turl = 'https://financialmodelingprep.com/api/v3/historical-price-full/AAPL,GOOG,FB'\n\tparam = {'from': '2019-01-01'}\n\tresp = requests.get(url = url, params = param)\n\tdata = None\n\t#Make sure there is a proper connection to API\n\tif resp.ok:\n\t\tdata = resp.json()['historicalStockList']\n\telse:\n\t\tprint('Connection to API Failed')\n\treturn data","repo_name":"kamkarm/Stock-Analysis","sub_path":"initialize_table/fetch_data.py","file_name":"fetch_data.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"7055242583","text":"def solution(a, b):\n answer = 0\n \n if a == b: \n answer = a\n else:\n if a > b:\n a, b = b, a\n for i in range(a, b+1):\n answer += i \n \n return answer\n\n'''\n# 다른 사람 풀이\ndef adder(a, b):\n\n if a > b: a, b = b, a\n\n return sum(range(a,b+1))\n'''","repo_name":"cijbest/TIL","sub_path":"Algorithm/Programmers/두 정수 사이의 합.py","file_name":"두 정수 사이의 합.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"77"} +{"seq_id":"34817825980","text":"import nltk\nimport sklearn\nimport numpy as np\nimport pandas as pd\nimport re\nfrom gensim.models import doc2vec\nimport gensim\nimport pickle\nimport random\nimport concurrent.futures\n\ndfa = pd.read_csv('/home/lanna/Dropbox/Insight/X-Cite/df_PLOS.csv') #PLOS articles\ndfb = pd.read_csv('/home/lanna/Dropbox/Insight/X-Cite/df_BioMed.csv') #BioMed pub articles\n\ndf = pd.concat([dfa, dfb])\n\n#Which do not have DOIs?\n#nodoi = pd.DataFrame(data = {'Reference':list(set(df.Reference[pd.isnull(df.DOI)])), 'DOI': \"\"})\n#nodoi.to_csv(\"/home/lanna/Dropbox/Shared/beadyeyes/findDOI.csv\",index=False)\n#Make it so that:\n#1. Tags are Ref#'s that can later be used to index either a DOI or reference\n\n#Remove rows with NaNs for Reference\ndf = df.dropna(subset=['Reference'])\n####################################################\n# 1. Clean-up sentences\n####################################################\n#Clean References:\n#Remove PubMed, View Article and PubMed Central at the end of the citations \ntarget = []\nfor i in df['Reference']:\n m = re.search(r\"(PubMed|View Article|PubMed Central)\", i)\n if not not m:\n target.append(i[:m.start(1)])\n else:\n target.append(i)\n\ntarget2 = []\nfor i in target:\n tmp = re.sub(r\"\\n\",\"\",i) #Get rid of extra \\n\n tmp = re.sub(r\"(doi\\: *10\\.+)\",\"\",tmp) #Get rid of everything after \"doi:\"\n tmp = re.sub(r\"(pmid\\: \\d+)\",\"\",tmp) #Get rid of everything after \"pmid:\"\n tmp = re.sub(r\"(pmid\\:\\d+)\",\"\",tmp) #Get rid of everything after \"pmid:\"\n tmp = re.sub(r\"(http\\:\\/\\/.+)\",\"\",tmp) #Get rid of everything after \"http://\"\n tmp = re.sub(r\"(10\\.\\d+\\/.+)\",\"\",tmp) #Get rid of evertyhing after a doi number of some sort\n tmp = re.sub(r\"(10\\.\\\\u\\d+\\/.+)\",\"\",tmp) #Get rid of evertyhing after a doi number of some sort\n tmp = ' '.join(tmp.split()) #Get rid of extra spaces\n target2.append(tmp)\n\n\ndf['Reference'] = target2 #Add cleaned Reference to dataframe\n\n#############################################################\n#Make it so that:\n#1. Tags are Ref#'s that can later be used to index either a DOI or reference\n#############################################################\n#Create a unique ID for each DOI\ntmp = [\"ID_\"+str(i) for i in list(range(0,len(set(df.DOI))))]\nbyDOI = pd.DataFrame(data = {'ID': tmp,'DOI': list(set(df.DOI))})\n\n#Merge with main data frame to create df1\ndf1 = pd.merge(byDOI,df, on='DOI')\n\n#If DOI = NaN; or, if ID = ID_0\nnum = len(set(df1.ID))\ntt = list(set(df1.Reference[pd.isnull(df1.DOI)]))\nfor i in range(0,len(tt)):\n df1.ID[df1.Reference == tt[i]] = \"ID_\"+str(num)\n num+=1\n\n#*\ndf1['freq'] = df1.groupby('Reference')['Reference'].transform('count') #Add frequency of citations to data frame\n\n#################################################\n# VALIDATION SET\n#################################################\n#Select 1,000 of each category for Test Set\ndef rand_smpl(mylist,num=1000):\n rand_smpl = [ mylist[i] for i in sorted(random.sample(range(len(mylist)), num)) ]\n return rand_smpl\n\ns1 = rand_smpl(list(set(df1[df1['freq']==2].Reference)),1000)\ns2 = rand_smpl(list(set(df1[df1['freq']==3].Reference)),1000)\ns3 = rand_smpl(list(set(df1[df1['freq']==4].Reference)),1000)\ns4 = rand_smpl(list(set(df1[df1['freq']==5].Reference)),1000)\ns5 = rand_smpl(list(set(df1[df1['freq']==6].Reference)),1000)\ns6 = rand_smpl(list(set(df1[df1['freq']==7].Reference)),1000)\ns7 = rand_smpl(list(set(df1[df1['freq']==8].Reference)),1000)\ns8 = rand_smpl(list(set(df1[df1['freq']>=9].Reference)),1000)\n\n\n#From df1 select first data sentences corresponding to references and remove from df1\n#import multiprocessing\ndef validation_Indices(j):\n try:\n mylist = [list(df1[df1.Reference==i].index)[0] for i in j]\n except:\n print('error with item')\n return mylist\n\nexecutor = concurrent.futures.ThreadPoolExecutor(12)\nfutures = [executor.submit(validation_Indices, item) for item in [s1,s2,s3,s4,s5,s6,s7,s8]]\nconcurrent.futures.wait(futures)\n\nvalidationIndices=[]\nfor i in futures:\n validationIndices.append(i.result())\n\nvalidationIndices = [item for sublist in validationIndices for item in sublist]\n\n# validationIndices = [] \n# for j in [s1,s2,s3,s4,s5,s6,s7,s8]:\n# tmp = [list(df1[df1.Reference==i].index)[0] for i in j]\n# validationIndices.append(tmp)\n#Save Validation set\ndfValidate = df1.ix[validationIndices]\ndfValidate['freq'] = dfValidate.freq-1\n#Drop Validation Set from data frame\ndfTrain= df1.drop(df1.index[validationIndices])\n\n\ndfValidate.to_csv('/home/lanna/Dropbox/Insight/X-Cite/dfValidate.csv')\ndfTrain.to_csv('/home/lanna/Dropbox/Insight/X-Cite/dfTrain.csv')\n#################################################\n# TRAINING SET!\n#################################################\n#dfTrain = df1.copy()\n#Multiple labels for each sentence\n#What are the unique sentences?\nsentences2 = list(set(dfTrain['Sentence']))\n\n#LabeledSentence objects:\n#Each such object represents a single sentence, and consists of two simple lists: a list of words and a list of labels\ndef label_Sentences(sentence):\n #Create a LabeledSentence object:\n #1. For each unique sentences (first argument)-- tokenized sentence (split sentences by words) \n #2. The corresponding Reference labels (second argument)\n tmp = dfTrain.ix[dfTrain[dfTrain['Sentence']==sentence].index.tolist()].Reference.tolist()\n return tmp\n\nexecutor = concurrent.futures.ProcessPoolExecutor(12)\nfutures = []\nnum = 0\nfor item in sentences2:\n num += 1\n print(str(round(num*100/len(sentences2),3))+'%', end='\\r')\n futures.append(executor.submit(label_Sentences, item))\nconcurrent.futures.wait(futures)\n\ntags=[]\nfor i in futures:\n tags.append(i.result())\n\n#Pickle/save list of tags for sentences\nf = open('/home/lanna/Dropbox/Insight/tags','wb')\npickle.dump(tags,f) \n\nLabeledSentences = []\nfor i in range(0,len(sentences2)):\n LabeledSentences.append(doc2vec.LabeledSentence(sentences2[i].split(), tags[i]))\n \n#https://linanqiu.github.io/2015/05/20/word2vec-sentiment/\n\nnfeatures = 300\nmodel = gensim.models.doc2vec.Doc2Vec(workers = 10, size=nfeatures, window=10, min_count=1,alpha=0.025, min_alpha=0.025)\n#Build the vocabulary table: digesting all the words and filtering out the unique words, and doing some basic counts on them\nmodel.build_vocab(LabeledSentences) \n\n#Train Doc2Vec\nfrom random import shuffle\n#Randomize order of sentences\nfor epoch in range(10):\n shuffle(LabeledSentences)\n model.train(LabeledSentences)\n model.alpha -= 0.002 # decrease the learning rate\n model.min_alpha = model.alpha # fix the learning rate, no decay\n\n# store the model to mmap-able files\nmodel.save('/home/lanna/Dropbox/Insight/X-Cite/doc2vec_model.doc2vec')\n\n#################################################\n# VALIDATION SET\n#################################################\n#http://blog.dato.com/how-to-evaluate-machine-learning-models-part-2a-classification-metrics\nmodel_loaded = gensim.models.doc2vec.Doc2Vec.load('/home/lanna/Dropbox/Insight/X-Cite/doc2vec_model.doc2vec')\ndfValidate = pd.read_csv('/home/lanna/Dropbox/Insight/X-Cite/dfValidate.csv')\n\ndef cleanInput(userInput):\n Input1 = re.sub(\"[^a-zA-Z]\", \" \", userInput) #Only extract words\n Input = Input1.lower().split() #Tokenize sentences: convert to lower case and split them into individual words\n return Input\n\n#Function to determine rank of \ndef rankValidation(datf):\n sentenceInput = datf['Sentence']\n actualReference = datf['Reference']\n freq = datf['freq']\n cI = cleanInput(sentenceInput) #Clean userInput sentence\n userVec = model_loaded.infer_vector(cI) #Infer a vector for given post-bulk training document. Document should be a list of (word) tokens.\n output = model_loaded.docvecs.most_similar(positive=[userVec], topn = 60921600) #Find the top-N most similar docvecs known from training. \n tt = pd.DataFrame(output, columns=['Citation','probability']) #turn into pandas dataframe\n refIndex = tt[tt.Citation==actualReference].index.tolist()[0] #Find index where actualReference occurs\n rank = tt.rank(0).probability.iloc[refIndex]\n prob = tt.probability[refIndex]\n out = pd.DataFrame(data = {'Reference': [actualReference], 'Sentence': [sentenceInput], 'freq': [freq], 'model_prob': [prob], 'model_rank': [rank]})\n return out\n\nvalidationResults = pd.DataFrame(columns=['Reference','Sentence','freq','model_prob','model_rank'])\nvalidationResults.to_csv('/home/lanna/Dropbox/Insight/X-Cite/validationResults.csv',header=True, index=False)\n\nchunk = []\nfor i in range(0,len(dfValidate)+100,100):\n chunk.append(i)\n\n#BREAK THIS UP SOMEHOW BY GROUPS OF 10!\nn = 0\nwhile n < 8000:\n dftmp = dfValidate.copy().iloc[range(chunk[n],chunk[n+1])]\n executor = concurrent.futures.ProcessPoolExecutor(10)\n futures = []\n num = 0\n for index, row in dftmp.iterrows():\n num+=1\n print(str(round(num*100/len(dftmp),3))+'%', end='\\r')\n futures.append(executor.submit(rankValidation, row))\n concurrent.futures.wait(futures)\n\n for j in futures:\n tmp = j.result()\n with open('/home/lanna/Dropbox/Insight/X-Cite/validationResults.csv',mode='a') as f:\n tmp.to_csv(f, header=False, index=False)\n n+=1\n\n#Read in Results\nvResults = pd.read_csv('/home/lanna/Dropbox/Insight/X-Cite/validationResults.csv')\nvResults['freq'] = vResults.freq-1\n\nvAvgs = pd.DataFrame(columns=['freq','mean_model_prob'])\nfor i in range(1,9):\n mean_model_prob = vResults[vResults.freq==i].model_prob.mean()\n vAvgs = vAvgs.append(pd.DataFrame(data = {'freq':[i],'mean_model_prob':[mean_model_prob]}))\n\n#Now for if frequency is 9 or greater\nmean_model_prob = vResults[vResults.freq>8].model_prob.mean()\nvAvgs = vAvgs.append(pd.DataFrame(data = {'freq':9,'mean_model_prob':[mean_model_prob]}))\n\nimport matplotlib.pyplot as plt\nplt.plot(vAvgs.freq, vAvgs.mean_model_prob)\nplt.ylabel('Mean Cosine similarity')\nplt.xlabel('Citation Frequency')\nplt.show()\n\n#################################################\n# PREDICT\n#################################################\n# load the model back\nmodel_loaded = gensim.models.doc2vec.Doc2Vec.load('/home/lanna/Dropbox/Insight/X-Cite/doc2vec_model.doc2vec')\n\nuserInput = 'Chimpanzee habituation allows for direct monitoring and hence precise censuses, but is a lengthy process which is necessarily restricted to small numbers of individuals, and may not be ethically appropriate or logistically feasible for many populations' #Input sentence\n\ndef cleanInput(userInput):\n Input1 = re.sub(\"[^a-zA-Z]\", \" \", userInput) #Only extract words\n Input = Input1.lower().split() #Tokenize sentences: convert to lower case and split them into individual words\n return Input\n\ncI = cleanInput(userInput) #Clean userInput sentence\n\n#Infer a vector for given post-bulk training document. Document should be a list of (word) tokens.\nuserVec = model_loaded.infer_vector(cI) \n#Find the top-N most similar docvecs known from training. Positive docs contribute positively towards the similarity, negative docs negatively. \n#This method computes cosine similarity between a simple mean of the projection weight vectors of the given docs. Docs may be specified as vectors, integer indexes of trained docvecs, or if the documents were originally presented with string tags, by the corresponding tags.\n#Here, doc is given as infered vector\noutput = model_loaded.docvecs.most_similar(positive=[userVec])\nthe_result = pd.DataFrame(output, columns=['Citation','probability'])\n\n","repo_name":"lannajin/X-Cite","sub_path":"1 Doc2Vec.py","file_name":"1 Doc2Vec.py","file_ext":"py","file_size_in_byte":11461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"38745051127","text":"class Solution:\n def combinationSum2(self, candidates, target):\n \"\"\"\n :type candidates: List[int]\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n def search(sum,path,index,res):\n if sum==0:\n if path not in res:\n res.append(path)\n if sum<0:\n return\n for i in range(index+1,len(candidates)):\n search(sum-candidates[i],path+[candidates[i]],i,res)\n answer = []\n candidates.sort()\n search(target,[],-1,answer)\n return answer\n\na =Solution()\nprint(a.combinationSum2([2,5,2,1,2],5))","repo_name":"sillytheif/leetcode_record","sub_path":"code_2019/num_0040.py","file_name":"num_0040.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"36564335451","text":"import csv\r\nimport requests\r\nimport re\r\nfrom bs4 import BeautifulSoup\r\n\r\nheaders = {\"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36\"}\r\n\r\nfilename = \"[쿠팡]스마트워치 검색.csv\"\r\nf = open(filename,\"w\",encoding=\"utf-8-sig\",newline=\"\")\r\nwriter = csv.writer(f)\r\ntitle =[\"제품명\",\"가격(원)\",\"평점\",\"평점 수\",\"링크\"]\r\nwriter.writerow(title)\r\n\r\nfor i in range(1,28): # 1페이지부터 27페이지까지\r\n \r\n url = \"https://www.coupang.com/np/search?q=%EC%8A%A4%EB%A7%88%ED%8A%B8%EC%9B%8C%EC%B9%98&channel=user&component=&eventCategory=SRP&trcid=&traid=&sorter=scoreDesc&minPrice=&maxPrice=&priceRange=&filterType=&listSize=36&filter=&isPriceRange=false&brand=&offerCondition=&rating=0&page={}&rocketAll=false&searchIndexingToken=&backgroundColor=\".format(i)\r\n res = requests.get(url, headers=headers)\r\n res.raise_for_status()\r\n\r\n soup = BeautifulSoup(res.text,\"lxml\") # 가져온 문서를 lxml을 통해 BeautifulSoup 객체로 만들기\r\n\r\n items = soup.find_all(\"li\", attrs={\"class\":re.compile(\"^search-product\")}) # 제품가져오기\r\n\r\n for item in items :\r\n link = \"https://www.coupang.com\" + item.a[\"href\"] #링크 추가\r\n ad = item.find_all(\"span\",attrs={\"class\":\"ad-badge-text\"}) #광고 제품가져오기\r\n if ad:\r\n continue #만약 광고제품이면 다음거로 넘어가기\r\n name = item.find(\"div\",attrs={\"class\":\"name\"}).get_text() # 제품명 가져오기\r\n name = name.replace(\",\",\"\")\r\n price = item.find(\"strong\", attrs={\"class\":\"price-value\"}).get_text() # 가격가져오기\r\n price = price.replace(\",\",\"\") # 문자열 변경\r\n rate = item.find(\"em\", attrs={\"class\":\"rating\"}) #평점 가져오기\r\n if rate:\r\n rate=rate.get_text()\r\n else:\r\n continue # 평점이 없으면 다음거로 넘어가기\r\n \r\n rate_num = item.find(\"span\", attrs={\"class\":\"rating-total-count\"}) #평점수 가져오기\r\n if rate_num: #(평점수)\r\n rate_num = rate_num.get_text()\r\n rate_num = rate_num[1:-1] #(평점수)이기때문에 처음인덱스와 마지막 인덱스를 제외해서 ()벗겨주기\r\n else:\r\n continue #평점수가 없으면 다음거로 넘어가기\r\n\r\n # 리뷰 500이상,평점 4.5이상만\r\n if float(rate) >= 4.5 and int(rate_num) >= 500 and int(price) < 300000:\r\n data = name, price, rate,rate_num,link\r\n data = list(data)\r\n writer.writerow(data)\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"start0ys/pyWebscraping","sub_path":"Webscraping/Basic/bt4_3.py","file_name":"bt4_3.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"19056370921","text":"\"\"\"Individual fine-tuning approach for CPT and baseline models.\"\"\"\nimport logging\nimport math\nimport os\n\nimport numpy as np\nimport torch\nfrom sklearn.metrics import f1_score\nfrom tqdm.auto import tqdm\nfrom transformers import (\n MODEL_MAPPING,\n AdamW,\n get_scheduler,\n)\n\nlogger = logging.getLogger(__name__)\nMODEL_CONFIG_CLASSES = list(MODEL_MAPPING.keys())\nMODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)\n\n\nclass Appr(object):\n\n def __init__(self, args):\n super().__init__()\n self.args = args\n return\n\n def train(self, model, accelerator, train_loader, test_loader):\n special_lr = ['adapter']\n try:\n adapter_lr = self.args.adapter_lr\n except Exception as e:\n print(\n \"Notice: You are using the same learning rate for adapter and backbone model.\")\n adapter_lr = self.args.lr\n\n optimizer_grouped_parameters = [\n {\n 'params': [p for n, p in model.named_parameters() if\n not any(nd in n for nd in special_lr) and p.requires_grad],\n 'weight_decay': self.args.weight_decay,\n 'lr': self.args.lr,\n },\n # Set different learning rate for adapter.\n {\n 'params': [p for n, p in model.named_parameters() if p.requires_grad and 'adapter' in n],\n 'weight_decay': self.args.weight_decay,\n 'lr': adapter_lr,\n }\n ]\n # Set the optimizer\n optimizer = AdamW(optimizer_grouped_parameters)\n\n num_update_steps_per_epoch = math.ceil(\n len(train_loader) / self.args.gradient_accumulation_steps)\n if self.args.max_train_steps is None:\n self.args.max_train_steps = self.args.epoch * num_update_steps_per_epoch\n else:\n self.args.epoch = math.ceil(\n self.args.max_train_steps / num_update_steps_per_epoch)\n\n lr_scheduler = get_scheduler(\n name=self.args.lr_scheduler_type,\n optimizer=optimizer,\n num_warmup_steps=self.args.num_warmup_steps,\n num_training_steps=self.args.max_train_steps,\n )\n\n # Prepare everything with the accelerator\n model, optimizer, train_loader, test_loader = accelerator.prepare(\n model, optimizer, train_loader, test_loader)\n\n # Train!\n logger.info(\"***** Running training *****\")\n logger.info(\n f\"Pretrained Model = {self.args.model_name_or_path}, Dataset name = {self.args.dataset_name}, seed = {self.args.seed}\")\n\n for epoch in range(self.args.epoch):\n print(\"Epoch {} started\".format(epoch))\n train_acc, training_loss = self.train_epoch(\n model, optimizer, train_loader, accelerator, lr_scheduler)\n print(\"train acc = {:.4f}, training loss = {:.4f}\".format(\n train_acc, training_loss))\n\n micro_f1, macro_f1, acc, test_loss = self.eval(\n model, test_loader, accelerator)\n\n logger.info(\n \"{} On {}, last epoch macro_f1 = {:.4f}, acc = {:.4f} (seed={})\".format(self.args.model_name_or_path,\n self.args.dataset_name,\n macro_f1,\n acc, self.args.seed))\n\n if accelerator.is_main_process:\n if self.args.few_shot:\n progressive_f1_path = os.path.join(self.args.output_dir + '/../',\n 'few_shot_progressive_f1_' + str(self.args.seed))\n progressive_acc_path = os.path.join(self.args.output_dir + '/../',\n 'few_shot_progressive_acc_' + str(self.args.seed))\n else:\n progressive_f1_path = os.path.join(self.args.output_dir + '/../',\n 'progressive_f1_' + str(self.args.seed))\n progressive_acc_path = os.path.join(self.args.output_dir + '/../',\n 'progressive_acc_' + str(self.args.seed))\n print('progressive_f1_path: ', progressive_f1_path)\n print('progressive_acc_path: ', progressive_acc_path)\n\n if os.path.exists(progressive_f1_path):\n f1s = np.loadtxt(progressive_f1_path)\n accs = np.loadtxt(progressive_acc_path)\n\n else:\n f1s = np.zeros(\n (self.args.ntasks, self.args.ntasks), dtype=np.float32)\n accs = np.zeros(\n (self.args.ntasks, self.args.ntasks), dtype=np.float32)\n\n f1s[self.args.pt_task][self.args.ft_task] = macro_f1\n np.savetxt(progressive_f1_path, f1s, '%.4f', delimiter='\\t')\n\n accs[self.args.pt_task][self.args.ft_task] = acc\n np.savetxt(progressive_acc_path, accs, '%.4f', delimiter='\\t')\n\n if self.args.ft_task == self.args.ntasks - 1: # last ft task, we need a final one\n if self.args.few_shot:\n final_f1 = os.path.join(\n self.args.output_dir + '/../', 'few_shot_f1_' + str(self.args.seed))\n final_acc = os.path.join(\n self.args.output_dir + '/../', 'few_shot_acc_' + str(self.args.seed))\n\n forward_f1 = os.path.join(self.args.output_dir + '/../',\n 'few_shot_forward_f1_' + str(self.args.seed))\n forward_acc = os.path.join(self.args.output_dir + '/../',\n 'few_shot_forward_acc_' + str(self.args.seed))\n else:\n final_f1 = os.path.join(\n self.args.output_dir + '/../', 'f1_' + str(self.args.seed))\n final_acc = os.path.join(\n self.args.output_dir + '/../', 'acc_' + str(self.args.seed))\n\n forward = os.path.join(\n self.args.output_dir + '/../', 'forward_f1_' + str(self.args.seed))\n forward_acc = os.path.join(\n self.args.output_dir + '/../', 'forward_acc_' + str(self.args.seed))\n\n print('final_f1: ', final_f1)\n print('final_acc: ', final_acc)\n\n if self.args.baseline == 'one':\n with open(final_acc, 'w') as file, open(final_f1, 'w') as f1_file:\n for j in range(accs.shape[1]):\n file.writelines(str(accs[j][j]) + '\\n')\n f1_file.writelines(str(f1s[j][j]) + '\\n')\n\n else:\n with open(final_acc, 'w') as file, open(final_f1, 'w') as f1_file:\n for j in range(accs.shape[1]):\n file.writelines(str(accs[-1][j]) + '\\n')\n f1_file.writelines(str(f1s[-1][j]) + '\\n')\n\n with open(forward_acc, 'w') as file, open(forward_f1, 'w') as f1_file:\n for j in range(accs.shape[1]):\n file.writelines(str(accs[j][j]) + '\\n')\n f1_file.writelines(str(f1s[j][j]) + '\\n')\n\n def train_epoch(self, model, optimizer, dataloader, accelerator, lr_scheduler):\n # Only show the progress bar once on each machine.\n progress_bar = tqdm(range(len(dataloader)),\n disable=not accelerator.is_local_main_process)\n model.train()\n train_acc = 0.0\n training_loss = 0.0\n total_num = 0.0\n t = torch.LongTensor([self.args.ft_task]).to(model.device)\n s = self.args.smax\n for batch, inputs in enumerate(dataloader):\n\n res = model(**inputs, return_dict=True, t=t, s=s)\n outp = res.logits\n loss = res.loss\n optimizer.zero_grad()\n accelerator.backward(loss)\n optimizer.step()\n lr_scheduler.step()\n\n pred = outp.max(1)[1]\n train_acc += (inputs['labels'] == pred).sum().item()\n training_loss += loss.item()\n total_num += inputs['labels'].size(0)\n\n progress_bar.update(1)\n\n return train_acc / total_num, training_loss / total_num\n\n def eval(self, model, dataloader, accelerator):\n model.eval()\n label_list = []\n prediction_list = []\n total_loss = 0\n total_num = 0\n t = torch.LongTensor([self.args.ft_task]).to(accelerator.device)\n s = self.args.smax\n # Only show the progress bar once on each machine.\n progress_bar = tqdm(range(len(dataloader)),\n disable=not accelerator.is_local_main_process)\n with torch.no_grad():\n for _, inputs in enumerate(dataloader):\n input_ids = inputs['input_ids']\n res = model(**inputs, return_dict=True, t=t, s=s)\n\n real_b = input_ids.size(0)\n loss = res.loss\n outp = res.logits\n pred = outp.max(1)[1]\n\n total_loss += loss.data.cpu().numpy().item() * real_b\n total_num += real_b\n label_list += inputs['labels'].cpu().numpy().tolist()\n prediction_list += pred.cpu().numpy().tolist()\n progress_bar.update(1)\n\n micro_f1 = f1_score(label_list, prediction_list, average='micro')\n macro_f1 = f1_score(label_list, prediction_list, average='macro')\n accuracy = sum([float(label_list[i] == prediction_list[i]) for i in range(len(label_list))]) * 1.0 / len(\n prediction_list)\n\n return micro_f1, macro_f1, accuracy, total_loss / total_num\n","repo_name":"UIC-Liu-Lab/CPT","sub_path":"approaches/finetune.py","file_name":"finetune.py","file_ext":"py","file_size_in_byte":9992,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"77"} +{"seq_id":"31824568944","text":"from typing_extensions import Final\n\nfrom bemani.backend.base import Base, Status\nfrom bemani.protocol import Node\nfrom bemani.common import Time, CardCipher\n\n\nclass PASELIHandler(Base):\n \"\"\"\n A mixin that can be used to provide PASELI services to a game.\n\n Handle PASELI requests. The game will check out a session at the beginning\n of the game, make PASELI purchases against that session, and then close it\n at the end of of a game. This handler ensures that this works for all games.\n \"\"\"\n\n INFINITE_PASELI_AMOUNT: Final[int] = 57300\n\n \"\"\"\n Override this in your subclass if the particular game/series\n needs a different padding amount to display PASELI transactions\n on the operator menu.\n \"\"\"\n paseli_padding: int = 1\n\n def handle_eacoin_checkin_request(self, request: Node) -> Node:\n if not self.config.paseli.enabled:\n # Refuse to respond, we don't have PASELI enabled\n print(\"PASELI not enabled, ignoring eacoin request\")\n root = Node.void(\"eacoin\")\n root.set_attribute(\"status\", str(Status.NOT_ALLOWED))\n return root\n\n root = Node.void(\"eacoin\")\n cardid = request.child_value(\"cardid\")\n pin = request.child_value(\"passwd\")\n\n if cardid is None or pin is None:\n # Refuse to return anything\n print(\"Invalid eacoin checkin request, missing cardid or pin\")\n root.set_attribute(\"status\", str(Status.NO_PROFILE))\n return root\n\n userid = self.data.local.user.from_cardid(cardid)\n if userid is None:\n # Refuse to do anything\n print(\"No user for eacoin checkin request\")\n root.set_attribute(\"status\", str(Status.NO_PROFILE))\n return root\n\n valid = self.data.local.user.validate_pin(userid, pin)\n if not valid:\n # Refuse to do anything\n print(\"User entered invalid pin for eacoin checkin request\")\n root.set_attribute(\"status\", str(Status.INVALID_PIN))\n return root\n\n session = self.data.local.user.create_session(userid)\n\n if self.config.paseli.infinite:\n balance = PASELIHandler.INFINITE_PASELI_AMOUNT\n else:\n if self.config.machine.arcade is None:\n # There's no arcade for this machine, but infinite is not\n # enabled, so there's no way to find a balance.\n balance = 0\n else:\n balance = self.data.local.user.get_balance(\n userid, self.config.machine.arcade\n )\n\n root.add_child(Node.s16(\"sequence\", 0))\n root.add_child(Node.u8(\"acstatus\", 0))\n root.add_child(Node.string(\"acid\", \"DUMMY_ID\"))\n root.add_child(Node.string(\"acname\", \"DUMMY_NAME\"))\n root.add_child(Node.s32(\"balance\", balance))\n root.add_child(Node.string(\"sessid\", session))\n return root\n\n def handle_eacoin_opcheckin_request(self, request: Node) -> Node:\n if not self.config.paseli.enabled:\n # Refuse to respond, we don't have PASELI enabled\n print(\"PASELI not enabled, ignoring eacoin request\")\n root = Node.void(\"eacoin\")\n root.set_attribute(\"status\", str(Status.NOT_ALLOWED))\n return root\n\n root = Node.void(\"eacoin\")\n passwd = request.child_value(\"passwd\")\n\n if passwd is None:\n # Refuse to return anything\n print(\"Invalid eacoin checkin request, missing passwd\")\n root.set_attribute(\"status\", str(Status.NO_PROFILE))\n return root\n\n if self.config.machine.arcade is None:\n # Machine doesn't belong to an arcade\n print(\"Machine doesn't belong to an arcade\")\n root.set_attribute(\"status\", str(Status.NO_PROFILE))\n return root\n\n arcade = self.data.local.machine.get_arcade(self.config.machine.arcade)\n if arcade is None:\n # Refuse to do anything\n print(\"No arcade for operator checkin request\")\n root.set_attribute(\"status\", str(Status.NO_PROFILE))\n return root\n\n if arcade.pin != passwd:\n # Refuse to do anything\n print(\"User entered invalid pin for operator checkin request\")\n root.set_attribute(\"status\", str(Status.INVALID_PIN))\n return root\n\n session = self.data.local.machine.create_session(arcade.id)\n root.add_child(Node.string(\"sessid\", session))\n return root\n\n def handle_eacoin_consume_request(self, request: Node) -> Node:\n if not self.config.paseli.enabled:\n # Refuse to respond, we don't have PASELI enabled\n print(\"PASELI not enabled, ignoring eacoin request\")\n root = Node.void(\"eacoin\")\n root.set_attribute(\"status\", str(Status.NOT_ALLOWED))\n return root\n\n def make_resp(status: int, balance: int) -> Node:\n root = Node.void(\"eacoin\")\n root.add_child(Node.u8(\"acstatus\", status))\n root.add_child(Node.u8(\"autocharge\", 0))\n root.add_child(Node.s32(\"balance\", balance))\n return root\n\n session = request.child_value(\"sessid\")\n payment = request.child_value(\"payment\")\n service = request.child_value(\"service\")\n details = request.child_value(\"detail\")\n if session is None or payment is None:\n # Refuse to do anything\n print(\"Invalid eacoin consume request, missing sessid or payment\")\n return make_resp(2, 0)\n\n userid = self.data.local.user.from_session(session)\n if userid is None:\n # Refuse to do anything\n print(\"Invalid session for eacoin consume request\")\n return make_resp(2, 0)\n\n if self.config.paseli.infinite:\n balance = PASELIHandler.INFINITE_PASELI_AMOUNT - payment\n else:\n if self.config.machine.arcade is None:\n # There's no arcade for this machine, but infinite is not\n # enabled, so there's no way to find a balance, assume failed\n # consume payment.\n balance = None\n else:\n # Look up the new balance based on this delta. If there isn't enough,\n # we will end up returning None here and exit without performing.\n balance = self.data.local.user.update_balance(\n userid, self.config.machine.arcade, -payment\n )\n\n if balance is None:\n print(\"Not enough balance for eacoin consume request\")\n return make_resp(\n 1,\n self.data.local.user.get_balance(\n userid, self.config.machine.arcade\n ),\n )\n else:\n self.data.local.network.put_event(\n \"paseli_transaction\",\n {\n \"delta\": -payment,\n \"balance\": balance,\n \"service\": -service,\n \"reason\": details,\n \"pcbid\": self.config.machine.pcbid,\n },\n userid=userid,\n arcadeid=self.config.machine.arcade,\n )\n\n return make_resp(0, balance)\n\n def handle_eacoin_getlog_request(self, request: Node) -> Node:\n if not self.config.paseli.enabled:\n # Refuse to respond, we don't have PASELI enabled\n print(\"PASELI not enabled, ignoring eacoin request\")\n root = Node.void(\"eacoin\")\n root.set_attribute(\"status\", str(Status.NOT_ALLOWED))\n return root\n\n root = Node.void(\"eacoin\")\n sessid = request.child_value(\"sessid\")\n logtype = request.child_value(\"logtype\")\n target = request.child_value(\"target\")\n limit = request.child_value(\"perpage\")\n offset = request.child_value(\"offset\")\n\n # Try to determine whether its a user or an arcade session\n userid = self.data.local.user.from_session(sessid)\n if userid is None:\n arcadeid = self.data.local.machine.from_session(sessid)\n else:\n arcadeid = None\n\n # Bail out if we don't have any idea what session this is\n if userid is None and arcadeid is None:\n print(\"Unable to determine session type\")\n return root\n\n # If we're a user session, also look up the current arcade\n # so we display only entries that happened on this arcade.\n if userid is not None:\n arcade = self.data.local.machine.get_arcade(self.config.machine.arcade)\n if arcade is None:\n print(\"Machine doesn't belong to an arcade\")\n return root\n arcadeid = arcade.id\n\n # Now, look up all transactions for this specific group\n events = self.data.local.network.get_events(\n userid=userid,\n arcadeid=arcadeid,\n event=\"paseli_transaction\",\n )\n\n # Further filter it down to the current PCBID\n events = [event for event in events if event.data.get(\"pcbid\") == target]\n\n # Grab the end of day today as a timestamp\n end_of_today = Time.end_of_today()\n time_format = \"%Y-%m-%d %H:%M:%S\"\n date_format = \"%Y-%m-%d\"\n\n # Set up common structure\n lognode = Node.void(logtype)\n topic = Node.void(\"topic\")\n lognode.add_child(topic)\n summary = Node.void(\"summary\")\n lognode.add_child(summary)\n\n # Display what day we are summed to\n topic.add_child(Node.string(\"sumdate\", Time.format(Time.now(), date_format)))\n\n if logtype == \"last7days\":\n # We show today in the today total, last 7 days prior in the week total\n beginning_of_today = end_of_today - Time.SECONDS_IN_DAY\n end_of_week = beginning_of_today\n beginning_of_week = end_of_week - Time.SECONDS_IN_WEEK\n\n topic.add_child(\n Node.string(\"sumfrom\", Time.format(beginning_of_week, date_format))\n )\n topic.add_child(Node.string(\"sumto\", Time.format(end_of_week, date_format)))\n today_total = sum(\n [\n -event.data.get_int(\"delta\")\n for event in events\n if event.timestamp >= beginning_of_today\n and event.timestamp < end_of_today\n ]\n )\n\n today_total = sum(\n [\n -event.data.get_int(\"delta\")\n for event in events\n if event.timestamp >= beginning_of_today\n and event.timestamp < end_of_today\n ]\n )\n week_txns = [\n -event.data.get_int(\"delta\")\n for event in events\n if event.timestamp >= beginning_of_week\n and event.timestamp < end_of_week\n ]\n week_total = sum(week_txns)\n if len(week_txns) > 0:\n week_avg = int(sum(week_txns) / len(week_txns))\n else:\n week_avg = 0\n\n # We display the totals for each day starting with yesterday and up through 7 days prior.\n # Index starts at 0 = yesterday, 1 = the day before, etc...\n items = []\n for days in range(0, 7):\n end_of_day = end_of_week - (days * Time.SECONDS_IN_DAY)\n start_of_day = end_of_day - Time.SECONDS_IN_DAY\n\n items.append(\n sum(\n [\n -event.data.get_int(\"delta\")\n for event in events\n if event.timestamp >= start_of_day\n and event.timestamp < end_of_day\n ]\n )\n )\n\n topic.add_child(Node.s32(\"today\", today_total))\n topic.add_child(Node.s32(\"average\", week_avg))\n topic.add_child(Node.s32(\"total\", week_total))\n summary.add_child(Node.s32_array(\"items\", items))\n\n if logtype == \"last52weeks\":\n # Start one week back, since the operator can look at last7days for newer stuff.\n beginning_of_today = end_of_today - Time.SECONDS_IN_DAY\n end_of_52_weeks = beginning_of_today - Time.SECONDS_IN_WEEK\n\n topic.add_child(\n Node.string(\n \"sumfrom\",\n Time.format(\n end_of_52_weeks - (52 * Time.SECONDS_IN_WEEK), date_format\n ),\n )\n )\n topic.add_child(\n Node.string(\"sumto\", Time.format(end_of_52_weeks, date_format))\n )\n\n # We index backwards, where index 0 = the first week back, 1 = the next week back after that, etc...\n items = []\n for weeks in range(0, 52):\n end_of_range = end_of_52_weeks - (weeks * Time.SECONDS_IN_WEEK)\n beginning_of_range = end_of_range - Time.SECONDS_IN_WEEK\n\n items.append(\n sum(\n [\n -event.data.get_int(\"delta\")\n for event in events\n if event.timestamp >= beginning_of_range\n and event.timestamp < end_of_range\n ]\n )\n )\n\n summary.add_child(Node.s32_array(\"items\", items))\n\n if logtype == \"eachday\":\n start_ts = Time.now()\n end_ts = Time.now()\n weekdays = [0] * 7\n\n for event in events:\n event_day = Time.days_into_week(event.timestamp)\n weekdays[event_day] = weekdays[event_day] - event.data.get_int(\"delta\")\n if event.timestamp < start_ts:\n start_ts = event.timestamp\n\n topic.add_child(Node.string(\"sumfrom\", Time.format(start_ts, date_format)))\n topic.add_child(Node.string(\"sumto\", Time.format(end_ts, date_format)))\n summary.add_child(Node.s32_array(\"items\", weekdays))\n\n if logtype == \"eachhour\":\n start_ts = Time.now()\n end_ts = Time.now()\n hours = [0] * 24\n\n for event in events:\n event_hour = int(\n (event.timestamp % Time.SECONDS_IN_DAY) / Time.SECONDS_IN_HOUR\n )\n hours[event_hour] = hours[event_hour] - event.data.get_int(\"delta\")\n if event.timestamp < start_ts:\n start_ts = event.timestamp\n\n topic.add_child(Node.string(\"sumfrom\", Time.format(start_ts, date_format)))\n topic.add_child(Node.string(\"sumto\", Time.format(end_ts, date_format)))\n summary.add_child(Node.s32_array(\"items\", hours))\n\n if logtype == \"detail\":\n history = Node.void(\"history\")\n lognode.add_child(history)\n\n # Respect details paging\n if offset is not None:\n events = events[offset:]\n if limit is not None:\n events = events[:limit]\n\n # Output the details themselves\n for event in events:\n card_no = \"\"\n if event.userid is not None:\n user = self.data.local.user.get_user(event.userid)\n if user is not None:\n cards = self.data.local.user.get_cards(user.id)\n if len(cards) > 0:\n card_no = CardCipher.encode(cards[0])\n\n item = Node.void(\"item\")\n history.add_child(item)\n item.add_child(\n Node.string(\"date\", Time.format(event.timestamp, time_format))\n )\n item.add_child(Node.s32(\"consume\", -event.data.get_int(\"delta\")))\n item.add_child(Node.s32(\"service\", -event.data.get_int(\"service\")))\n item.add_child(Node.string(\"cardtype\", \"\"))\n item.add_child(\n Node.string(\"cardno\", \" \" * self.paseli_padding + card_no)\n )\n item.add_child(Node.string(\"title\", \"\"))\n item.add_child(Node.string(\"systemid\", \"\"))\n\n if logtype == \"lastmonths\":\n year, month, _ = Time.todays_date()\n this_month = Time.timestamp_from_date(year, month)\n last_month = Time.timestamp_from_date(year, month - 1)\n month_before = Time.timestamp_from_date(year, month - 2)\n\n topic.add_child(\n Node.string(\"sumfrom\", Time.format(month_before, date_format))\n )\n topic.add_child(Node.string(\"sumto\", Time.format(this_month, date_format)))\n\n for start, end in [(month_before, last_month), (last_month, this_month)]:\n year, month, _ = Time.date_from_timestamp(start)\n\n items = []\n for day in range(0, 31):\n begin_ts = start + (day * Time.SECONDS_IN_DAY)\n end_ts = begin_ts + Time.SECONDS_IN_DAY\n if begin_ts >= end:\n # Passed the end of this month\n items.append(0)\n else:\n # Sum up all the txns for this day\n items.append(\n sum(\n [\n -event.data.get_int(\"delta\")\n for event in events\n if event.timestamp >= begin_ts\n and event.timestamp < end_ts\n ]\n )\n )\n\n item = Node.void(\"item\")\n summary.add_child(item)\n item.add_child(Node.s32(\"year\", year))\n item.add_child(Node.s32(\"month\", month))\n item.add_child(Node.s32_array(\"items\", items))\n\n root.add_child(Node.u8(\"processing\", 0))\n root.add_child(lognode)\n return root\n\n def handle_eacoin_opchpass_request(self, request: Node) -> Node:\n if not self.config.paseli.enabled:\n # Refuse to respond, we don't have PASELI enabled\n print(\"PASELI not enabled, ignoring eacoin request\")\n root = Node.void(\"eacoin\")\n root.set_attribute(\"status\", str(Status.NOT_ALLOWED))\n return root\n\n root = Node.void(\"eacoin\")\n oldpass = request.child_value(\"passwd\")\n newpass = request.child_value(\"newpasswd\")\n\n if oldpass is None or newpass is None:\n # Refuse to return anything\n print(\"Invalid eacoin pass change request, missing passwd\")\n root.set_attribute(\"status\", str(Status.NO_PROFILE))\n return root\n\n if self.config.machine.arcade is None:\n # Machine doesn't belong to an arcade\n print(\"Machine doesn't belong to an arcade\")\n root.set_attribute(\"status\", str(Status.NO_PROFILE))\n return root\n\n arcade = self.data.local.machine.get_arcade(self.config.machine.arcade)\n if arcade is None:\n # Refuse to do anything\n print(\"No arcade for operator pass change request\")\n root.set_attribute(\"status\", str(Status.NO_PROFILE))\n return root\n\n if arcade.pin != oldpass:\n # Refuse to do anything\n print(\"User entered invalid pin for operator pass change request\")\n root.set_attribute(\"status\", str(Status.INVALID_PIN))\n return root\n\n arcade.pin = newpass\n self.data.local.machine.put_arcade(arcade)\n return root\n\n def handle_eacoin_checkout_request(self, request: Node) -> Node:\n if not self.config.paseli.enabled:\n # Refuse to respond, we don't have PASELI enabled\n print(\"PASELI not enabled, ignoring eacoin request\")\n root = Node.void(\"eacoin\")\n root.set_attribute(\"status\", str(Status.NOT_ALLOWED))\n return root\n\n session = request.child_value(\"sessid\")\n if session is not None:\n # Destroy the session so it can't be used for any other purchases\n self.data.local.user.destroy_session(session)\n\n root = Node.void(\"eacoin\")\n return root\n\n def handle_eacoin_opcheckout_request(self, request: Node) -> Node:\n if not self.config.paseli.enabled:\n # Refuse to respond, we don't have PASELI enabled\n print(\"PASELI not enabled, ignoring eacoin request\")\n root = Node.void(\"eacoin\")\n root.set_attribute(\"status\", str(Status.NOT_ALLOWED))\n return root\n\n session = request.child_value(\"sessid\")\n if session is not None:\n # Destroy the session so it can't be used for any other purchases\n self.data.local.machine.destroy_session(session)\n\n root = Node.void(\"eacoin\")\n return root\n","repo_name":"DragonMinded/bemaniutils","sub_path":"bemani/backend/core/eacoin.py","file_name":"eacoin.py","file_ext":"py","file_size_in_byte":21278,"program_lang":"python","lang":"en","doc_type":"code","stars":185,"dataset":"github-code","pt":"77"} +{"seq_id":"70792485049","text":"import sys, heapq\n\n## 입력을 빠르게 하기 위한 함수\ninput = sys.stdin.readline\n## 입력받을 갯수\nnumber = int(input())\ndatas, heap = [], []\nfor i in range(number):\n temp = int(input())\n datas.append(temp)\n ## heap에 추가\n # 기본 heap은 최소 힙이라서 (-num, num)으로 값을 주어서 우선순위를 반대로\n heapq.heappush(heap, (-temp, temp))\n if temp == 0:\n print(heapq.heappop(heap)[1])","repo_name":"boring-km/Python_Algorithm","sub_path":"algorithm/baekjoon_heap_11279.py","file_name":"baekjoon_heap_11279.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"36238051903","text":"import random\nimport cv2\nimport torch\nimport numpy as np\nfrom pathlib import Path\nimport pydicom\nfrom pydicom.filebase import DicomBytesIO\nimport torch.distributed as dist\nimport dicomsdl\ntry:\n import redis\n storage = redis.Redis()\nexcept ImportError:\n pass\n\n\ndecoder = None\n\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\n\ndef crop_roi(image):\n copy_image = image.copy()\n copy_image[copy_image < 20] = 0\n return image[:, copy_image.sum(axis=0) > 1000]\n\n\ndef sync_masters(var):\n objects = [var]\n torch.distributed.broadcast_object_list(objects, src=0)\n return objects[0]\n\n\ndef normalised_to_8bit(image):\n xmin = image.min()\n xmax = image.max()\n norm = np.empty_like(image, dtype=np.uint8)\n dicomsdl.util.convert_to_uint8(image, norm, xmin, xmax)\n return norm\n\n\ndef parse_arg(s: str, default_args=None):\n results = s.split(\"@\")\n if len(results) == 1:\n main = results[0]\n args = {}\n else:\n main = results[0]\n args = [x.split(\"=\") for x in results[1].split(\"&\")]\n args = {key: eval(value) for key, value in args}\n if default_args is None:\n default_args = {}\n default_args.update(args)\n return main, default_args\n\n\ndef load_image(item, base_dir):\n return np.load(f\"{base_dir}/{item.image_id}.npz\")[\"data\"]\n\n\ndef flatten(xss):\n return [x for xs in xss for x in xs]\n\n\ndef init_decoder():\n global decoder\n import nvjpeg2k\n decoder = nvjpeg2k.Decoder()\n\n\ndef load_dicom(path, force_slow=False):\n dcmfile = pydicom.dcmread(path)\n reverse = dcmfile.PhotometricInterpretation == \"MONOCHROME1\"\n if not force_slow and dcmfile.file_meta.TransferSyntaxUID == '1.2.840.10008.1.2.4.90':\n with open(path, 'rb') as f:\n raw = DicomBytesIO(f.read())\n ds = pydicom.dcmread(raw)\n offset = ds.PixelData.find(b\"\\x00\\x00\\x00\\x0C\")\n hackedbitstream = bytearray()\n hackedbitstream.extend(ds.PixelData[offset:])\n return decoder.decode(hackedbitstream), reverse, dcmfile\n else:\n return dcmfile.pixel_array, reverse, dcmfile\n\n\ndef dicom_to_2k(dicom_file, output_dir):\n \"\"\"将某个 dicom 文件转换成 2K jepg 图像,并保存为文件,方便 dali 读取解压\n\n 返回 True 保存成功,False 保存失败\n \"\"\"\n dicom_file = Path(dicom_file)\n output_dir = Path(output_dir)\n dcmfile = pydicom.dcmread(dicom_file)\n if dcmfile.file_meta.TransferSyntaxUID == '1.2.840.10008.1.2.4.90':\n with open(dicom_file, 'rb') as fp:\n raw = DicomBytesIO(fp.read())\n ds = pydicom.dcmread(raw)\n offset = ds.PixelData.find(b\"\\x00\\x00\\x00\\x0C\")\n hackedbitstream = bytearray()\n hackedbitstream.extend(ds.PixelData[offset:])\n with open(output_dir / f\"{dicom_file.name}.jp2\", \"wb\") as binary_file:\n binary_file.write(hackedbitstream)\n return True\n else:\n return False\n\n\ndef get_ensemble_image(image, mode=\"flip+rotate\"):\n assert len(image.shape) == 3 and (image.shape[0] == 3 or image.shape[0] == 1)\n if isinstance(image, torch.Tensor):\n image = image.cpu().numpy()\n images = [image]\n\n if \"flip\" in mode:\n images += [\n image[:, :, ::-1],\n image[:, ::-1, :]\n ]\n\n if \"rotate\" in mode:\n transpose_image = image.transpose(0, 2, 1)\n images += [\n transpose_image,\n transpose_image[:, :, ::-1],\n transpose_image[:, ::-1, :],\n ]\n\n return torch.from_numpy(np.stack(images, axis=0))\n\n\nclass Infer():\n\n def __init__(self, model, tta=None):\n self.model = model\n self.tta = tta\n\n def batch_infer(self, batch):\n if self.tta is None:\n return self.model(batch)\n logits = []\n for i in range(batch.shape[0]):\n images = get_ensemble_image(batch[i], self.tta)\n logit = self.model(images.cuda())\n logit = torch.mean(logit, dim=0, keepdim=True)\n logits.append(logit)\n return torch.cat(logits, dim=0)\n\n\ndef all_gather_list(data):\n world_size = torch.distributed.get_world_size()\n if world_size == 1:\n return data\n data_list = [None for _ in range(world_size)]\n torch.distributed.all_gather_object(data_list, data)\n return flatten(data_list)\n\n\ndef convert_sync_batchnorm(module, process_group=None):\n # convert both BatchNorm and BatchNormAct layers to Synchronized variants\n module_output = module\n if isinstance(module, torch.nn.modules.batchnorm._BatchNorm):\n if isinstance(module, BatchNormAct2d):\n # convert timm norm + act layer\n module_output = SyncBatchNormAct(\n module.num_features,\n module.eps,\n module.momentum,\n module.affine,\n module.track_running_stats,\n process_group=process_group,\n )\n # set act and drop attr from the original module\n module_output.act = module.act\n module_output.drop = module.drop\n else:\n # convert standard BatchNorm layers\n module_output = torch.nn.SyncBatchNorm(\n module.num_features,\n module.eps,\n module.momentum,\n module.affine,\n module.track_running_stats,\n process_group,\n )\n if module.affine:\n with torch.no_grad():\n module_output.weight = module.weight\n module_output.bias = module.bias\n module_output.running_mean = module.running_mean\n module_output.running_var = module.running_var\n module_output.num_batches_tracked = module.num_batches_tracked\n if hasattr(module, \"qconfig\"):\n module_output.qconfig = module.qconfig\n for name, child in module.named_children():\n module_output.add_module(name, convert_sync_batchnorm(child, process_group))\n del module\n return module_output\n\n\ndef load_image_from_dicom(path):\n image, reverse, _ = load_dicom(path, force_slow=True)\n image = image.astype(np.float32)\n image = normalised_to_8bit(image)\n if reverse:\n image = 255 - image\n return image\n\n\ndef load_original_image(item):\n \"\"\" 返回 0 - 255 的 uint8 格式的单通道图片 \"\"\"\n if item.fold < 10:\n # return load_image_from_dicom(f\"/home/featurize/data/rsna-breast-cancer-detection/train_images/{item.patient_id}/{item.image_id}.dcm\")\n return np.load(f\"/home/featurize/rsna_datasets/roi/{item.image_id}.npz\")[\"data\"]\n elif item.fold >= 10 and item.fold < 20:\n # CMMD 数据集\n patient_id, suffix = item.image_id.split(\"_\")\n path = list(Path(f\"/home/featurize/work/rsna/data/CMMD/TheChineseMammographyDatabase/CMMD/{patient_id}\").glob(\"**/*.dcm\"))[int(suffix) - 1]\n return load_image_from_dicom(path)\n elif item.fold >= 20 and item.fold < 30:\n path = Path(f\"/home/featurize/work/rsna/data/INbreast-2012/INbreast Release 1.0/AllDICOMs/{item.image_id}\")\n return load_image_from_dicom(path)\n elif item.fold >= 30 and item.fold < 40:\n path = Path(f\"/home/featurize/work/rsna/data/King-Abdulaziz-University-Mammogram-Dataset/{item.image_id}\")\n return cv2.imread(path.as_posix()).mean(axis=2).astype(np.uint8)\n elif item.fold >= 40 and item.fold < 50:\n path = Path(f\"/home/featurize/work/rsna/data/vindr-mammo/vindr-mammo-a-large-scale-benchmark-dataset-for-computer-aided-detection-and-diagnosis-in-full-field-digital-mammography-1.0.0/images/{item.image_id}\")\n return load_image_from_dicom(path)\n","repo_name":"louis-she/rsna-2022-public","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7634,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"77"} +{"seq_id":"72280652410","text":"class Solution:\n def maxCoins(self, piles: List[int]) -> int:\n piles.sort(reverse = True)\n a = len(piles) // 3\n b = 0\n c = 1\n for i in range(a):\n b += piles[c]\n c += 2\n return b\n","repo_name":"Joephy527/A2SV-Competitive-programing","sub_path":"maximum-number-of-coins-you-can-get.py","file_name":"maximum-number-of-coins-you-can-get.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"34060077303","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 24 15:47:12 2019\n\n@author: Will\n\"\"\"\n\ncube=float(input(\"Give a number\"))\ntest=True\nepsilon=0.01\nguess=(cube/2)\nnum_guesses=0\nwhile test:\n num_guesses+=1\n if abs((guess**3))-abs(cube)>=epsilon:\n guess/=2\n else:\n guess=guess*3/2\n if(epsilon/10)<=abs((guess**3))-abs(cube) None:\n self.vehicles.clear()\n for v in vehicles_dict:\n self.vehicles.add(Hex(v[\"position\"][\"x\"], v[\"position\"][\"y\"], v[\"position\"][\"z\"]))\n\n def update_vehicle(self, old_pos: Hex, new_pos: Hex) -> None:\n self.vehicles.remove(old_pos)\n self.vehicles.add(new_pos)\n\n def get_closest_in_list(self, start: Hex, lst: List[Hex]) -> Hex:\n min_dist, closest = self.size * 2, None\n for h in lst:\n dist = Hex.distance(start, h)\n if dist < min_dist:\n min_dist, closest = dist, h\n return closest\n\n def hex_is_free(self, h: Hex) -> bool:\n return h not in self.obstacles and h not in self.vehicles and self.in_map_boundaries(h)\n\n def in_map_boundaries(self, hex: Hex) -> bool:\n return max(abs(hex.x), abs(hex.y), abs(hex.z)) <= self.size\n\n def get_free_neighbours(self, center: Hex) -> List[Hex]:\n results = []\n for d in DIRECTIONS:\n res = center + d\n if self.in_map_boundaries(res) and res not in self.obstacles:\n results.append(res)\n return results\n\n # all hexes in the area with self as center\n def get_hexes_in_range(self, center, n) -> List[Hex]:\n results = []\n for x in range(-n, n + 1):\n for y in range(max(-n, -x - n), min(n, -x + n) + 1):\n res = center + Hex(x, y, -x - y)\n if self.in_map_boundaries(res) and res not in self.obstacles:\n results.append(res)\n return results\n\n # only hexes on the edge of the area\n def get_hexes_of_circle(self, center, r) -> List[Hex]:\n results = []\n x = -r\n for y in range(0, r):\n vector = Hex(x, y, -x - y)\n res = center + vector\n if self.in_map_boundaries(res) and res not in self.obstacles:\n results.append(res)\n for i in range(5):\n vector = Hex(-vector.y, -vector.z, -vector.x) # rotate 60 degrees\n res = center + vector\n if self.in_map_boundaries(res) and res not in self.obstacles:\n results.append(res)\n return results\n\n def get_hexes_of_axes(self, center, d) -> List[Hex]:\n results = []\n for direction in DIRECTIONS:\n for i in range(1, d + 1):\n res = center + direction * i\n if res in self.obstacles:\n break # stop looking in direction of obstacle\n if self.in_map_boundaries(res):\n results.append(res)\n return results\n","repo_name":"maksim-ganusevich/Powerpuff-girls","sub_path":"work/Map.py","file_name":"Map.py","file_ext":"py","file_size_in_byte":3789,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"70826823290","text":"from django.shortcuts import render\nfrom django.core import serializers\nfrom django.http import (HttpResponseBadRequest,\n JsonResponse,\n HttpResponse)\nfrom django.views.decorators.csrf import csrf_exempt\nfrom random import choice\n\nfrom jobs.models import Job\nfrom persons.models import Person\n\n# Create your views here.\n@csrf_exempt\ndef persons_json_list(request):\n if request.method != 'GET':\n return HttpResponseBadRequest('You can only use GET')\n else:\n persons = serializers.serialize('json', Person.objects.all(), \n fields = (\"short_name\", \n \"full_name\", \n \"email\", \n \"job\", \n \"colleagues\"))\n\n return JsonResponse(persons, safe = False)\n\n@csrf_exempt\ndef add_person(request):\n if request.method != 'POST':\n return HttpResponseBadRequest('You can only use POST')\n else:\n short_name = request.POST['name']\n full_name = request.POST['full_name']\n email = request.POST['email']\n job = choice(Job.objects.all())\n new_person = Person(short_name = short_name, \n full_name = full_name, \n email = email, \n job = job)\n new_person.save()\n return HttpResponse('new person \"%s\" is added' % \n Person.objects.get(short_name = short_name).short_name)\n\n@csrf_exempt\ndef delete_person(request, substr):\n if request.method != \"DELETE\":\n return HttpResponseBadRequest('You can only use DELETE')\n else:\n pers_to_del = Person.objects.filter(short_name__icontains = substr)\n num_persons = len(pers_to_del)\n pers_to_del.delete()\n return HttpResponse('succesfulye deleted %s persons' % num_persons)\n\n","repo_name":"uapasha/python-stuff","sub_path":"tasks/swdev_homeworks/homework7/example/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"29441949869","text":"#completa el codigo de la funcion\ndef suma_divisores(num):\n suma = 0\n for x in range(1, num):\n if num % x == 0:\n suma += x\n if suma == 1:\n return suma, True\n else:\n return suma, False ","repo_name":"pabloschwarzenberg/grader","sub_path":"tema3_ej1/tema3_ej1_d680ae2d7920c930148481f54be6d2f8.py","file_name":"tema3_ej1_d680ae2d7920c930148481f54be6d2f8.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"19304413131","text":"n = int(input())\np, q, r, s, x, y = [int(x) for x in input().split()]\ni, j = [int(x) for x in input().split()]\n\nlinha = []\ncoluna = []\nC = 0\n\nfor _ in range(1, n+1):\n Ai_ = (p*i + q*_) % x\n B_j = (r*_ + s*j) % y\n \n C += Ai_ * B_j\n\nprint(C)","repo_name":"wesleydecezere/maratonista-faixa-preta","sub_path":"faixa-amarela/nivel-1/05-2385-multiplicacao-matrizes/wmain.py","file_name":"wmain.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"13485055365","text":"import requests\n\nfrom pyaxidraw import axidraw \nad = axidraw.AxiDraw()\n\n# get output via: buffer.getvalue()\n\nprint(\"In here to be tested\")\n\nport = \"/dev/cu.usbmodem1301\"\n\npath = \"Casey/Pulsz/Envelopes/test.svg\"\nad.plot_setup(path)\n#ad.options.webhhook = True\nad.options.port = \"/dev/cu.usbmodem1301\"\n#ad.options.webhhook_url = \"https://webhook.site/a733efce-93ef-4878-b31a-40c7fa1a4c94\"\nad.options.speed_pendown = 85\nad.options.speed_penup = 85\nad.options.accel = 90\nad.options.pen_pos_down = 30\nad.options.pen_pos_up = 10\nad.options.pen_rate_lower = 90\nad.options.pen_rate_raise = 90\nad.options.pen_delay_down = 2\nad.options.auto_rotate = False\nad.options.reordering = 2\n\nad.plot_run()\npackage = {\n \"port\": port,\n \"path\": path\n}\nx = requests.post(\"https://373a-24-53-138-18.ngrok.io\", data=package)\nprint(x.text)\n\n","repo_name":"Avinash-Puppala/new-envelopes","sub_path":"preview_axi.py","file_name":"preview_axi.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"35918883332","text":"###\r\n# by SpiderDave\r\n###\r\nimport urllib\r\n\r\nimport re\r\nimport supybot.utils as utils\r\nfrom supybot.commands import *\r\nimport supybot.plugins as plugins\r\nimport supybot.ircutils as ircutils\r\nimport supybot.callbacks as callbacks\r\nimport os\r\ntry:\r\n from supybot.i18n import PluginInternationalization, internationalizeDocstring\r\nexcept:\r\n PluginInternationalization, internationalizeDocstring = lambda x:x, lambda x:x\r\n\r\nimport json\r\n\r\n# This will be used to change the name of the class to the folder name\r\nPluginName=os.path.dirname( __file__ ).split(os.sep)[-1]\r\n\r\n_ = PluginInternationalization(PluginName)\r\n@internationalizeDocstring\r\nclass _Plugin(callbacks.Plugin):\r\n \"\"\"Contains commands for checking the server status of various games.\"\"\"\r\n# I have no idea how long gstatus.de has been down, just removing this for now.\r\n#\r\n# def diablo3(self, irc, msg, args):\r\n# \"\"\"\r\n# Get Diablo 3 server status from www.gstatus.de\r\n# \"\"\"\r\n# threaded = True\r\n# url = 'http://www.gstatus.de/game/diablo3'\r\n# try:\r\n# html = utils.web.getUrl(url)\r\n# except:\r\n# irc.reply('Error: could not get a response from gstatus.de')\r\n# return\r\n# m = re.search(r'Europe.*?Login.*?(.*?).*?Americas.*?Login.*?(.*?).*?Asia.*?Login.*?(.*?)', html, re.I | re.S)\r\n \r\n# if m:\r\n# text='Diablo 3 Server Status: Europe: %s | Americas: %s | Asia: %s' % (m.group(1).strip(), m.group(2).strip(), m.group(3).strip())\r\n# text=text.replace(\"Available\",\"up\")\r\n# text=text.replace(\"Unavailable\",\"down\")\r\n# irc.reply(text)\r\n# else:\r\n# irc.reply('Error: could not get information from gstatus.de')\r\n# diablo3 = wrap(diablo3)\r\n \r\n def leagueoflegends(self, irc, msg, args, region):\r\n \"\"\"\r\n \r\n Get League of Legends server status for the given region.\r\n \"\"\"\r\n threaded = True\r\n \r\n api_key = self.registryValue('riotAPIKey')\r\n validRegions = self.registryValue('lolValidRegions')\r\n defaultRegion = self.registryValue('lolDefaultRegion')\r\n \r\n if api_key == '':\r\n irc.error('Missing Riot API key. Please set plugins.%s.riotAPIKey.' % PluginName)\r\n return\r\n if validRegions == '':\r\n # Should be something like this: RU KR PBE1 BR1 OC1 JP1 NA1 EUN1 EUW1 TR1 LA1 LA2\r\n irc.error('Missing valid regions. Please set plugins.lolValidRegions.')\r\n return\r\n if defaultRegion == '':\r\n defaultRegion = 'NA1'\r\n pass\r\n # irc.error('Missing default region. Please set plugins.lolValidRegions.')\r\n #return\r\n \r\n region = region or defaultRegion\r\n if region.lower() not in validRegions.lower().split():\r\n irc.error('Valid regions are %s' % validRegions)\r\n return\r\n \r\n url = 'https://%s.api.riotgames.com/lol/status/v3/shard-data' % region.lower()\r\n headers = utils.web.defaultHeaders\r\n \r\n opts = {}\r\n opts['api_key']=api_key\r\n fd = utils.web.getUrlFd('%s?%s' % (url,\r\n urllib.parse.urlencode(opts)),\r\n headers)\r\n \r\n jsonData = json.load(fd)\r\n fd.close()\r\n \r\n out = ''\r\n \r\n if not jsonData:\r\n irc.error('Could not get data.')\r\n return\r\n else:\r\n if jsonData:\r\n if not jsonData.get('services'):\r\n # got a response, but services is empty.\r\n irc.error('Could not get data.')\r\n return\r\n for c in jsonData.get('services'):\r\n if c.get('slug') == 'game':\r\n out = '%s: %s' % (jsonData.get('name'), c.get('status'))\r\n if out:\r\n irc.reply(out)\r\n else:\r\n irc.error('Could not get data.')\r\n\r\n\r\n leagueoflegends = wrap(leagueoflegends, [optional('somethingWithoutSpaces')])\r\n\r\n_Plugin.__name__=PluginName\r\nClass = _Plugin\r\n\r\n\r\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\r\n","repo_name":"SpiderDave/spidey-supybot-plugins","sub_path":"Plugins/ServerStatus/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":4269,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"77"} +{"seq_id":"19147804017","text":"# -*- coding: utf-8 -*-\n\"\"\"Methods used in the calculation of transfer entropy. A JIDT wrapper.\n\n\"\"\"\n\nimport jpype\nimport numpy as np\n\n\ndef check_jvm(infodynamicsloc):\n if not jpype.isJVMStarted():\n jpype.startJVM(\n jpype.getDefaultJVMPath(),\n \"-Xms32M\",\n \"-Xmx512M\",\n \"-ea\",\n \"-Djava.class.path=\" + infodynamicsloc,\n convertStrings=True,\n )\n\n\ndef setup_infodynamics_te(infodynamicsloc, calcmethod, **parameters):\n \"\"\"Prepares the teCalc class of the Java Infodyamics Toolkit (JIDT)\n in order to calculate transfer entropy according to the kernel or Kraskov\n estimator method. Also supports discrete transfer entropy calculation.\n\n The embedding dimension of the destination or target variable (k) can\n easily be set by adjusting the histlength parameter.\n\n \"\"\"\n\n check_jvm(infodynamicsloc)\n\n if calcmethod == \"kernel\":\n teCalcClass = jpype.JPackage(\n \"infodynamics.measures.continuous.kernel\"\n ).TransferEntropyCalculatorKernel\n teCalc = teCalcClass()\n\n # Normalisation is performed before this step, set property to false to\n # prevent accidental data standardisation\n teCalc.setProperty(\"NORMALISE\", \"false\")\n\n # Parameter definitions - refer to JIDT Javadocs\n # k - destination embedded history length (Schreiber k=1)\n # kernelWidth - if NORMALISE_PROP_NAME property has been set,\n # then this kernel width corresponds to the number of\n # standard deviations from the mean (otherwise it is an absolute value)\n\n k = parameters.get(\"k\", 1)\n kernel_width = parameters.get(\"kernel_width\", 0.25)\n\n teCalc.initialise(k, kernel_width)\n\n elif calcmethod == \"kraskov\":\n \"\"\"The Kraskov method is the recommended method and also provides\n methods for auto-embedding. The max corr AIS auto-embedding method\n will be enabled as the default.\n\n \"\"\"\n\n teCalcClass = jpype.JPackage(\n \"infodynamics.measures.continuous.kraskov\"\n ).TransferEntropyCalculatorKraskov\n teCalc = teCalcClass()\n # Parameter definitions - refer to JIDT javadocs\n\n # k - embedding length of destination past history to consider\n # k_tau - embedding delay for the destination variable\n # l - embedding length of source past history to consider\n # l_tau - embedding delay for the source variable\n # delay - time lag between last element of source and destination\n # next value\n\n # Normalisation is performed before this step, set property to false to\n # prevent accidental data standardisation\n teCalc.setProperty(\"NORMALISE\", \"false\")\n\n # Allow for manual override\n\n if \"k_history\" in parameters:\n k_history = parameters[\"k_history\"]\n teCalc.setProperty(\"k_HISTORY\", str(k_history))\n\n if \"k_tau\" in parameters:\n k_tau = parameters[\"k_tau\"]\n teCalc.setProperty(\"k_TAU\", str(k_tau))\n\n if \"l_history\" in parameters:\n l_history = parameters[\"l_history\"]\n teCalc.setProperty(\"l_HISTORY\", str(l_history))\n\n if \"l_tau\" in parameters:\n l_tau = parameters[\"l_tau\"]\n teCalc.setProperty(\"l_TAU\", str(l_tau))\n\n if \"auto_embed\" in parameters:\n auto_embed = parameters[\"auto_embed\"]\n if auto_embed is True:\n # Enable the Ragwitz or max AIS method criterion\n # TODO: Enable flag to determine which one\n # Enable source as well as destination embedding due to the\n # nature of our data.\n # Use a maximum history and tau search of 5\n # teCalc.setProperty(\"AUTO_EMBED_METHOD\", \"RAGWITZ\")\n teCalc.setProperty(\"AUTO_EMBED_METHOD\", \"MAX_CORR_AIS\")\n\n ksearchmax = parameters.get(\"k_search_max\", 5)\n teCalc.setProperty(\"AUTO_EMBED_K_SEARCH_MAX\", str(ksearchmax))\n tausearchmax = parameters.get(\"tau_search_max\", 5)\n teCalc.setProperty(\n \"AUTO_EMBED_TAU_SEARCH_MAX\", str(tausearchmax)\n )\n\n # Note: If setting the delay is needed to be changed on each iteration,\n # it may be best to do this outside the loop and initialise teCalc\n # after each change.\n\n if \"delay\" in parameters:\n delay = parameters[\"delay\"]\n teCalc.setProperty(\"DELAY\", str(delay))\n\n if \"use_gpu\" in parameters:\n if parameters[\"use_gpu\"]:\n teCalc.setProperty(\"USE_GPU\", \"true\")\n else:\n teCalc.setProperty(\"USE_GPU\", \"false\")\n\n teCalc.initialise()\n\n elif calcmethod == \"discrete\":\n teCalcClass = jpype.JPackage(\n \"infodynamics.measures.discrete\"\n ).TransferEntropyCalculatorDiscrete\n # Parameter definitions - refer to JIDT javadocs\n # base - number of quantisation levels for each variable\n # binary variables are in base-2\n # destHistoryEmbedLength - embedded history length of the\n # destination to condition on - this is k in Schreiber's notation\n # sourceHistoryEmbeddingLength - embedded history length of the source\n # to include - this is l in Schreiber's notation\n # TODO: Allow these settings to be defined by configuration file\n\n base = parameters.get(\"base\", 2)\n # print \"base default of 2 (binary) is used\"\n\n destHistoryEmbedLength = parameters.get(\"destHistoryEmbedLength\", 1)\n\n base = 2\n destHistoryEmbedLength = 1\n # sourceHistoryEmbeddingLength = None # not used at the moment\n teCalc = teCalcClass(base, destHistoryEmbedLength)\n teCalc.initialise()\n\n else:\n raise NameError(\"Transfer entropy method name not recognized\")\n\n return teCalc\n\n\ndef calc_infodynamics_te(\n infodynamicsloc, calcmethod, affected_data, causal_data, **parameters\n):\n \"\"\"Calculates the transfer entropy for a specific timelag (equal to\n prediction horison) between two sets of time series data.\n\n This implementation makes use of the infodynamics toolkit:\n https://code.google.com/p/information-dynamics-toolkit/\n\n The transfer entropy should have a maximum value when timelag = delay\n used to generate an autoregressive dataset, or will otherwise indicate the\n dead time between data indicating a causal relationship.\n\n \"\"\"\n\n teCalc = setup_infodynamics_te(infodynamicsloc, calcmethod, **parameters)\n miCalc = setup_infodynamics_mi(infodynamicsloc, calcmethod, **parameters)\n\n test_significance = parameters.get(\"test_signifiance\", False)\n significance_permutations = parameters.get(\"significance_permutations\", 30)\n\n # sourceArray = causal_data.tolist()\n # destArray = affected_data.tolist()\n\n if len(causal_data) != len(affected_data):\n print(\"Source length: \" + str(len(causal_data)))\n print(\"Destination length: \" + str(len(affected_data)))\n raise ValueError(\n \"The source and destination arrays are of different lengths\"\n )\n\n # sourceArrayJava = jpype.JArray(jpype.JDouble, 1)(sourceArray)\n # destArrayJava = jpype.JArray(jpype.JDouble, 1)(destArray)\n\n # sourceArrayJava = np.asarray(sourceArray)\n # destArrayJava = np.asarray(destArray)\n\n if calcmethod == \"discrete\":\n source = map(int, causal_data)\n dest = map(int, affected_data)\n teCalc.addObservations(source, dest)\n miCalc.addObservations(source, dest)\n else:\n teCalc.setObservations(causal_data, affected_data)\n miCalc.setObservations(causal_data, affected_data)\n\n transentropy = teCalc.computeAverageLocalOfObservations()\n mutualinfo = miCalc.computeAverageLocalOfObservations()\n\n # Convert nats to bits if necessary\n if calcmethod == \"kraskov\":\n transentropy = transentropy / np.log(2.0)\n mutualinfo = mutualinfo / np.log(2.0)\n elif (calcmethod == \"kernel\") or (calcmethod == \"discrete\"):\n transentropy = transentropy\n mutualinfo = mutualinfo\n else:\n raise NameError(\"Infodynamics method name not recognized\")\n\n if test_significance:\n te_significance = teCalc.computeSignificance(significance_permutations)\n mi_significance = miCalc.computeSignificance(significance_permutations)\n else:\n te_significance = None\n mi_significance = None\n\n # Get all important properties from used teCalc\n if calcmethod != \"discrete\":\n k_history = teCalc.getProperty(\"k_HISTORY\")\n k_tau = teCalc.getProperty(\"k_TAU\")\n l_history = teCalc.getProperty(\"l_HISTORY\")\n l_tau = teCalc.getProperty(\"l_TAU\")\n delay = teCalc.getProperty(\"DELAY\")\n\n properties = [\n k_history,\n k_tau,\n l_history,\n l_tau,\n delay,\n ] # Mutual info included as a property\n else:\n properties = [None]\n\n return (\n transentropy,\n [[te_significance, mi_significance], properties, mutualinfo],\n )\n\n\ndef setup_infodynamics_mi(infodynamicsloc, calcmethod, **parameters):\n \"\"\"Prepares the miCalc class of the Java Infodyamics Toolkit (JIDT)\n in order to calculate mutual information according to the kernel or Kraskov\n estimator method. Also supports discrete mutual information calculation.\n\n The embedding dimension of the destination or target variable (k) can\n easily be set by adjusting the histlength parameter.\n\n \"\"\"\n\n check_jvm(infodynamicsloc)\n\n if calcmethod == \"kernel\":\n miCalcClass = jpype.JPackage(\n \"infodynamics.measures.continuous.kernel\"\n ).MutualInfoCalculatorMultiVariateKernel\n miCalc = miCalcClass()\n\n # Normalisation is performed before this step, set property to false to\n # prevent accidental data standardisation\n miCalc.setProperty(\"NORMALISE\", \"false\")\n\n # Parameter definitions - refer to JIDT Javadocs\n # k - destination embedded history length (Schreiber k=1)\n # kernelWidth - if NORMALISE_PROP_NAME property has been set,\n # then this kernel width corresponds to the number of\n # standard deviations from the mean (otherwise it is an absolute value)\n\n k = parameters.get(\"k\", 1)\n kernel_width = parameters.get(\"kernel_width\", 0.25)\n\n miCalc.setProperty(\"KERNEL_WIDTH\", str(kernel_width))\n\n miCalc.initialise()\n\n elif calcmethod == \"kraskov\":\n \"\"\"The Kraskov method is the recommended method and also provides\n methods for auto-embedding. The max corr AIS auto-embedding method\n will be enabled as the default.\n\n \"\"\"\n\n miCalcClass = jpype.JPackage(\n \"infodynamics.measures.continuous.kraskov\"\n ).MutualInfoCalculatorMultiVariateKraskov1\n miCalc = miCalcClass()\n # Parameter definitions - refer to JIDT javadocs\n\n # k - embedding length of destination past history to consider\n # delay - time lag between last element of source and destination\n # next value\n\n # Normalisation is performed before this step, set property to false to\n # prevent accidental data standardisation\n miCalc.setProperty(\"NORMALISE\", \"false\")\n\n # Note: If setting the delay is needed to be changed on each iteration,\n # it may be best to do this outside the loop and initialise teCalc\n # after each change.\n\n if \"delay\" in parameters:\n delay = parameters[\"delay\"]\n miCalc.setProperty(\"TIME_DIFF\", str(delay))\n\n miCalc.initialise()\n\n elif calcmethod == \"discrete\":\n miCalcClass = jpype.JPackage(\n \"infodynamics.measures.discrete\"\n ).MutualInformationCalculatorDiscrete\n # Parameter definitions - refer to JIDT javadocs\n # base - number of quantisation levels for each variable\n # binary variables are in base 2\n # TODO: Allow these settings to be defined by configuration file\n\n base = parameters.get(\"base\", 2)\n # print \"base default of 2 (binary) is used\"\n\n miCalc = miCalcClass(base, base, 0)\n miCalc.initialise()\n\n else:\n raise NameError(\"Mutual information method name not recognized\")\n\n return miCalc\n\n\ndef setup_infodynamics_entropy(\n infodynamicsloc, estimator=\"kernel\", kernel_bandwidth=0.1, mult=False\n):\n \"\"\"Prepares the entropyCalc class of the Java Infodyamics Toolkit (JIDK)\n in order to calculate differential entropy (continuous signals) according\n to the estimation method specified.\n\n Parameters\n ----------\n infodynamicsloc : path\n Location of infodynamics.jar\n estimator : string, default='kernel'\n Either 'kernel' or 'gaussian'. Specifies the estimator to use in\n determining the required probability density functions.\n kernel_bandwidth : float\n The width of the kernels for the kernel method. If normalisation\n is performed, these are in terms of standard deviation, otherwise\n absolute.\n mult : bool, default=False\n Indicates whether the entropy is to be calculated on a univariate\n or multivariate signal.\n\n Returns\n -------\n entropyCalc : EntropyCalculator JIDT object\n\n \"\"\"\n\n check_jvm(infodynamicsloc)\n\n if estimator == \"kernel\":\n if mult:\n entropyCalcClass = jpype.JPackage(\n \"infodynamics.measures.continuous.kernel\"\n ).EntropyCalculatorMultiVariateKernel\n else:\n entropyCalcClass = jpype.JPackage(\n \"infodynamics.measures.continuous.kernel\"\n ).EntropyCalculatorKernel\n\n entropyCalc = entropyCalcClass()\n # Normalisation is performed before this step, set property to false to\n # prevent accidental data standardisation\n entropyCalc.setProperty(\"NORMALISE\", \"false\")\n entropyCalc.initialise(kernel_bandwidth)\n\n elif estimator == \"gaussian\":\n if mult:\n entropyCalcClass = jpype.JPackage(\n \"infodynamics.measures.continuous.gaussian\"\n ).EntropyCalculatorMultiVariateGaussian\n else:\n entropyCalcClass = jpype.JPackage(\n \"infodynamics.measures.continuous.gaussian\"\n ).EntropyCalculatorGaussian\n\n entropyCalc = entropyCalcClass()\n entropyCalc.initialise()\n\n elif estimator == \"kozachenko\":\n entropyCalcClass = jpype.JPackage(\n \"infodynamics.measures.continuous.kozachenko\"\n ).EntropyCalculatorMultiVariateKozachenko\n\n entropyCalc = entropyCalcClass()\n entropyCalc.initialise()\n\n else:\n raise NameError(\"Estimator not recognized\")\n\n return entropyCalc, estimator\n\n\ndef calc_infodynamics_entropy(entropyCalc, data, estimator):\n \"\"\"Estimates the entropy of a single signal.\n\n Parameters\n ----------\n entropyCalc : EntropyCalculator JIDT object\n The estimation method is determined during initialisation of this\n object beforehand.\n data : one-dimensional numpy.ndarray\n The univariate signal.\n\n Returns\n -------\n entropy : float\n The entropy of the signal.\n\n Notes\n -----\n The entropy calculated with the Gaussian estimator is in nats, while\n that calculated by the kernel estimator is in bits.\n Nats can be converted to bits by division with ln(2).\n \"\"\"\n\n dataArray = data.tolist()\n dataArrayJava = jpype.JArray(jpype.JDouble, 1)(dataArray)\n entropyCalc.setObservations(dataArrayJava)\n entropy = entropyCalc.computeAverageLocalOfObservations()\n if estimator == \"gaussian\":\n # Convert nats to bits\n entropy = entropy / np.log(2.0)\n elif estimator == \"kernel\":\n # Do nothing\n entropy = entropy\n elif estimator == \"kozachenko\":\n entropy = entropy / np.log(2.0)\n else:\n raise NameError(\"Estimator not recognized\")\n\n return entropy\n","repo_name":"sjstreicher/FaultMap","sub_path":"faultmap/transentropy.py","file_name":"transentropy.py","file_ext":"py","file_size_in_byte":16160,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"77"} +{"seq_id":"34361819936","text":"# -*- coding: utf-8 -*-\nimport lmfit\nimport pickle\nfrom astropy.io import fits as pyfits\nimport numpy as np\nfrom pyx import *\n\n####################################################\nfname = 'TDRIZZLE_0010_010_HATS755004_SDSSz__000/'\nband = \"z'\"\nplot_title = 'HATS-49'\ndate = '2015-12-23'\nmin_contrast = -4.\n####################################################\n\nimage,h = pyfits.getdata(fname+'/original_image.fits',header=True)\nimage = image - np.median(image)\nimage = (image - np.min(image))+0.01\nimage = np.log(image/np.max(image))\n\n# Parameter fit data:\nthefile = open(fname+'/out_params.pkl','rb')\nparams = pickle.load(thefile,encoding='latin1')\nxcen,ycen,sigma_x,sigma_y = params['x0'].value,params['y0'].value,\\\n params['sigma_x'].value,params['sigma_y'].value\n\nsigma = (sigma_x+sigma_y)/2.\nxpixels = np.arange(image.shape[0])+0.5\nypixels = np.arange(image.shape[1])+0.5\nscale_x = 15.20*1e-3\nscale_y = 15.20*1e-3\nxarcsec = (xpixels - (image.shape[0]/2.))*scale_x\nyarcsec = (ypixels - (image.shape[1]/2.))*scale_y\n# Convert centroid to arcsec:\nxcen = (xcen + 0.5 - (image.shape[0]/2.))*scale_x\nycen = (ycen + 0.5 - (image.shape[1]/2.))*scale_y\nprint('centroid (ra,dec):',xcen,ycen)\nsigma = sigma*(scale_x)\nprint('sigma = ',sigma)\nprint('fwhm = ',sigma*2.355)\nx,y = np.meshgrid(xarcsec-xcen,yarcsec-ycen)\ndata = list(zip(x.flat,y.flat,image.flat))\n# Plot:\nunit.set(xscale=2.5)\ntext.set(mode=\"latex\")\ntext.preamble(r\"\\usepackage{color}\")\ntext.preamble(r\"\\usepackage{wasysym}\")\nc = canvas.canvas()\ng = c.insert(graph.graphxy(height=20, width=20, key=graph.key.key(pos='br'),\n x=graph.axis.linear(min=-3.6, max=4., title='$\\Delta$ R.A. (arcsec)'),\n y=graph.axis.linear(min=-4.0, max=3.2, title='$\\Delta$ DEC (arcsec)')))\n\ng.plot(graph.data.points(data, x=1, y=2, color=3, title = None),\n [graph.style.density(gradient=color.gradient.YellowBlack,\n coloraxis=graph.axis.linear(min=min_contrast, max=0.0,\n title=\"Relative flux (log-scale)\"))])\n\ng.plot(graph.data.values(x=[-60,60],y=[0,0], title = None),\\\n styles = [graph.style.line([color.cmyk.Grey,\\\n style.linestyle.dashed,\\\n style.linewidth.thin])])\n\ng.plot(graph.data.values(x=[0,0],y=[-60,60], title = None),\\\n styles = [graph.style.line([color.cmyk.Grey,\\\n style.linestyle.dashed,\\\n style.linewidth.thin])])\n\n# Plot circles:\nxc,yc = g.pos(0.,0.)#g.pos(xcen,ycen)\nxcr,ycr = g.pos(3.,ycen)\nrc = np.sqrt((xc-xcr)**2 + (yc-ycr)**2)\nc.stroke(path.circle(xc,yc,np.abs(rc)),[style.linewidth.thin, style.linestyle.solid, color.cmyk.Black])\n\n# Plot circles:\nxc,yc = g.pos(0.,0.)#g.pos(xcen,ycen)\nxcr,ycr = g.pos(1.,ycen)\nrc = np.sqrt((xc-xcr)**2 + (yc-ycr)**2)\nc.stroke(path.circle(xc,yc,np.abs(rc)),[style.linewidth.thin, style.linestyle.dashed, color.cmyk.Black])\n\n# Plot circles:\n############ IF A SOURCE, UNCOMMENT THIS #####################\n#xc,yc = g.pos(-1.52613,-3.48374)\n#rc = 1#np.sqrt((xc-xcr)**2 + (yc-ycr)**2)\n#c.stroke(path.circle(xc,yc,np.abs(rc)),[style.linewidth.thin, style.linestyle.dashed, color.cmyk.Blue])\n##############################################################\n#x0,y0 = g.pos(0.,0.)\n#xr,yr = g.pos(3.98*3.,0.)\n#r = np.sqrt((x0-xr)**2+(y0-yr)**2)\n#c.stroke(path.circle(x0,y0,np.abs(r)),[style.linewidth.Thick, style.linestyle.solid, color.cmyk.Black])\n\n# Plot text:\nxtext,ytext = g.pos(-50,50)\n#g.text(xtext,ytext,r\"(b)\")\ng.text(g.width/2, g.height + 0.3, plot_title+' '+date+\" (AstraLux Sur+\"+band+\")\", \n [text.halign.center, text.valign.bottom])\n#kg = graph.graphx(-5,5,length=10,direction=\"horizontal\")\n#g.plot(graph.data.points(zero_data, x=1, y=2, color=3),\n# styles = [graph.style.density(gradient=color.gradient.Gray,\n# keygraph=kg)])\n\n#g.insert(kg)\nc.writeEPSfile(plot_title+'.eps')#,write_mesh_as_bitmap = True,write_mesh_as_bitmap_resolution=5)\nc.writePDFfile(plot_title+'.pdf')#,write_mesh_as_bitmap = True,write_mesh_as_bitmap_resolution=5)\n","repo_name":"nespinoza/luckyimg-reduction","sub_path":"plot_image.py","file_name":"plot_image.py","file_ext":"py","file_size_in_byte":4200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"6329561278","text":"from django.shortcuts import render,HttpResponseRedirect,redirect\nfrom .forms import SignUpForm\nfrom django.contrib import messages\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.contrib.auth import authenticate,login,logout\nfrom django.urls import reverse \nfrom app_hotel.models import Room,Staff,Customer,Reservation\nfrom .forms import RoomForm,StaffForm,CustomerForm,ReservationForm\n\n# Create your views here.\n\n# VIEW FOR SIGNUP\ndef sign_up(request):\n\n if request.method == \"POST\":\n fm=SignUpForm(request.POST)\n if fm.is_valid():\n messages.success(request,'Account Created Successfully')\n fm.save()\n\n login_url = reverse('login') # redirect to login page after successfully signing up\n return HttpResponseRedirect(login_url)\n else:\n fm=SignUpForm()\n\n return render(request,'app_hotel/signup.html',{'form':fm})\n\n\n# VIEW FOR LOGIN\ndef user_login(request):\n # if not request.user.is_authenticated:\n if request.method == \"POST\":\n fm=AuthenticationForm(request=request,data=request.POST)\n if fm.is_valid():\n # used to store and retrieve cleaned (validated) data that a user has submitted\n uname=fm.cleaned_data['username']\n upass=fm.cleaned_data['password']\n\n # verify the user's credentials ... returns object if the credentials are correct or None if not correct\n user = authenticate(username=uname,password=upass)\n if user is not None:\n \n login(request,user)\n # print(\"User Successfully Logged In\")\n messages.success(request, 'Login successful')\n \n # Use reverse to generate the URL for the 'base' view\n return HttpResponseRedirect(reverse('base'))\n \n else:\n messages.error(request, 'Username or password is incorrect. Please try again.')\n\n else:\n fm=AuthenticationForm()\n return render(request,'app_hotel/login.html',{'form':fm})\n\n\n# VIEW FOR LOGOUT\ndef user_logout(request):\n logout(request)\n login_url=reverse('login')\n return HttpResponseRedirect(login_url)\n\n\n# VIEW FOR DASHBOARD\ndef dashboard(request):\n return render(request,'app_hotel/dashboard.html')\n\n\n# VIEW FOR BASE\ndef base(request):\n return render(request,'app_hotel/base.html')\n\n\n# VIEW FOR ROOM\ndef addroom(request):\n room = Room.objects.all()\n return render(request,'app_hotel/addroom.html',context={'room':room})\n\ndef room(request):\n if request.method == 'POST':\n rm = RoomForm(request.POST)\n\n if rm.is_valid():\n rnumber = rm.cleaned_data['room_number']\n rtype = rm.cleaned_data['room_type']\n rprice = rm.cleaned_data['room_price']\n rdescription = rm.cleaned_data['description']\n ravailable = rm.cleaned_data['is_available']\n\n reg = Room(room_number=rnumber,room_type=rtype,room_price=rprice,description=rdescription,is_available=ravailable)\n reg.save()\n\n return redirect('addroom')\n else:\n rm = RoomForm()\n room = Room.objects.all()\n return render(request,'app_hotel/room.html',{'rm':rm,'room':room})\n\n# TO UPDATE ROOM\ndef updateroom(request,id):\n if request.method==\"POST\":\n rm=Room.objects.get(pk=id)\n fm = RoomForm(request.POST,instance=rm)\n\n if fm.is_valid():\n fm.save()\n else:\n rm=Room.objects.get(pk=id)\n fm = RoomForm(instance=rm)\n return render(request,'app_hotel/updateroom.html',{'form':fm})\n\n# TO DELETE ROOM\ndef deleteroom(request,id):\n if request.method == \"POST\":\n room = Room.objects.get(pk=id)\n room.delete()\n return HttpResponseRedirect(reverse('addroom'))\n\n\n# VIEW FOR STAFF\ndef addstaff(request):\n staff = Staff.objects.all()\n return render(request,'app_hotel/addstaff.html',context={'staff':staff})\n\ndef staff(request):\n if request.method == 'POST':\n st = StaffForm(request.POST)\n\n if st.is_valid():\n fname = st.cleaned_data['first_name']\n lname = st.cleaned_data['last_name']\n email = st.cleaned_data['email']\n phone = st.cleaned_data['phone_number']\n position = st.cleaned_data['position']\n\n reg = Staff(first_name=fname,last_name=lname,email=email,phone_number=phone,position=position)\n reg.save()\n\n return redirect('addstaff')\n else:\n st = StaffForm()\n staff = Staff.objects.all()\n return render(request,'app_hotel/staff.html',{'st':st,'staff':staff})\n\n# TO UPDATE STAFF\ndef updatestaff(request,id):\n if request.method==\"POST\":\n st=Staff.objects.get(pk=id)\n fm = StaffForm(request.POST,instance=st)\n\n if fm.is_valid():\n fm.save()\n else:\n st=Staff.objects.get(pk=id)\n fm = StaffForm(instance=st)\n return render(request,'app_hotel/updatestaff.html',{'form':fm})\n\n# TO DELETE STAFF\ndef deletestaff(request,id):\n if request.method == \"POST\":\n \n staff = Staff.objects.get(pk=id)\n staff.delete()\n\n return HttpResponseRedirect(reverse('addstaff'))\n \n\n# VIEW FOR CUSTOMER\n\ndef addcustomer(request):\n customers = Customer.objects.all()\n return render(request,'app_hotel/addcustomer.html',{'customer':customers})\n\ndef customer(request):\n if request.method == 'POST':\n ct = CustomerForm(request.POST)\n\n if ct.is_valid():\n fname = ct.cleaned_data['first_name']\n lname = ct.cleaned_data['last_name']\n email = ct.cleaned_data['email']\n phone = ct.cleaned_data['phone_number']\n\n reg = Customer(first_name=fname,last_name=lname,email=email,phone_number=phone)\n reg.save()\n \n return redirect('addcustomer')\n else:\n ct = CustomerForm()\n customer = Customer.objects.all()\n return render(request,'app_hotel/customer.html',{'ct':ct,'customer':customer})\n\n# TO UPDATE CUSTOMER\ndef updatecustomer(request,id):\n if request.method==\"POST\":\n ct=Customer.objects.get(pk=id)\n fm = CustomerForm(request.POST,instance=ct)\n if fm.is_valid():\n fm.save()\n else:\n ct=Customer.objects.get(pk=id)\n fm = CustomerForm(instance=ct)\n return render(request,'app_hotel/updatecustomer.html',{'form':fm})\n\n# TO DELETE CUSTOMER\ndef deletecustomer(request,id):\n if request.method == \"POST\":\n customer = Customer.objects.get(pk=id)\n customer.delete()\n return HttpResponseRedirect(reverse('addcustomer'))\n \n\n# VIEW FOR RESERVATION\ndef addreservation(request):\n reservation = Reservation.objects.all()\n return render(request,'app_hotel/addreservation.html',{'reservation':reservation})\n\ndef reservation(request):\n if request.method == 'POST':\n rs = ReservationForm(request.POST)\n\n if rs.is_valid():\n cname = rs.cleaned_data['customer_name']\n checkin = rs.cleaned_data['check_in_date']\n checkout = rs.cleaned_data['check_out_date']\n room = rs.cleaned_data['room']\n ispaid = rs.cleaned_data['is_paid']\n total = rs.cleaned_data['total_amount']\n createdby = rs.cleaned_data['created_by']\n\n reg = Reservation(customer_name=cname,check_in_date=checkin,check_out_date=checkout,room=room,is_paid=ispaid,total_amount=total,created_by=createdby)\n reg.save()\n \n return redirect('addreservation')\n else:\n rs = ReservationForm()\n reservation = Reservation.objects.all()\n return render(request,'app_hotel/reservation.html',{'rs':rs,'reservation':reservation})\n\n# TO UPDATE RESERVATION\ndef updatereservation(request,id):\n if request.method==\"POST\":\n rs=Reservation.objects.get(pk=id)\n fm = ReservationForm(request.POST,instance=rs)\n if fm.is_valid():\n fm.save()\n else:\n rs=Reservation.objects.get(pk=id)\n fm = ReservationForm(instance=rs)\n return render(request,'app_hotel/updatereservation.html',{'form':fm})\n\n# TO DELETE RESERVATION\ndef deletereservation(request,id):\n if request.method == \"POST\":\n reservation = Reservation.objects.get(pk=id)\n reservation.delete()\n return HttpResponseRedirect(reverse('addreservation'))\n \n\n\n","repo_name":"Dipti158/Django_Hotel_Management_System","sub_path":"app_hotel/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"23095935895","text":"import numpy as np\r\nimport pandas as pd\r\nfrom gensim.models.doc2vec import Doc2Vec\r\nfrom sklearn.cluster import KMeans\r\nimport re\r\nimport jieba\r\n\r\n\r\n\r\n\r\n\r\ndef cut_sentence(word):\r\n stop_list = [line[:-1] for line in open(\"stop.txt\")]\r\n result = []\r\n for each in word:\r\n each = re.sub(r,'',each)\r\n each_cut = jieba.cut(each)\r\n each_split = ' '.join(each_cut).split()\r\n each_result = [words for words in each_split if words not in stop_list]\r\n result.append(' '.join(each_result).split())\r\n return result\r\n\r\n\r\ndf = pd.read_excel('pix_test.xlsx',encoding = 'utf-8')\r\nword = df['內容'].tolist()\r\nr=\"[\\s+\\.\\!\\/_,$%^*~(+\\\"\\')]~,-|[——()?『\\』;【】“”!,。?、~@#¥%……&*()●:[\\]「」=:.!',-/' ]\"\r\n\r\n\r\ncut_over = cut_sentence(word)\r\n\r\nmodel = Doc2Vec.load('test.model')\r\n\r\n\r\n\r\ndef sent2vec(model, words): \r\n vect_list = []\r\n not_in_model_word=0\r\n sucessful = 0\r\n for w in range(len(words)):\r\n try:\r\n sucessful+=1\r\n vect_list.append(model.wv[words[w]])\r\n except:\r\n x = np.zeros(300)\r\n vect_list.append(x)\r\n not_in_model_word+=1\r\n continue\r\n vect_list = np.array(vect_list)\r\n vect = vect_list.sum(axis=0)\r\n print('The word not in Doc2Vec: ',not_in_model_word)\r\n print('successful: ',sucessful)\r\n return vect / np.sqrt((vect ** 2).sum())\r\n\r\n\r\narticle = []\r\n\r\nfor h in range(len(cut_over)):\r\n\r\n word_vec = sent2vec(model,cut_over[h])\r\n \r\n article.append(word_vec)\r\n\r\n\r\nprint(article)\r\nclf = KMeans(n_clusters=8)\r\nclf.fit(article)\r\no = clf.labels_\r\nfinal = np.array(o)\r\ndf['分類結果'] = final\r\ndf.to_excel('final_result.xlsx')\r\n\r\n\r\n","repo_name":"arleigh418/Base-On-K_means-and-Doc2Vec-Pixnet-Article-Classification","sub_path":"KMEANS.py","file_name":"KMEANS.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"39269813711","text":"import re\n\nfrom typing import Optional\n\nfrom bs4 import BeautifulSoup\n\nfrom src import utils\nfrom src.dto.Description import Description\nfrom src.dto.Event import Event\nfrom src.dto.PriceRange import PriceRange\nfrom src.dto.Price import Price\nfrom src.finder.CategoryFinder import CategoryFinder\nfrom src.utils.Utils import Utils\n\n\nclass DescriptionFinder:\n\n @staticmethod\n def add_description(events) -> [Event]:\n\n for event in events:\n common_container = event.small_container\n if common_container is None:\n common_container = event.container\n\n longest_text_elem = DescriptionFinder.find_description_element(common_container)\n if longest_text_elem is None or (len(longest_text_elem.text) < 300 and (event.category == CategoryFinder.SINGLE_EVENT or event.category == CategoryFinder.SINGLE_EVENT_WITH_TIMELINE)):\n longest_text_elem = DescriptionFinder.find_description_element(common_container.parent)\n\n if longest_text_elem is None:\n continue\n\n event.description = Description(Utils.clean(longest_text_elem.text), longest_text_elem)\n\n return events\n\n @staticmethod\n def find_description_element(common_container):\n if common_container is None:\n return None\n longest_text = 0\n longest_text_elem = None\n for elem in common_container.find_all(text=True): # text=True\n elem = Utils.getTag(elem)\n text = elem.text\n text_len = len(text)\n if longest_text_elem is None or text_len > longest_text:\n longest_text_elem = elem\n longest_text = text_len\n if longest_text < 80:\n longest_text_elem = common_container\n return longest_text_elem\n","repo_name":"Jadro007/EventParser","sub_path":"src/finder/DescriptionFinder.py","file_name":"DescriptionFinder.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"17302353731","text":"import numpy as np\n\n\ndef weights_inits(init_type, **kwargs):\n inits = {\n 'fixed': _fixed_init,\n 'uniform': _rand_init\n }\n return inits[init_type](**kwargs)\n\n\ndef _fixed_init(n_weights, n_units, init_value, **kwargs):\n if n_weights == 1:\n return np.full(shape=n_units, fill_value=init_value)\n return np.full(shape=(n_weights, n_units), fill_value=init_value)\n\n\ndef _rand_init(n_weights, n_units, limits=(-0.1, 0.1), **kwargs):\n lower_lim, upper_lim = limits[0], limits[1]\n if lower_lim >= upper_lim:\n raise ValueError(f\"lower_lim must be <= than upper_lim\")\n res = np.random.uniform(low=lower_lim, high=upper_lim, size=(n_weights, n_units))\n if n_weights == 1:\n return res[0]\n return res\n","repo_name":"AlexPasqua/NNs-from-scratch","sub_path":"src/weights_initializations.py","file_name":"weights_initializations.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"77"} +{"seq_id":"34411582246","text":"# -*- coding: utf-8 -*-\n# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C)\n# 2020 MinIO, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"XML utility module.\"\"\"\n\nfrom __future__ import absolute_import\n\nimport io\nfrom xml.etree import ElementTree as ET\n\n_S3_NAMESPACE = \"http://s3.amazonaws.com/doc/2006-03-01/\"\n\n\ndef Element(tag, namespace=_S3_NAMESPACE): # pylint: disable=invalid-name\n \"\"\"Create ElementTree.Element with tag and namespace.\"\"\"\n return ET.Element(tag, {'xmlns': namespace} if namespace else {})\n\n\ndef SubElement(parent, tag, text=None): # pylint: disable=invalid-name\n \"\"\"Create ElementTree.SubElement on parent with tag and text.\"\"\"\n element = ET.SubElement(parent, tag)\n if text is not None:\n element.text = text\n return element\n\n\ndef _get_namespace(element):\n \"\"\"Exact namespace if found.\"\"\"\n start = element.tag.find(\"{\")\n if start < 0:\n return \"\"\n start += 1\n end = element.tag.find(\"}\")\n if end < 0:\n return \"\"\n return element.tag[start:end]\n\n\ndef findall(element, name):\n \"\"\"Namespace aware ElementTree.Element.findall().\"\"\"\n namespace = _get_namespace(element)\n return element.findall(\n \"ns:\" + name if namespace else name,\n {\"ns\": namespace} if namespace else {},\n )\n\n\ndef find(element, name):\n \"\"\"Namespace aware ElementTree.Element.find().\"\"\"\n namespace = _get_namespace(element)\n return element.find(\n \"ns:\" + name if namespace else name,\n {\"ns\": namespace} if namespace else {},\n )\n\n\ndef findtext(element, name, strict=False):\n \"\"\"\n Namespace aware ElementTree.Element.findtext() with strict flag\n raises ValueError if element name not exist.\n \"\"\"\n element = find(element, name)\n if element is None:\n if strict:\n raise ValueError(f\"XML element <{name}> not found\")\n return None\n return element.text or \"\"\n\n\ndef unmarshal(cls, xmlstring):\n \"\"\"Unmarshal given XML string to an object of passed class.\"\"\"\n return cls.fromxml(ET.fromstring(xmlstring))\n\n\ndef getbytes(element):\n \"\"\"Convert ElementTree.Element to bytes.\"\"\"\n data = io.BytesIO()\n ET.ElementTree(element).write(\n data, encoding=None, xml_declaration=False,\n )\n return data.getvalue()\n\n\ndef marshal(obj):\n \"\"\"Get XML data as bytes of ElementTree.Element.\"\"\"\n return getbytes(obj.toxml(None))\n","repo_name":"minio/minio-py","sub_path":"minio/xml.py","file_name":"xml.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","stars":706,"dataset":"github-code","pt":"77"} +{"seq_id":"39831289272","text":"import matplotlib.pyplot as plt\nimport math\nimport japanize_matplotlib\nimport numpy as np\nimport subprocess as sp\n\ndef plogp(p):\n if p <= 0:\n return 0\n else:\n return p*math.log(p)/math.log(2)\n\ndef H(p):\n return -plogp(p) - plogp(1-p)\n\n\nN=100\nx = np.array(range(N+1))/N\ny = [H(p) for p in x]\n\nplt.plot(x,y)\nplt.xlabel(\"表が出る確率p\")\nplt.ylabel(\"エントロピー\")\nimgname = 'picture/entropy.png'\nplt.savefig(imgname)\n\nsp.run(f'mpv {imgname}', shell=True)\n\n\n","repo_name":"trgkpc/blind_source_separation","sub_path":"graph/entropy.py","file_name":"entropy.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"71358661688","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Dec 7 10:28:05 2021\r\n\r\n@author: Alex Abades Grimes\r\n\"\"\"\r\n\r\n\r\ndef getWrongAnswers(N: int, C: str) -> str:\r\n s=\"\"\r\n l = ['A' if x=='B' else 'B' for x in C]\r\n s.join(l)\r\n print(s)\r\n return s\r\n\r\nN = 4\r\nC = 'ABBA'\r\n\r\n# =============================================================================\r\n# a = getWrongAnswers(N, C)\r\n# print(a)\r\n# =============================================================================\r\n\r\nb= ['A' if x=='B' else 'B' for x in C]\r\n\r\ns = ''.join(b)\r\nprint(s)\r\n\r\n#%% \r\n\r\n\r\n# =============================================================================\r\n# You're playing Battleship on a grid of cells with RR rows and CC columns.\r\n# There are 00 or more battleships on the grid, each occupying a single \r\n# distinct cell. The cell in the iith row from the top and jjth column from \r\n# the left either contains a battleship (G_{i,j} = 1 G i,j=1) or doesn't \r\n# (G_{i,j} = 0 ​\r\n# You're going to fire a single shot at a random cell in the grid. You'll \r\n# choose this cell uniformly at random from the R*CR∗C possible cells. You're \r\n# interested in the probability that the cell hit by your shot contains a \r\n# battleship.\r\n# Your task is to implement the function getHitProbability(R, C, G) which \r\n# returns this probability. # Note: Your return value must have an absolute or \r\n# relative error of at most 10^{-6}10−6 to be considered correct.\r\n# =============================================================================\r\n\r\nG = [[1, 0],[2, 1]]\r\n\r\nfrom typing import List\r\n\r\n\r\ndef getHitProbability(R: int, C: int, G: List[List[int]]) -> float:\r\n if 1 >= R >= 100 or 1 >= C >= 100 or not all(i <= 1 and i >= 0 for i in sum(G,[])):\r\n raise ValueError('apsd')\r\n return sum(sum(G,[]))/(R*C)\r\n","repo_name":"AlexAbades/Python-Algorithms","sub_path":"Interviews/Probelms.py","file_name":"Probelms.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"16645555195","text":"#!/bin/python3\n\nimport os\nimport sys\n\n#\n# Complete the miniMaxSum function below.\n#\ndef miniMaxSum(arr):\n \n sum=0\n n=len(arr)\n for i in range(n):\n sum+=arr[i]\n minsum=sum\n maxsum=0\n for i in range(n):\n if(sum-arr[i]>maxsum):\n maxsum=sum-arr[i]\n if(sum-arr[i] %s **\" %(i+1, seance.heure_depart, seance.heure_fin))\n # récuperer les 'nom_prenom' des étudiants présents\n nicknames = self.gerer_seance(seance.heure_depart)\n if nicknames is not None :\n print(\"[INFO] groupe numero \",seance.groupe_ID)\n print(\"[INFO] traitement des données en cours ...\")\n # récuperer les dictionnaires contenants les étudiants présents et absents\n dict_presents,dict_absents = etudiants_CNE(nicknames,seance.groupe_ID)\n\n # initialiser la liste des objets de la classe Etudiant\n etudiants_presents = []\n etudiants_absents = []\n\n # boucler sur les deux dictionnaires\n for CNE,fullName in dict_presents.items() :\n # créer un objet de la classe Etudiant\n etudiant = Etudiant(CNE,fullName)\n etudiants_presents.append(etudiant)\n for CNE,fullName in dict_absents.items() :\n # créer un objet de la classe Etudiant\n etudiant = Etudiant(CNE,fullName)\n etudiants_absents.append(etudiant)\n\n # initialiser et remplir la fiche d'absence\n fiche = Fiche_absence(seance)\n fiche.ajouter_etudiants(etudiants_presents,True)\n fiche.ajouter_etudiants(etudiants_absents,False)\n\n # Initialiser le 'Writer'\n writer = Writer(fiche)\n # enregister la fiche d'absence dans la base de données\n writer.enregistrer_fiche()\n print(\"[INFO] la fiche d'absence est enregistrée.\")\n else :\n print(\"[WARNING] la séance est expirée.\")\n print('---------------------------------------------------')\n\n def gerer_seance(self,heure_depart):\n '''\n cette méthode lance la reconnaissance des étudiants pendant une séance\n\n :param heure_depart: heure de départ de la séance décalée par 5 min (avant )\n :return: liste des étudiants présents dans la séance\n '''\n\n # transformer les string en objets de type time\n finish_time = datetime.datetime.strptime(heure_depart, \"%H:%M\")\n start_time = finish_time - datetime.timedelta(hours=0,minutes=1)\n start_time = start_time.time()\n finish_time = finish_time.time()\n # récuperer le temps réel\n current_time = datetime.datetime.now().time()\n\n while current_time < start_time :\n # synchroniser le temps réel\n current_time = datetime.datetime.now().time()\n\n # commencer la reconnaissance des étudiants\n\n # initialiser la liste des étudiants détectés par le système\n etudiants_presents = None\n # éviter de démarer la caméra si la séance est expirée\n if current_time >= finish_time :\n return etudiants_presents\n\n # charger les encodages de tous les étudiants\n print(\"[INFO] loading encodings...\")\n data = pickle.loads(open(\"gestion_absence/reconnaissance/encodings.pickle\", \"rb\").read())\n\n # initialiser le video stream et pointer sur la sortie du fichier video, puis\n # permettre la caméra de se réchauffer\n print(\"[INFO] starting video stream...\")\n vs = VideoStream(src=0).start()\n writer = None\n time.sleep(2.0)\n # initialiser l'ensemble des étudiants présents\n etudiants_presents = set()\n #initialiser le compteur des blink\n counters = dict()\n # boucler sur des frames du video stream\n while current_time < finish_time :\n\n # récuperer un frame du video stream\n frame = vs.read()\n\n # convertir le frame du BGR au RGB puis changer sa taille pour qu'elle devient\n # de 750px en largeur (pour accélerer le processing)\n rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n rgb = imutils.resize(frame, width=750)\n r = frame.shape[1] / float(rgb.shape[1])\n\n # detecter les coordonnées (x, y)des boxes\n # correspondant à chaque visage dans le frame, puis\n # reconnaître le visage de chaqu'un d'eux\n boxes = face_recognition.face_locations(rgb,\n model=\"hog\")\n encodings = face_recognition.face_encodings(rgb, boxes)\n names = []\n #TODO: extraire les landmarks\n landmarks = face_recognition.face_landmarks(rgb,boxes)\n # boucler sur les encodages #TODO boucler aussi sur les landmarks\n for encoding,landmark in zip(encodings,landmarks):\n # comparer les encodages du visage détecté avec celles\n # des visage déjà connus\n matches = face_recognition.compare_faces(data[\"encodings\"],\n encoding, tolerance=0.5)\n name = \"Unknown\"\n\n # vérifier si on a trouvé une similitude\n if True in matches:\n #trouver les indices de toutes les similitudes trouvées puis\n # initialiser un dictionnaire pour compter le nombre total\n # des cas de similitude pour chaque visage\n matchedIdxs = [i for (i, b) in enumerate(matches) if b]\n counts = {}\n\n # boucler sur les indices de similitude et maintenir un\n # compteur pour chaque visage reconnu\n for i in matchedIdxs:\n name = data[\"names\"][i]\n counts[name] = counts.get(name, 0) + 1\n\n # determiner le visage reconnu avec le grand nombre de\n # votes\n name = max(counts, key=counts.get)\n\n #TODO : calculer le EAR a partir du variable landmark et faire la comparaison\n # extract the left and right eye coordinates, then use the\n # coordinates to compute the eye aspect ratio for both eyes\n leftEye = landmark.get(\"left_eye\")\n rightEye = landmark.get(\"right_eye\")\n leftEAR = eye_aspect_ratio(leftEye)\n rightEAR = eye_aspect_ratio(rightEye)\n\n # average the eye aspect ratio together for both eyes\n ear = (leftEAR + rightEAR) / 2.0\n\n # check to see if the eye aspect ratio is below the blink\n # threshold, and if so, increment the blink frame counter\n print(ear)\n if not name in counters.keys() :\n counters[name] = 0\n if ear < EYE_AR_THRESH:\n counters[name] += 1\n\n # otherwise, the eye aspect ratio is not below the blink\n # threshold\n else:\n # if the eyes were closed for a sufficient number of\n # then increment the total number of blinks\n if name != \"Unknown\" and counters[name] >= EYE_AR_CONSEC_FRAMES:\n etudiants_presents.add(name)\n\n\n\n\n\n\n # Ajouter l'étudiant détecté à l'ensemble des étudiants\n # reconnus pendant la séance\n if name != \"Unknown\":\n names.append(name)\n etudiants_presents.add(name)\n\n # boucler sur les visages reconnus dans le frame\n print(counters)\n for ((top, right, bottom, left),name) in zip(boxes,names):\n # rescale the face coordinates\n top = int(top * r)\n right = int(right * r)\n bottom = int(bottom * r)\n left = int(left * r)\n\n # dessiner le nom du visage prédit dans l'image\n cv2.rectangle(frame, (left, top), (right, bottom),\n (0, 255, 0), 2)\n y = top - 15 if top - 15 > 15 else top + 15\n cv2.putText(frame, name, (left, y), cv2.FONT_HERSHEY_SIMPLEX,\n 0.75, (0, 255, 0), 2)\n\n # si le 'writer'du video est null *ET* nous sommes supposés d'écrire\n # la video de sortie dans le disque --> initialiser le 'writer'\n if writer is None and 'output/videooutput.avi' is not None:\n fourcc = cv2.VideoWriter_fourcc(*\"MJPG\")\n writer = cv2.VideoWriter('output/videooutput.avi', fourcc, 20,\n (frame.shape[1], frame.shape[0]), True)\n\n # si le 'writer'du video est non null, écrire le frame avec\n # les visages reconnus dans le disque\n if writer is not None:\n writer.write(frame)\n # afficher le streaming\n cv2.imshow(\"Frame\", frame)\n key = cv2.waitKey(1) & 0xFF\n\n # synchroniser le temps réel\n current_time = datetime.datetime.now().time()\n\n # arrêter le video stream\n cv2.destroyAllWindows()\n vs.stop()\n\n # check to see if the video writer point needs to be released\n if writer is not None:\n writer.release()\n time.sleep(2.0)\n return etudiants_presents\n\n\n\ndef eye_aspect_ratio(eye):\n # compute the euclidean distances between the two sets of\n # vertical eye landmarks (x, y)-coordinates\n A = dist.euclidean(eye[1], eye[5])\n B = dist.euclidean(eye[2], eye[4])\n\n # compute the euclidean distance between the horizontal\n # eye landmark (x, y)-coordinates\n C = dist.euclidean(eye[0], eye[3])\n\n # compute the eye aspect ratio\n ear = (A + B) / (2.0 * C)\n\n # return the eye aspect ratio\n return ear\n\n\n","repo_name":"ayoubSoussi/weseeu","sub_path":"gestion_absence/reconnaissance/recognizer.py","file_name":"recognizer.py","file_ext":"py","file_size_in_byte":10715,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"24698540946","text":"from building import *\n\ncwd = GetCurrentDir()\nsrc\t= Glob('*.c')\nCPPPATH = [cwd]\n\n# remove no need file.\nif GetDepend('RT_USING_LWIP') == False:\n SrcRemove(src, 'stm32f2_eth.c')\nif GetDepend('RT_USING_DFS') == False:\n SrcRemove(src, 'sdio_sd.c')\n\n#remove other no use files\n#SrcRemove(src, 'FM25Lx.c')\n#SrcRemove(src, '24LCxx.c')\n\ngroup = DefineGroup('Drivers', src, depend = [''], CPPPATH = CPPPATH)\n\nReturn('group')\n","repo_name":"vvhh2002/lv7_rtthread_f1c100s","sub_path":"rt-thread/bsp/stm32f20x/Drivers/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"77"} +{"seq_id":"10449705161","text":"from vtk import *\n\npts = vtk.vtkPoints()\n\ngrid = vtk.vtkUnstructuredGrid()\n\npv = vtkPolyVertex()\n\nclass Tns(object):\n pass\n\nimport itertools\n\nTns.l_id, Tns.l_x, Tns.l_y, Tns.l_z = xrange(5, 20), xrange(3, 18), xrange(0,30,2), itertools.repeat(-1,15)\n\nTns.units_coords = [(x, y, z) for (u_id, x, y, z) in itertools.izip(Tns.l_id, Tns.l_x, Tns.l_y, Tns.l_z)]\n\nl = []\n\nfor c in Tns.units_coords:\n l.append(pts.InsertNextPoint(c))\n\npv.GetPointIds().SetNumberOfIds(len(l)) # necessay if using SetId and not InsertId in the next loop \nfor i in range(len(l)):\n pv.GetPointIds().SetId(i, l[i])\n\ngrid.InsertNextCell(pv.GetCellType(), pv.GetPointIds())\ngrid.SetPoints(pts)\n\naPolyVertexMapper = vtk.vtkDataSetMapper()\naPolyVertexMapper.SetInput(grid)\naPolyVertexActor = vtk.vtkActor()\naPolyVertexActor.SetMapper(aPolyVertexMapper)\n# Create the usual rendering stuff.\nren = vtk.vtkRenderer()\nrenWin = vtk.vtkRenderWindow()\nrenWin.AddRenderer(ren)\nrenWin.SetSize(300, 150)\niren = vtk.vtkRenderWindowInteractor()\niren.SetRenderWindow(renWin)\nren.SetBackground(.1, .2, .4)\nren.AddActor(aPolyVertexActor)\n# Render the scene and start interaction.\niren.Initialize()\nrenWin.Render()\niren.Start()\n\n\nfrom ui.graphical.visualisation import VisualisableNetwork as VN\n\nfrom ui.graphical.visualisation import VisualisableNetworkStructure as VNS\n\nTns.vns_units = [VNS.Unit(u_id, x, y, z) for (u_id, x, y, z) in itertools.izip(Tns.l_id, Tns.l_x, Tns.l_y, Tns.l_z)]\n\n\n","repo_name":"agravier/pycogmo","sub_path":"tests/visualisation_scratch.py","file_name":"visualisation_scratch.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"6166498906","text":"import numpy as np\nfrom keras.models import Model\nfrom keras.optimizers import SGD, Adam, Nadam, RMSprop\n\nimport data\nimport datagen\nimport net\n\nimport random\nimport skimage.transform\nimport json\n\nimport sys\nimport importlib\nimport datetime\nimport subprocess\n\nSNAP_PATH = '/mnt/data/snap/'\n\nconfig_name = sys.argv[1]\nconfig = importlib.import_module(config_name)\n\nfold = int(sys.argv[2])\n\nweights_file = sys.argv[3]\n\nrun_id = 'localizer' + '__' + config_name + '__' + datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S')\nprint(run_id)\n\nvsize = np.asarray([32,32,32])\n\ndf_nodes = data.ndsb17_get_df_nodes() \ndf_nodes = df_nodes[(df_nodes[\"diameter_mm\"]>=9)]\n\npatient_ids = data.ndsb17_get_patient_ids_noncancer()\nfor k in range(fold):\n np.random.shuffle(patient_ids)\n\nX_nodules, diams = data.ndsb17_get_all_nodules(np.asarray([64,64,64]), df_nodes)\n#X_nodules = [x for x in X_nodules if x.shape == (64,64,64)] # FIXME this was a critical bug, nodules is filtered but diams is not\nprint(\"nodules\", len(X_nodules))\n\nX_nodules_train, X_nodules_test = data.kfold_split(X_nodules, fold)\ndiams_train, diams_test = data.kfold_split(diams, fold)\n\nprint(len(X_nodules_train), len(X_nodules_test))\n\ngen = datagen.batch_generator(vsize, patient_ids, X_nodules_train, diams_train)\n\n\ndef random_volume(image, vsize):\n pos = np.asarray([ np.random.randint(k, image.shape[k] - vsize[k]) for k in range(3) ])\n volume = image[pos[0]:pos[0]+vsize[0], pos[1]:pos[1]+vsize[1], pos[2]:pos[2]+vsize[2]]\n return volume\n\n# FIXME pass nodules split as input\n# FIXME crop because expanded margin for rotation\ntest_nodules = np.stack(X_nodules_test)[:,16:16+32,16:16+32,16:16+32,None]\ntest_nodules = datagen.preprocess(test_nodules)\ntest_nodules = skimage.transform.downscale_local_mean(test_nodules, (1,2,2,2,1), clip=False)\n\n\nnum_test_volumes = 50\ndef get_test_volumes():\n test_volumes = []\n\n vsize = np.asarray([128,128,128])\n\n while len(test_volumes) < num_test_volumes:\n pid = np.random.choice(patient_ids)\n image = data.ndsb17_get_image(pid)\n segmented_image = data.ndsb17_get_segmented_image(pid)\n pos = np.asarray([ np.random.randint(k, image.shape[k] - vsize[k]) for k in range(3) ])\n segmented_volume = segmented_image[pos[0]:pos[0]+vsize[0], pos[1]:pos[1]+vsize[1], pos[2]:pos[2]+vsize[2]]\n if np.count_nonzero(segmented_volume) == 0:\n continue\n volume = image[pos[0]:pos[0]+vsize[0], pos[1]:pos[1]+vsize[1], pos[2]:pos[2]+vsize[2]]\n\n test_volumes.append(volume)\n\n test_volumes = np.stack(test_volumes)[...,None]\n test_volumes = datagen.preprocess(test_volumes)\n test_volumes = skimage.transform.downscale_local_mean(test_volumes, (1,2,2,2,1), clip=False)\n\n return test_volumes\n\n\ntest_volumes = get_test_volumes()\n\n\ndef eval_model(model, volume_model):\n p_list = model.predict(test_nodules)[:,0]\n p_threshold = np.mean(sorted(p_list)[10:15]) # FIXME depends on size of X_nodules and tpr target\n print([ '%.4f' %(x) for x in sorted(p_list)[:10] ])\n #p_threshold = 0.99\n model.save_weights(SNAP_PATH + run_id + '.tmp.h5')\n volume_model.load_weights(SNAP_PATH + run_id + '.tmp.h5')\n\n fpr_list = []\n fpr90_list = []\n for n in range(num_test_volumes):\n test_result = volume_model.predict(test_volumes[n:n+1], batch_size=1)[:,:,:,0]\n test_p = net.sigmoid_activations(test_result)\n fpr = np.count_nonzero(test_p[0,:,:,:] > p_threshold) / test_volumes[n].size\n fpr_list.append(fpr)\n fpr90 = np.count_nonzero(test_p[0,:,:,:] > 0.880797) / test_volumes[n].size\n fpr90_list.append(fpr90)\n \n return np.mean(fpr_list), np.mean(fpr90_list), p_threshold, fpr_list, fpr90_list, p_list\n\n\nhistory = {'loss':[], 'acc':[], 'fpr':[], 'p_threshold':[], 'p_list':[]}\nhistory['version'] = subprocess.check_output('git describe --always --dirty', shell=True).decode('ascii').strip()\nhistory['argv'] = sys.argv\n\nmodel = net.model3d((16, 16, 16), sz=config.feature_sz, alpha=config.feature_alpha)\nprint(model.summary())\nvolume_model = net.model3d((64, 64, 64), sz=config.feature_sz, alpha=config.feature_alpha, do_features=True)\n\ndef get_optimizer(lr):\n if config.optimizer == 'rmsprop':\n optimizer = RMSprop(lr=lr)\n elif config.optimizer == 'adam':\n optimizer = Adam(lr=lr)\n elif config.optimizer == 'nadam':\n optimizer = Nadam(lr=lr)\n elif config.optimizer == 'sgd':\n optimizer = SGD(lr=lr, momentum=0.9, nesterov=True)\n return optimizer\n\nmodel.compile(loss='binary_crossentropy', metrics=['accuracy'], optimizer=get_optimizer(config.lr))\n# model.load_weights(SNAP_PATH + 'localizer.h5')\n\nfom_best = -1e+6\nfor e in range(1, config.num_epochs):\n h = model.fit_generator(\n gen,\n config.samples_per_epoch,\n nb_epoch=1,\n verbose=1)\n\n fpr, fpr90, p_threshold, fpr_list, fpr90_list, p_list = eval_model(model, volume_model)\n print(\"fpr\", fpr, \"fpr90\", fpr90, \"std\", np.std(fpr_list), \"p_threshold\", p_threshold)\n history['loss'].append(h.history['loss'][0])\n history['acc'].append(h.history['acc'][0])\n history['fpr'].append(fpr)\n history['p_threshold'].append(float(p_threshold))\n history['p_list'].append([ float(x) for x in p_list])\n\n model.save_weights(SNAP_PATH + run_id + '.{:04d}'.format(e) + '.h5')\n\n with open(SNAP_PATH + run_id + '.log.json', 'w') as fh:\n json.dump(history, fh)\n\n # trade off 1e-6 fpr versus 0.1 tpr\n fom = np.mean(p_list) - 0.1 * fpr90 / 1e-6\n print(\"fom\", fom)\n if fom > fom_best:\n fom_best = fom\n print(\"*** saving best result\")\n model.save_weights(SNAP_PATH + weights_file)\n\n if e == config.lr_step_num_epochs:\n print(\"*** reloading from best result\")\n\n model.compile(loss='binary_crossentropy', metrics=['accuracy'], optimizer=get_optimizer(config.lr * config.lr_step_multiplier))\n model.load_weights(SNAP_PATH + weights_file)\n","repo_name":"aizvorski/ndsb17","sub_path":"train_localizer.py","file_name":"train_localizer.py","file_ext":"py","file_size_in_byte":5950,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"39172919910","text":"import imp\nimport torch \nfrom torch import nn\nfrom .time_model import TimeModel\nfrom .patient_embedding import TimeConfig, PatientConfig, EventConfig, PatientEmbedding, TemporalInputs\nfrom .medical_classifier import MedicalClassifier\n\nclass Hba1cModel(nn.Module): \n def __init__(self, config): \n super(Hba1cModel, self).__init__()\n self.config = set_up_dimensions(config)\n \n\n # init patient embedding config class \n patient_config_dict = config['patient_config']\n patient_config = PatientConfig(patient_config_dict['representation_type'],\n patient_config_dict['num_inputs'],\n patient_config_dict['hidden_dims'],\n patient_config_dict['activation'],\n patient_config_dict['output_dim'],\n )\n # init time embedding config class \n time_config_dict = config['time_config']\n time_config = TimeConfig(time_config_dict['representation_type'],\n time_config_dict['hidden_dims'],\n time_config_dict['projection_size'],\n time_config_dict['activation'],\n time_config_dict['output_dim'],\n time_config_dict['embeddings_init_std']\n )\n \n # init event embedding config class \n event_config_dict = config['event_config']\n event_config = EventConfig(event_config_dict['categoricals'],\n event_config_dict['continuous'], \n event_config_dict['categorical_representation'],\n event_config_dict['continuous_representation'],\n event_config_dict['categorical_embeddings'],\n event_config_dict['continuous_hidden_dims'],\n event_config_dict['continuous_output_dim'],\n event_config_dict['tf_activation'])\n\n self.patient_embedding = PatientEmbedding(config['aggregation_mode'], \n config['use_patient_info'],\n config['use_time_info'], \n event_config,\n time_config,\n patient_config)\n\n self.model_type = config['model_type']\n self.time_model = TimeModel(config['model_type'], config['max_len'], config['temporal_model'])\n\n config_classifier = config['classifier']\n self.classifier = MedicalClassifier(input_dim=config_classifier['input_dim'],\n hidden_dim=config_classifier['hidden_dim'],\n output_dropout=config_classifier['output_dropout'],\n num_classes=config_classifier['num_classes'],\n use_patient_info=config_classifier['use_patient_info'],\n patient_embedding_dim=config_classifier['patient_embedding_dim'])\n \n def forward(self, inputs):\n x_rep = self.patient_embedding(inputs)\n x, self_attention_weights = self.time_model(x_rep, mask=None)\n out, attention = self.classifier(x, x_rep['sequence_lengths'], x_rep['patient_representation'])\n if self.model_type == 'attention':\n return out, [attention, self_attention_weights]\n return out, [attention]\n\n\n\ndef set_up_dimensions(config): \n event_config_dict = config['event_config']\n patient_config_dict = config['patient_config']\n # set up dimension of inputs of TimeModel \n if config['aggregation_mode'] in ['element-wise-sum-multiplication', 'element-wise-sum', 'element-wise-multiplication']: \n config['patient_config']['output_dim'] = event_config_dict['continuous_output_dim']\n config['time_config']['output_dim'] = event_config_dict['continuous_output_dim']\n config['temporal_model']['input_size'] = event_config_dict['continuous_output_dim']\n # set up dimension of inputs of TimeModel for masking mode \n elif config['aggregation_mode'] == 'mask-multiplication':\n config['time_config']['output_dim'] = event_config_dict['continuous_output_dim']\n if not config['use_patient_info']:\n config['temporal_model']['input_size'] = event_config_dict['continuous_output_dim']\n else: \n config['temporal_model']['input_size'] = event_config_dict['continuous_output_dim']+ patient_config_dict['output_dim']\n # set up dimension of inputs of TimeModel for concat mode \n elif config['aggregation_mode'] == 'concat':\n if (config['use_time_info']) and (config['use_patient_info']):\n config['temporal_model']['input_size'] = event_config_dict['continuous_output_dim'] + config['time_config']['output_dim'] + patient_config_dict['output_dim']\n elif config['use_time_info'] and not config['use_patient_info']:\n config['temporal_model']['input_size'] = event_config_dict['continuous_output_dim'] + config['time_config']['output_dim']\n elif not config['use_time_info'] and config['use_patient_info']:\n config['temporal_model']['input_size'] = event_config_dict['continuous_output_dim'] + patient_config_dict['output_dim']\n else:\n config['temporal_model']['input_size'] = event_config_dict['continuous_output_dim'] \n \n if config['model_type'] == 'attention':\n config['temporal_model']['hidden_size'] = config['temporal_model']['input_size']\n # infer attention heads of Transformer bloc\n config['temporal_model']['attn_heads'] = config['temporal_model']['input_size'] // config['temporal_model']['hidden_size'] \n\n \n # set up input dim of classifier \n if config['temporal_model']['bidirectional'] and config['model_type'] == 'lstm':\n config['classifier']['input_dim'] = config['temporal_model']['hidden_size'] * 2\n elif config['model_type'] == 'attention':\n config['classifier']['input_dim'] = config['temporal_model']['hidden_size'] * config['temporal_model']['attn_heads']\n else: \n config['classifier']['input_dim'] = config['temporal_model']['hidden_size'] \n \n config['classifier']['patient_embedding_dim'] = config['patient_config']['output_dim']\n \n return config\n\n#import numpy as np \n#cfg = load_cfg(\"./config_files/test_1/test.yaml\")\n#model = Hba1cModel(cfg)\n#patient = torch.tensor(np.random.uniform(0, 1, (16, 1)))\n#time = torch.tensor(np.random.uniform(0, 1, (16, 10, 1)))\n#event = {'seq_hba1c': torch.tensor(np.random.uniform(0, 1, (16, 10, 1)))} \n#sequence_lengths = torch.tensor(np.random.randint(1, 11, 16))\n#temporal_inputs = TemporalInputs(event, time, patient, sequence_lengths)\n#print(model(temporal_inputs)[0])\n\n \n\n","repo_name":"sararb/Temporal-Deep-Learning-for-Medical-time-series","sub_path":"models/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"71750162809","text":"from flask import Blueprint, request, jsonify\nfrom essentia.standard import (\n MonoLoader,\n KeyExtractor,\n PitchMelodia,\n RhythmExtractor2013,\n Meter,\n Beatogram,\n BeatsLoudness,\n)\nfrom operator import itemgetter\nfrom .utils import model\nimport os\nfrom tempfile import TemporaryDirectory\nimport math\n\nharmony = Blueprint(\"harmony\", __name__, url_prefix=\"/harmony\")\n\n\ndef allowed_file(filename):\n return \".\" in filename and filename.rsplit(\".\", 1)[1].lower() in {\n \"aiff\",\n \"flac\",\n \"mp3\",\n \"mp4\",\n \"ogg\",\n \"wav\",\n }\n\n\n@harmony.route(\"\", methods=[\"POST\"])\ndef harmonize():\n melody = request.files.get(\"melody\")\n\n if melody is None or melody.filename == \"\":\n return (\n jsonify({\"success\": False, \"message\": \"No file provided\"}),\n 400,\n )\n\n if not allowed_file(melody.filename):\n return jsonify({\"success\": False, \"message\": \"Invalid file type\"}), 400\n\n tempdir = TemporaryDirectory()\n melody_path = os.path.join(tempdir.name, melody.filename)\n melody.save(melody_path)\n melody.close()\n\n audio = MonoLoader(filename=melody_path)()\n\n frequencies, freq_confidence = PitchMelodia()(audio) # binned list of frequencies\n\n key, scale, strength = KeyExtractor()(\n audio\n ) # key (note) and scale (major vs. minor) matter\n\n if scale == \"major\":\n scale = \"Major\"\n\n bpm, beats = RhythmExtractor2013()(audio)[:2]\n bpm = float(request.form.get(\"bpm\", bpm))\n\n loudness, loudness_band_ratio = BeatsLoudness(beats=beats)(audio)\n beatogram = Beatogram()(loudness, loudness_band_ratio)\n meter = Meter()(beatogram)\n start = max(float(beats[0]) - 60 / bpm, 0)\n\n key = request.form.get(\"key\", key + \" \" + scale)\n meter = float(request.form.get(\"meter\", meter))\n\n measure_bin_length = (\n meter * (60 / bpm) * (44100 / 128)\n ) # (beats/measure) (seconds/ebat) * (bins/second) = frequency bins/measure\n\n num_measures = max(round(len(frequencies) / measure_bin_length), 1)\n\n chords = [\"\"] * num_measures # stores string representation of chord progression\n\n # assume first and last chords are tonic\n chords[0] = model[\"keys\"][key][\"chords\"][0]\n chords[num_measures - 1] = chords[0]\n\n for i in range(num_measures - 2):\n # start from second last and go backwards (important for contextual scoring)\n measure_number = len(chords) - 2 - i\n measure_frequencies = frequencies[\n int(measure_number * measure_bin_length) : int(\n min(len(frequencies), (measure_number + 1) * measure_bin_length)\n )\n ]\n measure_confidences = freq_confidence[\n int(measure_number * measure_bin_length) : int(\n min(len(frequencies), (measure_number + 1) * measure_bin_length)\n )\n ]\n\n pitch_histogram = {} # stores number of occurences of each pitch\n index_histogram = {} # stores number of occurences of each pitch\n\n for i in range(len(measure_frequencies)):\n frequency = measure_frequencies[i]\n confidence = measure_confidences[i]\n if frequency == 0.0: # disregard invalid values\n continue\n\n A1 = 55\n pitches = [\"A\", \"A#\", \"B\", \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\"]\n\n pitch_index = round(12 * math.log2(frequency / A1)) % 12\n\n pitch_name = pitches[pitch_index]\n\n if pitch_name in pitch_histogram:\n pitch_histogram[pitch_name] += confidence\n else:\n pitch_histogram[pitch_name] = confidence\n\n chord_scores = {} # arbitrarily defined scores for each possible chord\n available_chords = model[\"keys\"][key][\"chords\"]\n\n for chord in available_chords:\n chord_score = 0\n notes = model[\"chords\"][chord][\"notes\"]\n\n for note in notes:\n note_val = pitch_histogram.get(note, 0)\n\n if note == notes[0]:\n chord_score += 1.2 * note_val\n else:\n chord_score += note_val\n\n chord_scores[chord] = chord_score\n\n chords[measure_number] = max(chord_scores.items(), key=itemgetter(1))[0]\n\n return (\n jsonify(\n {\n \"success\": True,\n \"message\": \"Input harmonized\",\n \"result\": {\n \"chords\": chords,\n \"bpm\": bpm,\n \"key\": key,\n \"meter\": meter,\n \"start\": start,\n },\n }\n ),\n 200,\n )\n","repo_name":"arpanlaha/harmonizer","sub_path":"api/views/harmony.py","file_name":"harmony.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":"8709183745","text":"from distutils.core import setup\n\n\nsetup_kwargs = {\n 'name': 'dalianmao',\n 'version': '0.10',\n 'description': 'A Web Crawling and Web Scraping microframework based on aiohttp',\n 'packages': ['dalianmao',],\n 'platforms': 'any',\n 'license': 'MIT',\n 'author': 'Zeng Jianxin',\n 'author_email': 'zengjx92@163.com',\n 'url': 'https://github.com/ZengJianxin/dalianmao',\n 'classifiers': [\n 'Development Status :: 2 - Pre-Alpha',\n 'Environment :: Console',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n ],\n 'install_requires': [\n 'aiohttp>=1.3.3'\n 'aiofiles>=0.3.0',\n 'beautifulsoup4>=4.2.0',\n 'motor>=1.1'\n ]\n}\n\nsetup(**setup_kwargs)\n\nprint('DaLianMao version {} successfully installed.'.format(setup_kwargs['version']))\n","repo_name":"ZengJianxin/dalianmao","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"77"} +{"seq_id":"36086561854","text":"\nfrom flask_app.config.mysqlconnection import connectToMySQL\nfrom flask_app.models import dojo\n\n\nclass Ninja:\n def __init__(self, data):\n self.id = data['id']\n self.first_name = data['first_name']\n self.last_name = data['last_name']\n self.age = data['age']\n self.created_at = data['created_at']\n self.updated_at = data['updated_at']\n self.dojos_id = data['dojos_id']\n\n @classmethod\n def save(cls, data):\n query = \"INSERT INTO ninjas (first_name, last_name, age, created_at, updated_at, dojos_id) VALUES (%(first_name)s, %(last_name)s, %(age)s, NOW(), NOW(), %(dojo_id)s);\"\n result = connectToMySQL('dojos_and_ninjas_schema').query_db(query,data)\n return result\n\n @classmethod\n def get_all(cls):\n query = \"SELECT * FROM ninjas;\"\n results = connectToMySQL('dojos_and_ninjas_schema').query_db(query)\n ninja = []\n for u in results:\n ninja.append( cls(u) )\n return ninja\n\n @classmethod\n def get_one(cls,data):\n query = \"SELECT * FROM ninjas WHERE id = %(id)s;\"\n result = connectToMySQL('dojos_and_ninjas_schema').query_db(query,data)\n return cls(result[0])\n\n @classmethod\n def dojos_ninjas(cls,data):\n query = \"select * From ninjas WHERE dojos_id = %(id)s\"\n results = connectToMySQL('dojos_and_ninjas_schema').query_db(query,data)\n return results","repo_name":"UncleBud87/python","sub_path":"flask_mysql/crud/dojos_ninjas_mod/flask_app/models/ninja.py","file_name":"ninja.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"7572903487","text":"import sys\r\nfrom collections import Counter\r\ninput = sys.stdin.readline\r\n\r\nn = int(input().strip())\r\n\r\nfor _ in range(n):\r\n answer = \"\"\r\n while True:\r\n x = input().strip()\r\n if x == \"\":\r\n break\r\n answer += x\r\n a = len(answer)\r\n t = Counter(answer)\r\n rr = round(100 * (a - t[\"#\"]) / a,1)\r\n if int(rr) == rr:\r\n rr = int(rr)\r\n print(f\"Efficiency ratio is {rr}%.\")","repo_name":"wjs2063/BaekJoon","sub_path":"백준/Bronze/3448. 문자 인식/문자 인식.py","file_name":"문자 인식.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"36860426438","text":"\"\"\"\nInternal tests that are (partly) only executable with raw data and test recentness of the data\n\"\"\"\n\nimport os\nimport re\nimport time\nimport glob\nimport datetime\nimport itertools\n\nimport pandas as pd\n\ndef test_full_columns(full):\n \"\"\"Columns in data match columns in documentation\"\"\"\n descriptions = []\n for line in open('README.md', 'r', encoding=\"utf8\"):\n match = re.match('- ([\\\\w-]+):.+', line)\n if match:\n descriptions.append(match.group(1))\n assert set(descriptions)-set(['trip']) == set(full.columns) # trip is only in df\n\ndef test_time(full):\n \"\"\"Check time plausibility\"\"\"\n assert (datetime.datetime(year=2020, month=6, day=1, tzinfo=datetime.timezone.utc)\n < full['time'].min())\n assert full['time'].max() < datetime.datetime.now(datetime.timezone.utc)\n\ndef test_full_interpolation(full):\n \"\"\"Interpolated values (~5%)\"\"\"\n assert 0.05 < full['notes'].str.contains('interpolated').mean() < 0.06\n\ndef test_contains_new_data(df, full, newest_dataset_name):\n \"\"\"New file and new content\"\"\"\n # New content in full with cutoff at 10 days\n age = datetime.timedelta(days=10)\n assert time.time() - age.total_seconds() < os.path.getmtime(newest_dataset_name)\n\n cutoff = datetime.datetime.now(datetime.timezone.utc) - age\n assert full['time'].max() > cutoff\n\n # Test individual devices\n for device in full['device'].unique():\n # Any measurement from device\n assert full[full['device']==device]['time'].max() > cutoff\n\n # Test types of measurement\n assert full[(full['device']==device) & (full['ping'].notna())]['time'].max() > cutoff\n assert (full[(full['device']==device) & (full['datarateDown'].notna())]['time'].max()\n > cutoff)\n\n # Allow 17 days for df\n age = datetime.timedelta(days=17)\n cutoff = datetime.datetime.now(datetime.timezone.utc) - age\n assert df['time'].max() > cutoff\n\n # Test individual devices\n for device in df['device'].unique():\n # Any measurement from device\n assert df[df['device']==device]['time'].max() > cutoff\n\n # Test types of measurement\n assert df[(df['device']==device) & (df['ping'].notna())]['time'].max() > cutoff\n assert df[(df['device']==device) & (df['datarateDown'].notna())]['time'].max() > cutoff\n\ndef test_recent_gps_time(df, dfa, dfb):\n \"\"\"Timesync over GPS has happened recently\"\"\"\n age = datetime.timedelta(days=17)\n cutoff = datetime.datetime.now(datetime.timezone.utc) - age\n assert df[df['ntp-TP-Core_refid'] == '.PPS.']['time'].max() > cutoff\n assert dfa[dfa['ntp-GPS-PI_refid'] == '.PPS.']['time'].max() > cutoff\n assert dfb[dfb['ntp-GPS-PI_refid'] == '.PPS.']['time'].max() > cutoff\n\ndef test_gap_mark(full):\n \"\"\"Some marks indicate that parts are missing: Test if neighboring rows are missing\"\"\"\n gap_before = (full['time'].diff(1) > datetime.timedelta(seconds=1))\n gap_after = (-full['time'].diff(-1) > datetime.timedelta(seconds=1))\n gap_at = gap_before | gap_after\n for note in ['old-tech', 'cut-long', 'cut-lat', 'cut-track']:\n assert gap_at[full['notes'].str.contains(note)].all()\n\n # Test inverse; do both neighbors exist\n assert not gap_at[full['notes'].str.contains('interpolated')].any()\n\ndef test_download_details(df, full):\n \"\"\"Plausibility of application level measurement details\"\"\"\n assert (df['download_total_sum'].dropna() == 0).mean() < 0.055\n assert (df['download_total_sum'].dropna() > 1).mean() < 0.005\n\n assert full['download_total_sum'].max() < 15\n assert full['download_connect_sum'].max() < 8\n assert full['download_starting_sum'].max() < 7\n assert full['download_done_sum'].max() < 6\n assert full['download_cannot_sum'].max() < 6\n assert full['download_timeout_sum'].max() < 6\n\n # Test if more downloads finish than start (not perfect as lines with downloads can be dropped)\n fullf = full.groupby(\"file\")\n assert (((fullf['download_starting_sum'].sum() - fullf['download_done_sum'].sum()) >= 0).mean()\n > 0.975)\n assert (fullf['download_starting_sum'].sum() - fullf['download_done_sum'].sum()).max() <= 12\n\n # total_bw lines > 0 -> est available (not always because of misplaced linebreaks)\n assert ((full['download_total_sum'] > 0) == full['datarateDown_app'].notna()).mean() > 0.9999\n\ndef test_filename_content(full):\n \"\"\"Filename corresponds to data within\"\"\"\n file_times = full.groupby('file')[['time']].min()\n file_times['filetime'] = pd.to_datetime(file_times.index.str[0:15],\n errors='coerce').tz_localize(\"Europe/Vienna\").tz_convert(\"UTC\")\n assert ((file_times['filetime'] - file_times['time']).abs().max()\n < datetime.timedelta(minutes=13))\n\ndef test_full_note_appearances(df, full):\n \"\"\"Test if all notes appear and no unknown notes appear\"\"\"\n notes = ['resample-loss', 'interpolated', 'cut-long', 'cut-lat', 'cut-track', 'est_error',\n 'neg-time-diff-time', 'neg-time-diff-gpstime', 'old-tech', 'high-timestamp-position',\n 'high-timestamp-stdOut', 'low-timestamp-signalStrength', 'low-timestamp-download',\n 'low-timestamp-stdOut', 'incomplete-signalStrength', 'low-timestamp-position']\n # Need to add file-specific notes as they appear (that is, when this test fails)\n\n # All types of notes appear in full dataset\n for note in notes:\n assert full['notes'].str.contains(note).any() | df['notes'].str.contains(note).any()\n\n # All notes in dataset are in list\n for note in itertools.chain.from_iterable(full['notes'].str.split(',').tolist()):\n if note != '':\n assert note in notes\n\ndef test_abandoned_measurement_logs(raw_folder):\n \"\"\"Test if days with measurement logs have data files\"\"\"\n logs = glob.glob(raw_folder + '**/*-measurement.log', recursive=True)\n log_days = set([l[:-20] for l in logs])\n measurements = glob.glob(raw_folder + '**/*.txt', recursive=True)\n empty_days = [day for day in log_days if len([m for m in measurements if m.startswith(day)])==0]\n assert len(empty_days) <= 30 # Known value of empty days\n","repo_name":"mherlich/redundant-wireless-data-set","sub_path":"tests/test_data_internal.py","file_name":"test_data_internal.py","file_ext":"py","file_size_in_byte":6118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"5174058379","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 29 19:13:17 2022\n\n@author: andrea\n\"\"\"\nimport numpy as np\n\n\nimport cv2\n\ndef stack_registration(stack, z_idx, c_idx = 0, method = 'cv2', mode = 'Euclidean'):\n '''\n Stack registration works on 3D 4D stacks\n Paramenters:\n z_idx: index of the stack where the registration starts\n c_idx: for 4D stacks it is the channel on which the registration is performed. \n The other channels are registered with the warp matrix found in this channel\n method: choose between 'optical flow', 'crosscorrelation', 'cv2'\n mode: type of registration for cv2\n \n Returns a 3D or 4D resistered stack\n \n '''\n \n \n def phase_cross_reg(ref, im):\n from scipy.ndimage import fourier_shift\n from skimage.registration import phase_cross_correlation\n \n shift, error, diffphase = phase_cross_correlation(ref,im)\n print(shift)\n reg = fourier_shift(np.fft.fftn(im), shift)\n reg = np.fft.ifftn(reg).real \n return reg, None\n \n def optical_flow_reg(ref,im): # --- Compute the optical flow\n from skimage.registration import optical_flow_tvl1 \n from skimage.transform import warp\n v, u = optical_flow_tvl1(ref, im)\n nr, nc = ref.shape\n row_coords, col_coords = np.meshgrid(np.arange(nr), np.arange(nc),\n indexing='ij')\n reg = warp(im, np.array([row_coords + v, col_coords + u]))\n return reg, None\n \n def cv2_reg(ref,im, mode = mode):\n\n warp_mode_dct = {'Translation' : cv2.MOTION_TRANSLATION,\n 'Affine' : cv2.MOTION_AFFINE,\n 'Euclidean' : cv2.MOTION_EUCLIDEAN,\n 'Homography' : cv2.MOTION_HOMOGRAPHY\n }\n warp_mode = warp_mode_dct[mode] \n \n \n \n number_of_iterations = 3000\n termination_eps = 1e-6\n criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT,\n number_of_iterations, termination_eps)\n \n if warp_mode == cv2.MOTION_HOMOGRAPHY :\n warp_matrix = np.eye(3, 3, dtype=np.float32)\n else :\n warp_matrix = np.eye(2, 3, dtype=np.float32)\n \n try:\n _, warp_matrix = cv2.findTransformECC((ref.astype(np.float32)), im.astype(np.float32),\n warp_matrix, warp_mode, criteria)\n \n reg = apply_warp(im, warp_matrix)\n except Exception as e:\n # print(f'{e}, frame not registered')\n reg = im\n \n return reg, warp_matrix \n \n \n def apply_warp(im,w):\n sy,sx = im.shape\n reg = cv2.warpAffine(im, w, (sx,sy),\n flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP)\n return reg\n \n \n if method == 'optical flow':\n image_registration = optical_flow_reg\n elif method == 'crosscorrelation':\n image_registration = phase_cross_reg\n elif method == 'cv2':\n image_registration = cv2_reg \n else:\n raise(TypeError, f'registration method {method} not supported')\n \n s = stack.shape\n \n if stack.ndim ==4:\n sc = s[0]\n sz = s[1] \n \n registered = np.zeros_like(stack)\n wm_list = [np.eye(2, 3, dtype=np.float32)]*sz\n registered[c_idx,z_idx,:,:] = stack[c_idx,z_idx,:,:] \n \n #otherchannels = [ci for ci in range(sc) if ci !=c_idx ] \n #print(otherchannels)\n \n #register forwards\n for zi in range(z_idx,sz):\n ref_image = registered[c_idx,zi-1,:,:]\n current_image = stack[c_idx,zi,:,:]\n _, wm = image_registration(ref_image, current_image)\n for ci in range(sc):\n otherimage = stack[ci,zi,:,:]\n registered[ci,zi,:,:] = apply_warp(otherimage, wm)\n wm_list[zi] = wm\n #register backwards\n for zi in range(z_idx-1,-1,-1):\n ref_image = registered[c_idx,zi+1,:,:]\n current_image = stack[c_idx,zi,:,:]\n _, wm = image_registration(ref_image, current_image)\n for ci in range(sc):\n otherimage = stack[ci,zi,:,:]\n registered[ci,zi,:,:] = apply_warp(otherimage, wm)\n wm_list[zi] = wm\n \n return registered, wm_list \n \n \n elif stack.ndim ==3:\n sz = s[0]\n registered = np.zeros_like(stack)\n wm_list = [np.eye(2, 3, dtype=np.float32)]*sz\n registered[z_idx,:,:] = stack[z_idx,:,:]\n \n #register forwards\n for zi in range(z_idx+1,sz):\n ref_image = registered[zi-1,:,:]\n current_image = stack[zi,:,:]\n registered[zi,:,:],wm = image_registration(ref_image, current_image)\n wm_list[zi] = wm\n #register backwards\n for zi in range(z_idx-1,-1,-1):\n ref_image = registered[zi+1,:,:]\n current_image = stack[zi,:,:]\n registered[zi,:,:],wm = image_registration(ref_image, current_image)\n wm_list[zi] = wm\n \n return registered, wm_list\n\n else:\n raise(TypeError( 'only 3D (z,y,x) or 4D (c,z,y,x) registration is supported'))\n \n \nif __name__ == '__main__':\n \n \n import matplotlib.pyplot as plt\n from skimage import data\n from scipy.ndimage import fourier_shift\n \n image = data.camera()\n shift0 = np.array([-22.4, 13.32])\n\n offset_image = fourier_shift(np.fft.fftn(image), shift0)\n \n offset_image = np.fft.ifftn(offset_image).real\n \n shift1 = np.array([15, 5])\n offset_image1 = fourier_shift(np.fft.fftn(offset_image), shift1)\n \n offset_image1 = np.fft.ifftn(offset_image1).real\n \n stack0 = np.array([image,offset_image,offset_image1])\n \n registered1 = stack_registration(stack0, 0 )\n\n fig = plt.figure(figsize=(8, 3))\n #plt.imshow(offset_image.real, cmap='gray')\n plt.imshow(registered1[1,:,:], cmap='gray', vmin = -24, vmax =270)\n\n","repo_name":"andreabassi78/Napari_Applications","sub_path":"HexSIM/registration_tools.py","file_name":"registration_tools.py","file_ext":"py","file_size_in_byte":6136,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"77"} +{"seq_id":"18301441180","text":"import logging\nimport requests\nimport time\nfrom bs4 import BeautifulSoup\nfrom urllib.error import HTTPError\n\nlogger = logging.getLogger(__name__)\n\nclass RateCentralbank:\n # Считаем курс доллара на сегодня\n @classmethod\n def rate_dollar(cls) -> float:\n # Пока не получим актуальный курс - не уйдем\n while True:\n try:\n all_rate_text = requests.get('https://www.cbr.ru/scripts/XML_daily.asp'\n ).text\n rate_as_str = BeautifulSoup(all_rate_text,\n features='xml'\n ).Value.string\n dollar_rate = float(rate_as_str.replace(',', '.'))\n return dollar_rate\n except AttributeError:\n msg = ('Не получены данные по курсу!',\n 'Повторная попытка через минуту!')\n logger.warning(msg)\n time.sleep(60)\n except HTTPError:\n msg = 'API ЦБ отказался принять запрос или URL изменился!'\\\n 'Повторная попытка через минуту!'\n logger.warning(msg)\n time.sleep(60)\n","repo_name":"georg220022/Google_Sheet","sub_path":"google_sheet/centrobank.py","file_name":"centrobank.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"9781051791","text":"from abstraction import *\nfrom display_settings import *\ntitle=\"Desi StImUlAtOr\"\nglutInit(sys.argv)\nglutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)\nglutInitWindowSize(display_height, display_width)\nglutInitWindowPosition(100, 100)\nglutCreateWindow(title)\ninit()\n#Display\nglutDisplayFunc(display)\nglutReshapeFunc(reshape)\nglutKeyboardFunc(keyboard)\nglutMouseFunc(mouse)\nglutMainLoop()\n","repo_name":"shubhankarsharma00/circuit-draw","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"77"} +{"seq_id":"2537879783","text":"from ftplib import FTP \r\nimport os\r\nimport fileinput\r\nimport ftplib\r\n\r\ndef ftp_upload(localfile, remotefile, ftp_folder, full_remote_file_path):\r\n ftp = FTP()\r\n ftp.set_debuglevel(2)\r\n ftp.connect('endereço_ip', 21) \r\n ftp.login('usuário_ftp', 'senha')\r\n ftp.cwd(ftp_folder)\r\n\r\n fp = open(localfile, 'rb')\r\n ftp.storbinary('STOR %s' % os.path.basename(localfile), fp, 1024)\r\n fp.close()\r\n print(\"after upload \" + localfile + \" to \" + remotefile)\r\n \r\n ","repo_name":"rodolfhoalves/cmflex2ftp","sub_path":"ftp.py","file_name":"ftp.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":"37075225565","text":"import cv2\n\n# Inisialisasi pengenal wajah (gunakan cascade classifier)\nface_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')\n\n# Mulai streaming dari kamera (gunakan angka 0 untuk kamera bawaan)\ncap = cv2.VideoCapture(0)\n\nwhile True:\n # Baca frame dari kamera\n ret, frame = cap.read()\n\n # Konversi frame ke abu-abu (grayscale) untuk deteksi wajah\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # Deteksi wajah dalam frame\n faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))\n\n # Gambar kotak di sekitar wajah yang terdeteksi\n for (x, y, w, h) in faces:\n cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 3)\n\n # Tampilkan frame yang telah dimodifikasi\n cv2.imshow('Face Detection', frame)\n\n # Berhenti jika tombol 'q' ditekan\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# Tutup kamera dan jendela tampilan\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"DestaFauzi/SIMFONI-FACE-RECOGNITION","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"} +{"seq_id":"15956363854","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom msedge.selenium_tools import Edge, EdgeOptions\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\ndef find_book(ISBN):\n book_title, book_series, book_author = find_on_abebooks(ISBN)\n\n if book_title == None:\n book_title2, book_series2, book_author2 = find_on_goodreads(ISBN)\n\n if book_title2 == None:\n return None\n else:\n return book_title2, book_series2, book_author2\n\n return book_title, book_series, book_author\n\n\ndef find_on_goodreads(ISBN):\n # Launch Microsoft Edge (Chromium)\n PATH = \"/Users/azw/Pictures/Programming/book-inventory/edgedriver_mac64/msedgedriver\"\n\n options = EdgeOptions()\n options.use_chromium = True\n options.add_argument(\"headless\")\n options.set_capability(\"platform\", \"MAC\")\n\n driver = Edge(executable_path=PATH, options=options)\n\n driver.get(\"https://www.goodreads.com/\")\n\n search = driver.find_element_by_name(\"query\")\n search.clear()\n search.send_keys(ISBN)\n search.send_keys(Keys.RETURN)\n\n try:\n title = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.ID, \"bookTitle\"))\n )\n series = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.ID, \"bookSeries\"))\n )\n authors = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.ID, \"bookAuthors\"))\n )\n\n book_title = title.text\n book_series = series.text\n author = authors.text[3:]\n book_author = author.split(\",\")\n\n if book_series == \"\":\n book_series = None\n\n return book_title, book_series, book_author\n\n except:\n book_title = None\n book_series = None\n book_author = None\n\n return book_title, book_series, book_author\n\n # time.sleep(5)\n driver.quit()\n\n\ndef find_on_abebooks(ISBN):\n url = f\"https://www.abebooks.com/servlet/SearchResults?sts=t&isbn={ISBN}\"\n\n page = requests.get(url)\n soup = BeautifulSoup(page.content, \"html.parser\")\n\n try:\n result = soup.find(\"li\", {\"id\": \"book-1\"})\n heading = result.find(\"h2\", {\"class\": \"title\"})\n heading_url = heading.find(\"a\")\n book_title = heading_url.span.string\n p_author = result.find(\"p\", {\"class\": \"author\"})\n author = p_author.strong.string\n book_author = author.split(\",\")\n book_series = None\n\n return book_title, book_series, book_author\n\n except:\n book_title = None\n book_series = None\n book_author = None\n\n return book_title, book_series, book_author\n\n\n# THIS THREAD SAVED ME\n# https://travis-ci.community/t/runtime-for-releases-of-edge-and-msedgedriver-with-python/11552\n\n\n# DESIRED_CAP = {\"os\": \"OS X\",\n# \"os_version\": \"Big Sur\",\n# \"browser\": \"Edge\",\n# \"browser_version\": \"90.0\",\n# \"browserstack.local\": \"false\",\n# \"browserstack.selenium_version\": \"3.141.0\"\n# }\n# driver = webdriver.Edge(executable_path=PATH,\n# capabilities=DESIRED_CAP, options=options)\n","repo_name":"azwidodo/book-inventory","sub_path":"find_book_Edge.py","file_name":"find_book_Edge.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"77"}