diff --git "a/1366.jsonl" "b/1366.jsonl" new file mode 100644--- /dev/null +++ "b/1366.jsonl" @@ -0,0 +1,1163 @@ +{"seq_id":"13279785181","text":"from sklearn.naive_bayes import ComplementNB\nimport pickle\n\ndef train(dataset): \n\tX = dataset[0] # vecteur d'image\n\ty = dataset[1] # vecteur de classes\n\n\talgo = ComplementNB()\n\ttrain = algo.fit(X, y)\n\tpickle.dump(train, open(\"trainModel.joblib\", \"wb\"))\n\n\ndef predict (dataset):\n\ttrain = pickle.load(open(\"trainModel.joblib\", \"rb\"))\n\tresult = train.predict(dataset)\n\t\n\treturn result\n","repo_name":"Roger-ELIAS/Apprentissage-Automatique","sub_path":"naiveBayes.py","file_name":"naiveBayes.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42837766106","text":"import sys\nimport os\nimport math\nimport random\nfrom sklearn import datasets\nimport numpy as np\nfrom utils.distances import ciede_distance\nfrom utils.distances import euclidean_distance\nfrom utils.PCA import PCA\n\n# Import helper functions\n# dir_path = os.path.dirname(os.path.realpath(__file__))\n# sys.path.insert(0, dir_path + \"/../utils\")\n# from data_manipulation import normalize\n# from data_operation import euclidean_distance\n#\n# sys.path.insert(0, dir_path + \"/../unsupervised_learning/\")\n# from principal_component_analysis import PCA\n\n\nclass PAM():\n \"\"\"A simple clustering method that forms k clusters by first assigning\n samples to the closest medoids, and then swapping medoids with non-medoid\n samples if the total distance (cost) between the cluster members and their medoid\n is smaller than prevoisly.\n\n\n Parameters:\n -----------\n k: int\n The number of clusters the algorithm will form.\n \"\"\"\n\n def __init__(self, k=2):\n self.k = k\n\n # Initialize the medoids as random samples\n def _init_random_medoids(self, X):\n n_samples, n_features = np.shape(X) #кол-во примеров, размерность параметров\n\n medoids = np.zeros((self.k, n_features)) #массив из нулей, размерность - кол-во кластеров Х кол-во фич\n\n #while (len(np.unique(medoids, axis=0)) != self.k):\n for i in range(self.k):\n medoid = X[np.random.choice(range(n_samples), replace=False)]\n medoids[i] = medoid\n return medoids\n\n # Return the index of the closest medoid to the sample\n def _closest_medoid(self, sample, medoids):\n closest_i = None\n closest_distance = float(\"inf\")\n for i, medoid in enumerate(medoids):\n #distance = euclidean_distance(sample, medoid)\n distance = ciede_distance(sample, medoid)\n if distance < closest_distance:\n closest_i = i\n closest_distance = distance\n return closest_i\n\n # Assign the samples to the closest medoids to create clusters\n def _create_clusters(self, X, medoids):\n clusters = [[] for _ in range(self.k)]\n for sample_i, sample in enumerate(X): #sample_i - счетчик, sample - элемент в X\n medoid_i = self._closest_medoid(sample, medoids)\n clusters[medoid_i].append(sample_i)\n if((sample_i + 1) % 10000 == 0):\n print(sample_i)\n return clusters\n\n # Calculate the cost (total distance between samples and their medoids)\n def _calculate_cost(self, X, clusters, medoids):\n cost = 0\n # For each cluster\n for i, cluster in enumerate(clusters):\n medoid = medoids[i]\n for sample_i in cluster:\n # Add distance between sample and medoid as cost\n #cost += euclidean_distance(X[sample_i], medoid)\n cost += ciede_distance(X[sample_i], medoid)\n #print(cost)\n\n return cost\n\n # Returns a list of all samples that are not currently medoids\n def _get_non_medoids(self, X, medoids):\n non_medoids = []\n for sample in X:\n if not sample in medoids:\n non_medoids.append(sample)\n return non_medoids\n\n # Classify samples as the index of their clusters\n def _get_cluster_labels(self, clusters, X):\n # One prediction for each sample\n y_pred = np.zeros(np.shape(X)[0])\n for cluster_i in range(len(clusters)):\n cluster = clusters[cluster_i]\n for sample_i in cluster:\n y_pred[sample_i] = cluster_i\n return y_pred\n\n\n # Do Partitioning Around Medoids and return the cluster labels\n def fit(self, X):\n # Initialize medoids randomly\n medoids = self._init_random_medoids(X) #содержит семплы\n # Assign samples to closest medoids\n clusters = self._create_clusters(X, medoids) #содержит индексы X\n\n # Calculate the initial cost (total distance between samples and\n # corresponding medoids)\n cost = self._calculate_cost(X, clusters, medoids)\n\n # Iterate until we no longer have a cheaper cost\n i = 0\n while True:\n print(\"iteration: \" + i.__str__())\n i = i + 1\n best_medoids = medoids\n lowest_cost = cost\n for medoid in medoids:\n # Get all non-medoid samples\n non_medoids = self._get_non_medoids(X, medoids)\n # Calculate the cost when swapping medoid and samples\n for sample in non_medoids:\n # Swap sample with the medoid\n new_medoids = medoids.copy()\n #new_medoids[medoids == medoid] = sample\n new_medoids[np.argwhere(medoids == medoid)[0][0]] = sample\n # Assign samples to new medoids\n new_clusters = self._create_clusters(X, new_medoids)\n # Calculate the cost with the new set of medoids\n new_cost = self._calculate_cost(X, new_clusters, new_medoids)\n # If the swap gives us a lower cost we save the medoids and cost\n if new_cost < lowest_cost:\n lowest_cost = new_cost\n best_medoids = new_medoids\n # If there was a swap that resultet in a lower cost we save the\n # resulting medoids from the best swap and the new cost\n if lowest_cost < cost:\n cost = lowest_cost\n medoids = best_medoids\n # Else finished\n else:\n print(lowest_cost)\n break\n\n final_clusters = new_clusters#self._create_clusters(X, medoids)\n self.cluster_medoids_ = medoids\n # Return the samples cluster indices as labels\n return self._get_cluster_labels(final_clusters, X)\n\n def predict(self, X):\n final_clusters = self._create_clusters(X, self.cluster_medoids_)\n return self._get_cluster_labels(final_clusters, X)\n\n\ndef main():\n # Load the dataset\n X, y = datasets.make_blobs()\n\n # Cluster the data using K-Medoids\n clf = PAM(k=3)\n clf.fit(X[:20])\n y_pred = clf.predict(X)\n print(y_pred)\n print(clf.cluster_medoids_)\n\n # Project the data onto the 2 primary principal components\n pca = PCA()\n pca.plot_in_2d(X, y_pred)\n pca.plot_in_2d(X, y)\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"ipospelov/color-constancy","sub_path":"k_medoids.py","file_name":"k_medoids.py","file_ext":"py","file_size_in_byte":6576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4982329713","text":"from datetime import date, time, datetime\nfrom PyQt5.QtGui import QColor\n\n# Defines custom data types for capra. Currently all are only used in conjunction\n# with the projector\n\n\nclass CapraDataType:\n \"\"\"Superclass for shared functionality between Picture and Hike objects\"\"\"\n def _parse_hr_min(self, timestamp: float) -> str:\n \"\"\"Parses timestamp into string\n ::\n\n :param timestamp: Unix timestamp\n :return str: '5:19 PM'\n \"\"\"\n t = datetime.fromtimestamp(timestamp)\n s = t.strftime('%-I:%M')\n return s\n\n def _parse_sec(self, timestamp: float) -> str:\n \"\"\"Parses timestamp into string\n ::\n\n :param timestamp: Unix timestamp\n :return str: ':24 PM'\n \"\"\"\n t = datetime.fromtimestamp(timestamp)\n s = t.strftime(':%S %p')\n return s\n\n def _parse_am_pm(self, timestamp: float) -> str:\n \"\"\"Parses timestamp into AM or PM\n ::\n\n :param timestamp: Unix timestamp\n :return str: 'PM'\n \"\"\"\n t = datetime.fromtimestamp(timestamp)\n s = t.strftime(' %p')\n return s\n\n def _parse_date(self, timestamp: float) -> str:\n \"\"\"Parses timestamp into string\n ::\n\n :param timestamp: Unix timestamp\n :return str: 'April 27, 2019'\n \"\"\"\n d = datetime.fromtimestamp(timestamp)\n s = d.strftime('%B %-d, %Y')\n return s\n\n def _parse_hike(self, hike: int) -> str:\n \"\"\"Parses `int` into string\n ::\n\n :param hike: int\n :return str: 'Hike 2'\n \"\"\"\n s = 'Hike {h}'.format(h=hike)\n return s\n\n def _parse_color(self, text: str) -> QColor:\n \"\"\"Parses `,` separated text into QColor\n ::\n\n :param text: input format \"217,220,237\"\n :return: QColor in RBG format\n \"\"\"\n\n c = text.split(',')\n color = QColor(int(c[0]), int(c[1]), int(c[2]))\n return color\n\n def _parse_color_HSV(self, text: str) -> QColor:\n \"\"\"Parses `,` separated text into QColor\n ::\n\n :param text: input format \"217,220,237\"\n :return: QColor in HSV format\n \"\"\"\n c = text.split(',')\n color = QColor()\n color.setHsv(int(c[0]), int(c[1]), int(c[2]))\n return color\n\n def _parse_color_list(self, text: str) -> list:\n \"\"\"Parses `|` and `,` separated text into list of QColors\n ::\n\n :param text: input format \"217,220,237|92,78,69|50,49,43|50,42,31|78,75,82\"\n :return: list of QColors\n \"\"\"\n\n color_strs = text.split('|')\n colorlist = list()\n for c in color_strs:\n color = self._parse_color(c)\n colorlist.append(color)\n return colorlist\n\n def _parse_percent_list(self, text: str) -> list:\n \"\"\"Parses `,` separated text into a list of floats\n ::\n\n :param text: input format \"0.46,0.16,0.15,0.15,0.09\"\n :return: list of float (each value is between 0.0 - .99)\n \"\"\"\n\n percents = text.split(',')\n percents = list(map(float, percents))\n return percents\n\n\nclass Picture(CapraDataType):\n \"\"\"Defines object which hold a row from the database table 'pictures'\"\"\"\n\n def __init__(self, picture_id, time, year, month, day, minute, dayofweek, hike_id, index_in_hike, timerank_global,\n altitude, altrank_hike, altrank_global, altrank_global_h,\n color_hsv, color_rgb, colorrank_hike, colorrank_global, colorrank_global_h,\n colors_count, colors_rgb, colors_conf,\n camera1, camera2, camera3, cameraf, created, updated):\n super().__init__()\n self.picture_id = picture_id\n self.time = time\n self.year = year\n self.month = month\n self.day = day\n self.minute = minute\n self.dayofweek = dayofweek\n\n self.hike_id = hike_id\n self.index_in_hike = index_in_hike\n self.timerank_global = timerank_global\n\n self.altitude = altitude\n self.altrank_hike = altrank_hike\n self.altrank_global = altrank_global\n self.altrank_global_h = altrank_global_h\n\n self.color_hsv = self._parse_color_HSV(color_hsv)\n self.color_rgb = self._parse_color(color_rgb)\n self.colorrank_hike = colorrank_hike\n self.colorrank_global = colorrank_global\n self.colorrank_global_h = colorrank_global_h\n self.colors_count = colors_count\n self.colors_rgb = self._parse_color_list(colors_rgb)\n self.colors_conf = self._parse_percent_list(colors_conf)\n\n self.camera1 = camera1\n self.camera2 = camera2\n self.camera3 = camera3\n self.cameraf = cameraf\n\n self.created = created\n self.updated = updated\n\n # Labels for the UI\n self.uitime_hrmm = self._parse_hr_min(self.time)\n self.uitime_sec = self._parse_sec(self.time)\n self.uitime_ampm = self._parse_am_pm(self.time)\n self.uidate = self._parse_date(self.time)\n self.uihike = self._parse_hike(self.hike_id)\n self.uialtitude = str(int(self.altitude))\n\n def print_obj_mvp(self):\n print('({id}, {t}, {yr}, {mth}, {day}, {min}, {dow}, {hike_id}, {index}, {alt}, {altr}, {hsv}, {rgb}, {crh}, {crg}, {c1}, {c2}, {c3}, {cf})\\\n '.format(id=self.picture_id, t=self.time, yr=self.year, mth=self.month, day=self.day,\n min=self.minute, dow=self.dayofweek, hike_id=self.hike_id, index=self.index_in_hike,\n alt=self.altitude, altr=self.altrank_global, hsv=self.color_hsv, rgb=self.color_rgb,\n crh=self.colorrank_hike, crg=self.colorrank_global, c1=self.camera1, c2=self.camera2, c3=self.camera3, cf=self.cameraf))\n\n def print_obj(self):\n print('id\\ttime\\t\\taltitude\\thike_id\\tindex\\taltrank_hike\\tcolorrank_hike\\tpath')\n print('{id}\\t{t}\\t{alt}\\t\\t{hike_id}\\t{index}\\t{ar}\\t\\t{cr}\\t{pth}\\n\\\n '.format(id=self.picture_id, t=self.time, alt=self.altitude,\n hike_id=self.hike_id, index=self.index_in_hike, ar=self.altrank_hike, cr=self.colorrank_hike, pth=self.cameraf))\n\n\nclass Hike(CapraDataType):\n \"\"\"Defines object which hold a row from the database table 'hikes'\"\"\"\n\n def __init__(self, hike_id, avg_altitude, avg_altrank,\n start_time, start_year, start_month, start_day, start_minute, start_dayofweek,\n end_time, end_year, end_month, end_day, end_minute, end_dayofweek,\n color_rgb, color_rank,\n num_pictures, path, created, updated):\n super().__init__()\n\n self.hike_id = hike_id\n self.avg_altitude = avg_altitude\n self.avg_altrank = avg_altrank\n\n self.start_time = start_time\n self.start_year = start_year\n self.start_month = start_month\n self.start_day = start_day\n self.start_minute = start_minute\n self.start_dayofweek = start_dayofweek\n self.end_time = end_time\n self.end_year = end_year\n self.end_month = end_month\n self.end_day = end_day\n self.end_minute = end_minute\n self.end_dayofweek = end_dayofweek\n\n self.color_rgb = self._parse_color(color_rgb)\n self.color_rank = color_rank\n self.num_pictures = num_pictures\n self.path = path\n\n self.created = created\n self.updated = updated\n\n self.uistarttime_hrmm = self._parse_hr_min(self.start_time)\n self.uistartdate = self._parse_date(self.start_time)\n self.uihike = self._parse_hike(self.hike_id)\n self.uialtitude = str(int(self.avg_altitude))\n\n def print_obj(self):\n print('Hike ID\\tstart time\\t\\tavg_alt\\tavg_altrank\\tcolor\\tcolor_rank\\tpictures\\tpath')\n print('{id}\\t{t}\\t{avg_alt}\\t{avg_altrank}\\t{color}\\t{color_rank}\\t{pic}\\t{path}\\n\\\n '.format(id=self.hike_id, t=self.start_time, avg_alt=self.avg_altitude, avg_altrank=self.avg_altrank,\n color=self.color_rgb, color_rank=self.color_rank, pic=self.num_pictures, path=self.path))\n\n def get_hike_length_seconds(self) -> float:\n return round(self.end_time - self.start_time, 0)\n\n def get_hike_length_minutes(self) -> float:\n return round((self.end_time - self.start_time)/60, 1)\n\n\nclass UIData:\n \"\"\"Defines object which holds all the UI data for the archive\"\"\"\n\n def __init__(self):\n super().__init__()\n\n # Hikes UI data\n self.indexListForHike = {}\n\n self.altitudesSortByAltitudeForHike = {}\n self.altitudesSortByColorForHike = {}\n self.altitudesSortByTimeForHike = {}\n\n self.colorSortByAltitudeForHike = {}\n self.colorSortByColorForHike = {}\n self.colorSortByTimeForHike = {}\n\n # Archive UI data\n self.indexListForArchive = []\n\n self.altitudesSortByAltitudeForArchive = []\n self.altitudesSortByColorForArchive = []\n self.altitudesSortByTimeForArchive = []\n\n self.colorSortByAltitudeForArchive = []\n self.colorSortByColorForArchive = []\n self.colorSortByTimeForArchive = []\n","repo_name":"EverydayDesignStudio/capra","sub_path":"classes/capra_data_types.py","file_name":"capra_data_types.py","file_ext":"py","file_size_in_byte":9197,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"4034822770","text":"import numpy as np\nimport pytest\nfrom hypothesis import given\nfrom thewalrus.fock_gradients import (\n beamsplitter,\n displacement,\n mzgate,\n squeezing,\n two_mode_squeezing,\n)\n\nfrom mrmustard.lab import (\n Attenuator,\n BSgate,\n Coherent,\n Dgate,\n Interferometer,\n MZgate,\n RealInterferometer,\n Rgate,\n S2gate,\n Sgate,\n)\nfrom mrmustard.lab.states import TMSV, Fock, SqueezedVacuum, State\nfrom mrmustard.math import Math\nfrom mrmustard.math.lattice import strategies\nfrom mrmustard.physics import fock\nfrom tests.random import (\n angle,\n array_of_,\n medium_float,\n n_mode_pure_state,\n r,\n single_mode_cv_channel,\n single_mode_unitary_gate,\n two_mode_unitary_gate,\n)\n\nmath = Math()\n\n\n@given(state=n_mode_pure_state(num_modes=1), x=medium_float, y=medium_float)\ndef test_Dgate_1mode(state, x, y):\n state_out = state >> Dgate(x, y) >> Dgate(-x, -y)\n assert state_out == state\n\n\ndef test_attenuator_on_fock():\n \"tests that attenuating a fock state makes it mixed\"\n assert not (Fock(10) >> Attenuator(0.5)).is_pure\n\n\n@given(state=n_mode_pure_state(num_modes=2), xxyy=array_of_(medium_float, minlen=4, maxlen=4))\ndef test_Dgate_2mode(state, xxyy):\n x1, x2, y1, y2 = xxyy\n state_out = state >> Dgate([x1, x2], [y1, y2]) >> Dgate([-x1, -x2], [-y1, -y2])\n assert state_out == state\n\n\n@given(gate=single_mode_cv_channel())\ndef test_single_mode_fock_equals_gaussian_dm(gate):\n \"\"\"Test same state is obtained via fock representation or phase space\n for single mode circuits.\"\"\"\n cutoffs = [60]\n gaussian_state = SqueezedVacuum(0.5) >> Attenuator(0.5)\n fock_state = State(dm=gaussian_state.dm(cutoffs))\n\n via_fock_space_dm = (fock_state >> gate).dm(cutoffs)\n via_phase_space_dm = (gaussian_state >> gate).dm(cutoffs)\n assert np.allclose(via_fock_space_dm, via_phase_space_dm)\n\n\n@given(gate=single_mode_unitary_gate())\ndef test_single_mode_fock_equals_gaussian_ket(gate):\n \"\"\"Test same state is obtained via fock representation or phase space\n for single mode circuits.\"\"\"\n cutoffs = [70]\n gaussian_state = SqueezedVacuum(-0.1)\n fock_state = State(ket=gaussian_state.ket(cutoffs))\n\n via_fock_space_ket = (fock_state >> gate).ket([10])\n via_phase_space_ket = (gaussian_state >> gate).ket([10])\n phase = np.exp(1j * np.angle(via_fock_space_ket[0]))\n assert np.allclose(via_fock_space_ket, phase * via_phase_space_ket)\n\n\n@given(gate=single_mode_unitary_gate())\ndef test_single_mode_fock_equals_gaussian_ket_dm(gate):\n \"\"\"Test same state is obtained via fock representation or phase space\n for single mode circuits.\"\"\"\n cutoffs = (70,)\n gaussian_state = SqueezedVacuum(-0.1)\n fock_state = State(ket=gaussian_state.ket(cutoffs))\n\n via_fock_space_dm = (fock_state >> gate >> Attenuator(0.1)).dm([10])\n via_phase_space_dm = (gaussian_state >> gate >> Attenuator(0.1)).dm([10])\n assert np.allclose(via_fock_space_dm, via_phase_space_dm, atol=1e-5)\n\n\n@given(gate=two_mode_unitary_gate())\ndef test_two_mode_fock_equals_gaussian(gate):\n \"\"\"Test same state is obtained via fock representation or phase space\n for two modes circuits.\"\"\"\n cutoffs = (20, 20)\n gaussian_state = TMSV(0.1) >> BSgate(np.pi / 2) >> Attenuator(0.5)\n fock_state = State(dm=gaussian_state.dm(cutoffs))\n\n via_fock_space_dm = (fock_state >> gate).dm(cutoffs)\n via_phase_space_dm = (gaussian_state >> gate).dm(cutoffs)\n assert np.allclose(via_fock_space_dm, via_phase_space_dm)\n\n\n@pytest.mark.parametrize(\n \"cutoffs,x,y\",\n [\n [[5, 5], 0.3, 0.5],\n [[5, 5], 0.0, 0.0],\n [[2, 2, 2, 2], [0.1, 0.1], [0.25, -0.2]],\n [[3, 3, 3, 3], [0.0, 0.0], [0.0, 0.0]],\n [[2, 5, 1, 2, 5, 1], [0.1, 5.0, 1.0], [-0.3, 0.1, 0.0]],\n [[3, 3, 3, 3, 3, 3, 3, 3], [0.1, 0.2, 0.3, 0.4], [-0.5, -4, 3.1, 4.2]],\n ],\n)\ndef test_fock_representation_displacement(cutoffs, x, y):\n \"\"\"Tests that DGate returns the correct unitary.\"\"\"\n\n # apply gate\n dgate = Dgate(x, y)\n Ud = dgate.U(cutoffs)\n\n # compare with the standard way of calculating\n # transformation unitaries using the Choi isomorphism\n X, _, d = dgate.XYd(allow_none=False)\n expected_Ud = fock.wigner_to_fock_U(X, d, cutoffs)\n\n assert np.allclose(Ud, expected_Ud, atol=1e-5)\n\n\n@given(x1=medium_float, x2=medium_float, y1=medium_float, y2=medium_float)\ndef test_parallel_displacement(x1, x2, y1, y2):\n \"\"\"Tests that parallel Dgate returns the correct unitary.\"\"\"\n U12 = Dgate([x1, x2], [y1, y2]).U([2, 7, 2, 7])\n U1 = Dgate(x1, y1).U([2, 2])\n U2 = Dgate(x2, y2).U([7, 7])\n assert np.allclose(U12, np.transpose(np.tensordot(U1, U2, [[], []]), [0, 2, 1, 3]))\n\n\ndef test_squeezer_grad_against_finite_differences():\n \"\"\"tests fock squeezer gradient against finite differences\"\"\"\n cutoffs = (5, 5)\n r = math.new_variable(0.5, None, \"r\")\n phi = math.new_variable(0.1, None, \"phi\")\n delta = 1e-6\n dUdr = (Sgate(r + delta, phi).U(cutoffs) - Sgate(r - delta, phi).U(cutoffs)) / (2 * delta)\n dUdphi = (Sgate(r, phi + delta).U(cutoffs) - Sgate(r, phi - delta).U(cutoffs)) / (2 * delta)\n _, (gradr, gradphi) = math.value_and_gradients(\n lambda: fock.squeezer(r, phi, shape=cutoffs), [r, phi]\n )\n assert np.allclose(gradr, 2 * np.real(np.sum(dUdr)))\n assert np.allclose(gradphi, 2 * np.real(np.sum(dUdphi)))\n\n\ndef test_displacement_grad():\n \"\"\"tests fock displacement gradient against finite differences\"\"\"\n cutoffs = [5, 5]\n x = math.new_variable(0.1, None, \"x\")\n y = math.new_variable(0.1, None, \"y\")\n alpha = math.make_complex(x, y).numpy()\n delta = 1e-6\n dUdx = (fock.displacement(x + delta, y, cutoffs) - fock.displacement(x - delta, y, cutoffs)) / (\n 2 * delta\n )\n dUdy = (fock.displacement(x, y + delta, cutoffs) - fock.displacement(x, y - delta, cutoffs)) / (\n 2 * delta\n )\n\n D = fock.displacement(x, y, shape=cutoffs)\n dD_da, dD_dac = strategies.jacobian_displacement(math.asnumpy(D), alpha)\n assert np.allclose(dD_da + dD_dac, dUdx)\n assert np.allclose(1j * (dD_da - dD_dac), dUdy)\n\n\ndef test_fock_representation_displacement_rectangular():\n \"\"\"Tests that DGate returns the correct unitary.\"\"\"\n x, y = 0.3, 0.5\n cutoffs = 5, 10\n # apply gate\n dgate = Dgate(x, y)\n Ud = dgate.U(cutoffs)\n\n # compare with tw implementation\n expected_Ud = displacement(np.sqrt(x * x + y * y), np.arctan2(y, x), 10)[:5, :10]\n\n assert np.allclose(Ud, expected_Ud, atol=1e-5)\n\n\ndef test_fock_representation_displacement_rectangular2():\n \"\"\"Tests that DGate returns the correct unitary.\"\"\"\n x, y = 0.3, 0.5\n cutoffs = 10, 5\n # apply gate\n dgate = Dgate(x, y)\n Ud = dgate.U(cutoffs)\n\n # compare with tw implementation\n expected_Ud = displacement(np.sqrt(x * x + y * y), np.arctan2(y, x), 10)[:10, :5]\n\n assert np.allclose(Ud, expected_Ud, atol=1e-5)\n\n\n@given(r=r, phi=angle)\ndef test_fock_representation_squeezing(r, phi):\n S = Sgate(r=r, phi=phi)\n expected = squeezing(r=r, theta=phi, cutoff=20)\n assert np.allclose(expected, S.U(cutoffs=[20, 20]), atol=1e-5)\n\n\n@given(r1=r, phi1=angle, r2=r, phi2=angle)\ndef test_parallel_squeezing(r1, phi1, r2, phi2):\n \"\"\"Tests that two parallel squeezers return the correct unitary.\"\"\"\n U12 = Sgate([r1, r2], [phi1, phi2]).U([5, 7, 5, 7])\n U1 = Sgate(r1, phi1).U([5, 5])\n U2 = Sgate(r2, phi2).U([7, 7])\n assert np.allclose(U12, np.transpose(np.tensordot(U1, U2, [[], []]), [0, 2, 1, 3]))\n\n\n@given(theta=angle, phi=angle)\ndef test_fock_representation_beamsplitter(theta, phi):\n BS = BSgate(theta=theta, phi=phi)\n expected = beamsplitter(theta=theta, phi=phi, cutoff=10)\n assert np.allclose(expected, BS.U(cutoffs=[10, 10, 10, 10]), atol=1e-5)\n\n\n@given(r=r, phi=angle)\ndef test_fock_representation_two_mode_squeezing(r, phi):\n S2 = S2gate(r=r, phi=phi)\n expected = two_mode_squeezing(r=r, theta=phi, cutoff=10)\n assert np.allclose(expected, S2.U(cutoffs=[10, 10, 10, 10]), atol=1e-5)\n\n\n@given(phi_a=angle, phi_b=angle)\ndef test_fock_representation_mzgate(phi_a, phi_b):\n MZ = MZgate(phi_a=phi_a, phi_b=phi_b, internal=False)\n expected = mzgate(theta=phi_b, phi=phi_a, cutoff=10)\n assert np.allclose(expected, MZ.U(cutoffs=[10, 10, 10, 10]), atol=1e-5)\n\n\n@pytest.mark.parametrize(\n \"cutoffs,angles,modes\",\n [\n [[5, 4, 3], [np.pi, np.pi / 2, np.pi / 4], None],\n [[3, 4], [np.pi / 3, np.pi / 2], [0, 1]],\n [[3], np.pi / 6, [0]],\n ],\n)\ndef test_fock_representation_rgate(cutoffs, angles, modes):\n \"\"\"Tests that DGate returns the correct unitary.\"\"\"\n\n # apply gate\n rgate = Rgate(angles, modes=modes)\n R = rgate.U(cutoffs)\n\n # compare with the standard way of calculating\n # transformation unitaries using the Choi isomorphism\n d = np.zeros(len(cutoffs) * 2)\n expected_R = fock.wigner_to_fock_U(rgate.X_matrix, d, tuple(cutoffs + cutoffs))\n assert np.allclose(R, expected_R, atol=1e-5)\n\n\ndef test_raise_interferometer_error():\n \"\"\"test Interferometer raises an error when both `modes` and `num_modes` don't match\"\"\"\n num_modes = 3\n modes = [0, 2]\n with pytest.raises(ValueError):\n Interferometer(num_modes=num_modes, modes=modes)\n with pytest.raises(ValueError):\n RealInterferometer(num_modes=num_modes, modes=modes)\n modes = [2, 5, 6, 7]\n with pytest.raises(ValueError):\n Interferometer(num_modes=num_modes, modes=modes)\n with pytest.raises(ValueError):\n RealInterferometer(num_modes=num_modes, modes=modes)\n\n\ndef test_choi_cutoffs():\n output = State(dm=Coherent([1.0, 1.0]).dm([5, 8])) >> Attenuator(0.5, modes=[1])\n assert output.cutoffs == [5, 8] # cutoffs are respected by the gate\n\n\ndef test_measure_with_fock():\n \"tests that the autocutoff respects the fock projection cutoff\"\n cov = np.array(\n [\n [1.08341848, 0.26536937, 0.0, 0.0],\n [0.26536937, 1.05564949, 0.0, 0.0],\n [0.0, 0.0, 0.98356475, -0.24724869],\n [0.0, 0.0, -0.24724869, 1.00943755],\n ]\n )\n\n state = State(means=np.zeros(4), cov=cov)\n\n n_detect = 2\n state_out = state << Fock([n_detect], modes=[1])\n assert np.allclose(state_out.ket(), np.array([0.00757899, 0.0]))\n\n\n@given(theta=angle, phi=angle)\ndef test_schwinger_bs_equals_vanilla_bs_for_small_cutoffs(theta, phi):\n \"\"\"Tests that the Schwinger boson BS gate is equivalent to the vanilla BS gate for low cutoffs.\"\"\"\n U_vanilla = BSgate(theta, phi).U([10, 10, 10, 10], method=\"vanilla\")\n U_schwinger = BSgate(theta, phi).U([10, 10, 10, 10], method=\"schwinger\")\n\n assert np.allclose(U_vanilla, U_schwinger, atol=1e-6)\n","repo_name":"sabinthapa100/MrMustard","sub_path":"tests/test_lab/test_gates_fock.py","file_name":"test_gates_fock.py","file_ext":"py","file_size_in_byte":10699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"74618348533","text":"# -*- coding: utf-8 -*-\n\n\nfrom django.shortcuts import redirect\nfrom django.http import HttpResponse\nfrom loginSystem.views import loadLoginPage\nimport json\nfrom .mailserverManager import MailServerManager\nfrom .pluginManager import pluginManager\n\ndef loadEmailHome(request):\n try:\n msM = MailServerManager(request)\n return msM.loadEmailHome()\n except KeyError:\n return redirect(loadLoginPage)\n\ndef createEmailAccount(request):\n try:\n msM = MailServerManager(request)\n return msM.createEmailAccount()\n except KeyError:\n return redirect(loadLoginPage)\n\ndef listEmails(request):\n try:\n msM = MailServerManager(request)\n return msM.listEmails()\n except KeyError:\n return redirect(loadLoginPage)\n\n\ndef fetchEmails(request):\n try:\n msM = MailServerManager(request)\n return msM.fetchEmails()\n except KeyError:\n return redirect(loadLoginPage)\n\ndef submitEmailCreation(request):\n try:\n\n result = pluginManager.preSubmitEmailCreation(request)\n if result != 200:\n return result\n\n msM = MailServerManager(request)\n coreResult = msM.submitEmailCreation()\n\n result = pluginManager.postSubmitEmailCreation(request, coreResult)\n if result != 200:\n return result\n\n return coreResult\n except KeyError:\n return redirect(loadLoginPage)\n\ndef deleteEmailAccount(request):\n try:\n msM = MailServerManager(request)\n return msM.deleteEmailAccount()\n except KeyError:\n return redirect(loadLoginPage)\n\ndef getEmailsForDomain(request):\n try:\n msM = MailServerManager(request)\n return msM.getEmailsForDomain()\n except KeyError as msg:\n data_ret = {'fetchStatus': 0, 'error_message': str(msg)}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\ndef submitEmailDeletion(request):\n try:\n\n result = pluginManager.preSubmitEmailDeletion(request)\n if result != 200:\n return result\n\n msM = MailServerManager(request)\n coreResult = msM.submitEmailDeletion()\n\n result = pluginManager.postSubmitEmailDeletion(request, coreResult)\n if result != 200:\n return result\n\n return coreResult\n except KeyError as msg:\n data_ret = {'deleteEmailStatus': 0, 'error_message': str(msg)}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\ndef fixMailSSL(request):\n try:\n\n msM = MailServerManager(request)\n coreResult = msM.fixMailSSL()\n\n return coreResult\n except KeyError as msg:\n data_ret = {'deleteEmailStatus': 0, 'error_message': str(msg)}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\ndef emailForwarding(request):\n try:\n msM = MailServerManager(request)\n return msM.emailForwarding()\n except KeyError:\n return redirect(loadLoginPage)\n\ndef fetchCurrentForwardings(request):\n try:\n msM = MailServerManager(request)\n return msM.fetchCurrentForwardings()\n except KeyError as msg:\n data_ret = {'fetchStatus': 0, 'error_message': str(msg)}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\ndef submitForwardDeletion(request):\n try:\n\n result = pluginManager.preSubmitForwardDeletion(request)\n if result != 200:\n return result\n\n msM = MailServerManager(request)\n coreResult = msM.submitForwardDeletion()\n\n result = pluginManager.postSubmitForwardDeletion(request, coreResult)\n if result != 200:\n return result\n\n return coreResult\n except KeyError as msg:\n data_ret = {'deleteEmailStatus': 0, 'error_message': str(msg)}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\ndef submitEmailForwardingCreation(request):\n try:\n\n result = pluginManager.preSubmitEmailForwardingCreation(request)\n if result != 200:\n return result\n\n msM = MailServerManager(request)\n coreResult = msM.submitEmailForwardingCreation()\n\n result = pluginManager.postSubmitEmailForwardingCreation(request, coreResult)\n if result != 200:\n return result\n\n return coreResult\n except KeyError as msg:\n data_ret = {'createStatus': 0, 'error_message': str(msg)}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\n#######\n\ndef changeEmailAccountPassword(request):\n try:\n msM = MailServerManager(request)\n return msM.changeEmailAccountPassword()\n except KeyError:\n return redirect(loadLoginPage)\n\ndef submitPasswordChange(request):\n try:\n\n result = pluginManager.preSubmitPasswordChange(request)\n if result != 200:\n return result\n\n msM = MailServerManager(request)\n coreResult = msM.submitPasswordChange()\n\n result = pluginManager.postSubmitPasswordChange(request, coreResult)\n if result != 200:\n return result\n\n return coreResult\n except KeyError as msg:\n data_ret = {'passChangeStatus': 0, 'error_message': str(msg)}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\n#######\n\ndef dkimManager(request):\n try:\n msM = MailServerManager(request)\n return msM.dkimManager()\n except KeyError:\n return redirect(loadLoginPage)\n\ndef fetchDKIMKeys(request):\n try:\n msM = MailServerManager(request)\n return msM.fetchDKIMKeys()\n except KeyError as msg:\n data_ret = {'fetchStatus': 0, 'error_message': str(msg)}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\ndef generateDKIMKeys(request):\n try:\n\n result = pluginManager.preGenerateDKIMKeys(request)\n if result != 200:\n return result\n\n msM = MailServerManager(request)\n coreResult = msM.generateDKIMKeys()\n\n result = pluginManager.postGenerateDKIMKeys(request, coreResult)\n if result != 200:\n return result\n\n return coreResult\n except BaseException as msg:\n data_ret = {'generateStatus': 0, 'error_message': str(msg)}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\ndef installOpenDKIM(request):\n try:\n msM = MailServerManager(request)\n return msM.installOpenDKIM()\n except KeyError:\n final_dic = {'installOpenDKIM': 0, 'error_message': \"Not Logged In, please refresh the page or login again.\"}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\ndef installStatusOpenDKIM(request):\n try:\n msM = MailServerManager()\n return msM.installStatusOpenDKIM()\n except KeyError:\n final_dic = {'abort':1,'installed':0, 'error_message': \"Not Logged In, please refresh the page or login again.\"}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n\n","repo_name":"usmannasir/cyberpanel","sub_path":"mailServer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7017,"program_lang":"python","lang":"en","doc_type":"code","stars":1302,"dataset":"github-code","pt":"21"} +{"seq_id":"1459575567","text":"# Advent of Code 2020 Day 12 Puzzle Rain Risk https://adventofcode.com\n# Created 12/12/2020\n\nimport collections\n\nclass Accumulator:\n # class Accumulator maintains a running total and count of items added\n total = 0\n N = 0\n\n def __init__(self, value):\n self.total = value\n self.N = 0\n\n def ToString(self):\n str(self.total)\n\n def AddValue(self, value):\n self.total += value\n self.N += 1\n\n\nprint('Advent of Code 2020')\nprint('--- Day 12: Rain Risk ---')\nprint()\n\n# Taxicab aka Manhattan distance https://en.wikipedia.org/wiki/Taxicab_geometry\n# sum of absolute dist (p1,p1), (q2,q2) = |p1 - q1| + |p2 - q2|\n\n# Python find letter in list\n# https://stackoverflow.com/questions/26355191/python-check-if-a-letter-is-in-a-list\n\nfn = \"PuzzleInput.txt\"\nnav_instr = list()\nwith open(fn) as f:\n for line in f:\n if (line.strip() != \"\"):\n new_instr = []\n new_instr.append(line[0])\n new_instr.append(int(line[1:].strip()))\n nav_instr.append(new_instr)\n\n#print(nav_instr)\n\n# ship starts at East 0, North 0 and is facing East\n# postion = list of direction ship is facing followed by coords of curr curr_pos (East-West, North-South)\n# the ship starts at the center of a cartesian grid\ncurr_pos = ['E',0,0]\nNE = ['E','N']\nSW = ['W','S']\ncardinal_pts = ['N','S','E','W']\nright_turns = ['E','S','W','N']\nleft_turns = ['E','N','W','S']\nturns = {}\nfor y in right_turns:\n i = right_turns.index(y)\n for x in [90, 180, 270, 360]:\n if i < 3:\n i += 1\n else:\n i = 0\n\n turns['R' + '_' + y + '_' + str(x)] = right_turns[i]\n\nfor y in right_turns:\n i = left_turns.index(y)\n for x in [-90, -180, -270, -360]:\n if i < 3:\n i += 1\n else:\n i = 0\n turns['R' + '_' + y + '_' + str(x)] = left_turns[i]\n\nfor y in left_turns:\n i = left_turns.index(y)\n for x in [90, 180, 270, 360]:\n if i < 3:\n i += 1\n else:\n i = 0\n turns['L' + '_' + y + '_' + str(x)] = left_turns[i]\n\nfor y in left_turns:\n i = right_turns.index(y)\n for x in [-90, -180, -270, -360]:\n if i < 3:\n i += 1\n else:\n i = 0\n turns['L' + '_' + y + '_' + str(x)] = right_turns[i]\n\n#print(turns)\n\n\n# Part 1: following the instructions in the input file where does the ship end up?\n\nfor inst in nav_instr:\n print(inst, ' : ', end='')\n n = inst[0] # nav instruction cardinal directon or 'F' \n d = inst[1] # units / distance\n di = curr_pos[0] # current direction ship is facing\n if (n in ['F']):\n if ( di == 'N'):\n curr_pos[2] += d * 1\n elif (di == 'S'):\n curr_pos[2] += d * -1\n elif ( di == 'E'):\n curr_pos[1] += d * 1\n elif (di == 'W'):\n curr_pos[1] += d * -1\n elif (n in cardinal_pts):\n if ( n == 'N'):\n curr_pos[2] += d * 1\n elif (n == 'S'):\n curr_pos[2] += d * -1\n elif ( n == 'E'):\n curr_pos[1] += d * 1\n elif (n == 'W'):\n curr_pos[1] += d * -1\n elif (n in ['R','L']):\n new_di = turns[n + '_' + di + '_' + str(d)]\n curr_pos[0] = new_di\n else:\n pass\n\n print(\"curr_pos is now \",curr_pos)\n\n\nprint('Manhattan distance from starting curr_pos is ', abs(curr_pos[1]) + abs(curr_pos[2]))\n\n# Part 2 of the Day 12 puzzle:\nprint()\nprint('Part 2: ? ')\n","repo_name":"douggal/advent-of-code-2020","sub_path":"Day12_RainRisk/rain_risk.py","file_name":"rain_risk.py","file_ext":"py","file_size_in_byte":3463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15318054846","text":"ISBN = input(\"please input your ISBN number:\")\nwhile len(ISBN) != 9:\n ISBN = input(\"must be 9 numbers:\")\nnum1 = int(ISBN[0])\nnum2 = int(ISBN[1])\nnum3 = int(ISBN[2])\nnum4 = int(ISBN[3])\nnum5 = int(ISBN[4])\nnum6 = int(ISBN[5])\nnum7 = int(ISBN[6])\nnum8 = int(ISBN[7])\nnum9 = int(ISBN[8])\nmultiplied1 = (num1*10)\nmultiplied2 = (num2*9)\nmultiplied3 = (num3*8)\nmultiplied4 = (num4*7)\nmultiplied5 = (num5*6)\nmultiplied6 = (num6*5)\nmultiplied7 = (num7*4)\nmultiplied8 = (num8*3)\nmultiplied9 = (num9*2)\nallnum = (multiplied1+multiplied2+multiplied3+multiplied4+multiplied5+multiplied6+multiplied7+multiplied8+multiplied9)\nmodulo = allnum%11\nfinalnumber = 11-modulo\n\nif finalnumber == 10:\n print(\"the check digit is X\")\nelif finalnumber == 11:\n print(\"the check digit is 0\")\nelse:\n print(\"the check digit is\", finalnumber)\n","repo_name":"Sanct1fied/Python-Challenges","sub_path":"GC/GC17 .py","file_name":"GC17 .py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36540831363","text":"import numpy as np\nfrom sklearn.decomposition import PCA\nf = open(\"data/heartAttackClean.csv\")\nf.readline() # skip the header\ndata = np.loadtxt(f, delimiter=\",\")\npca = PCA(n_components=data.shape[1])\npca.fit(data)\n\nprint(pca.explained_variance_ratio_)\n\nprint(pca.singular_values_)\n","repo_name":"HenryDykhne/heartAttackPrediction","sub_path":"pca.py","file_name":"pca.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37404832465","text":"import pytest\nfrom love_and_stats import utils\n\nfrom itertools import permutations\nimport statistics\n\n\ndef brute_force_expt_score(mar_list):\n return statistics.mean(\n utils.play_game(item_ranks, mar_list)\n for item_ranks in permutations(range(len(mar_list)))\n )\n\n\n@pytest.mark.parametrize('some_mar_list', list(utils.gen_mar_lists(4)))\ndef test_expt_score(some_mar_list):\n assert (\n float(utils.expt_score(some_mar_list))\n == brute_force_expt_score(some_mar_list)\n )\n","repo_name":"CrepeGoat/love-and-stats","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7905665522","text":"from behave import given, when, then\nimport requests\n\nrequest_headers = {}\nrequest_bodies = {}\nresponse_codes = {}\napi_url = None\n\n\n@given('a pagina de registro da praga')\ndef step_impl_given(context):\n global api_url\n api_url = 'https://smartvit-pest-stg.herokuapp.com/pest'\n print('url :'+api_url)\n\n\n@when('ele registar os campos da praga')\ndef step_impl_when(context):\n request_bodies['POST'] = {\"idVineyard\": \"5fad331b38b2670687db57e2\",\n \"type\": \"cigarras\",\n \"startTime\": \"12-11-2020\"}\n response = requests.post(\n api_url,\n json=request_bodies['POST']\n )\n statuscode = response.status_code\n response_codes['POST'] = statuscode\n\n\n@then('os dados devem passar pelo servico atraves do BFF e armazenar no banco')\ndef step_impl_then(context):\n print('Post rep code ;'+str(response_codes['POST']))\n assert response_codes['POST'] == 200","repo_name":"PI2-viticultura/SmartVit-Pest","sub_path":"app/features/steps/test_pest.py","file_name":"test_pest.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16382606027","text":"#%%\n#%%\n# Problem 1 \n\n#%%\n## Part 1 \n\n### Option 1 \nfor i in range(1,11):\n print(i)\n### Option 2 \nlst = [1,2,3,4,5,6,7,8,9,10]\nfor i in lst:\n print(i)\n\n#%%\n# Part 2:\nnames = [\"John\", \"Mary\", \"Joe\", \"Sue\"]\nfor i in names: \n print(f\"Hello, {i}\")\n#%%\n# Part 3\n## Option 1 \nlst = [1,5,6,21,4]\nsm = 0\nfor i in lst:\n sm += i\n#%%\n# Part 4\nstring = \"python\"\nnew_string = ''\nindex = len(string)\nwhile index:\n index -= 1 # index = index - 1\n new_string += string[index] # new_string = new_string + character\nprint(new_string)\n\n#%%\n# Part 5\nstring = \"banana\"\n\nstring_dict = {} \n\nfor i in string:\n if i in string_dict.keys():\n string_dict[i] += 1 \n else: \n string_dict[i] = 1\n\nfor i in string_dict.keys():\n print(f\"{i}: {string_dict[i]}\")\n\n#%% Part 6\nstudents = {\n \"John\": 90,\n \"Mary\": 80,\n \"Joe\": 30,\n \"Sue\": 75,\n \"Bob\": 20,\n}\n\nfor i in students.keys():\n if students[i] >= 60:\n print(f\"{i} passed with a {students[i]}\")\n else:\n print(f\"{i} failed with a {students[i]}\")\n\n#%% Part 7\nn = 5 \nfor i in range(1,11):\n print(f\"{n} x {i} = {n*i}\")\n\n#%% Problem 2\n#%% Part 1\ni = 0 \nwhile i < 10:\n print(i)\n i += 1\n\n#%% Part 2 \nname = input(\"What is your name? \")\nwhile name != \"quit\":\n print(f\"Hello, {name}\")\n name = input(\"What is your name? \")\n\n#%% Problem 3, Part 1\nnumber = input(\"What is your number? \")\nwhile number != \"quit\":\n if int(number) % 2 == 0:\n print(\"Even\")\n else:\n print(\"Odd\")\n number = input(\"What is your number? \")\n\n#%% Problem 3, Part 2\n\nimport random \n\nrandom.randint(0,100)\n\nlst = []\nfor i in range(10):\n lst.append(random.randint(0,100))\n\n#%%\nsmallest = lst[0]\nlargest = lst[0]\n\nfor i in lst:\n # print(f\"I am checking this number now {i}\")\n if i <= smallest: \n # print(f\"This is the smallest: {i}\")\n smallest = i \n if i >= largest:\n # print(f\"This is the largest: {i}\") \n largest = i \n\n# %% Part 3\nfruits = {\n \"apple\": 10,\n \"banana\": 20,\n \"orange\": 30,\n \"kiwi\": 40,\n \"mango\": 50,\n}\n\ncheck = input(\"What fruit do you want to check? \")\nwhile check != \"quit\":\n if check in fruits.keys():\n print(f\"Yes, we have {check} for ${fruits[check]}\")\n else:\n print(f\"No, we don't have {check}\")\n","repo_name":"dkadyrov/introductiontopython","sub_path":"04_Assignments/Assignment_2/assignment2.py","file_name":"assignment2.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17388795153","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 30 10:43:02 2019\n\n@author: lindsay.hu\n\"\"\"\n\n'''\n【课程3.3】 图表的样式参数\n\nlinestyle、style、color、marker\n \n'''\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n#不打印警告信息\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\n#linestyle参数\n\nplt.plot([i**2 for i in range(100)],linestyle = '-.')\n# '-' solid line style\n# '--' dashed line style\n# '-.' dash-dot line style\n# ':' dotted line style\n\n# marker参数\n\ns = pd.Series(np.random.randn(100).cumsum())\ns.plot(linestyle='--',marker='2')\n# '.' point marker\n# ',' pixel marker\n# 'o' circle marker\n# 'v' triangle_down marker\n# '^' triangle_up marker\n# '<' triangle_left marker\n# '>' triangle_right marker\n# '1' tri_down marker\n# '2' tri_up marker\n# '3' tri_left marker\n# '4' tri_right marker\n# 's' square marker\n# 'p' pentagon marker\n# '*' star marker\n# 'h' hexagon1 marker\n# 'H' hexagon2 marker\n# '+' plus marker\n# 'x' x marker\n# 'D' diamond marker\n# 'd' thin_diamond marker\n# '|' vline marker\n# '_' hline marker\n\n# color参数\n\nplt.hist(np.random.randn(100),color='g',alpha=0.8)\nplt.hist(np.random.randn(100),color='#FFBBB4',alpha=0.8)#也可以自己找颜色参数\n# alpha:0-1,透明度\n# 常用颜色简写:red-r, green-g, black-k, blue-b, yellow-y\n\n \ndf = pd.DataFrame(np.random.randn(1000, 4),columns=list('ABCD'))\ndf = df.cumsum()\ndf.plot(style='--',alpha=0.8,colormap='GnBu')\n# colormap:颜色板,包括:\n# Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r,\n# Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, \n# PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, \n# RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, \n# YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, \n# cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r,\n# gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, \n# gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, hsv_r, inferno, inferno_r, jet, jet_r, magma, magma_r, nipy_spectral, \n# nipy_spectral_r, ocean, ocean_r, pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, seismic, seismic_r, spectral, \n# spectral_r ,spring, spring_r, summer, summer_r, terrain, terrain_r, viridis, viridis_r, winter, winter_r\n\n# 其他参数见“颜色参数.docx”\n\n# style参数,可以包含linestyle,marker,color\n\nts = pd.Series(np.random.randn(1000).cumsum(), index=pd.date_range('1/1/2000', periods=1000))\nts.plot(style='--g.',grid=True)\n# style → 风格字符串,这里包括了linestyle(-),marker(.),color(g)\n# plot()内也有grid参数\n\n#整体风格样式\n\nimport matplotlib.style as psl\n#查看样式表\nprint(plt.style.available)\n\n# 一旦选用样式后,所有图表都会有样式,重启后才能关掉\npsl.use('ggplot')\n\nts = pd.Series(np.random.randn(1000).cumsum(), index=pd.date_range('1/1/2000', periods=1000))\nts.plot(style = '--g.',grid = True,figsize=(10,6))\n\n\n","repo_name":"hulinjuan/Python_data_analysis_action_netease","sub_path":"03 重点工具掌握:数据分析核心技巧/第3章 图表绘制工具:Matplotlib/Part1 基本知识/课程3.3 图表的样式参数.py","file_name":"课程3.3 图表的样式参数.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25057213297","text":"#ウインドウ枠(行と列)の固定\r\n\r\nfrom openpyxl import load_workbook\r\n\r\nwb = load_workbook(\"作業時間.xlsx\")\r\nws = wb.active\r\n\r\nws.freeze_panes = \"E4\"\r\n# A列以外の列で2行目以降のセル番地を指定すると、指定列の前列と前の行までを固定する\r\n\r\nwb.save(\"作業時間_変更後.xlsx\")\r\n","repo_name":"jun-yoshiyoshi/python_for_excel","sub_path":"freeze_column_row.py","file_name":"freeze_column_row.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18726994919","text":"import sys\nimport traceback\nimport copy\nfrom pprint import pprint\nimport pandas as pd\nimport time\n\nfrom falx.table.language import (HOLE, Node, Table, Select, Unite, Filter, Separate, Spread, \n\tGather, GroupSummary, CumSum, Mutate, MutateCustom)\nfrom falx.table import enum_strategies\nfrom falx.table import abstract_eval\nfrom falx.utils.synth_utils import remove_duplicate_columns, check_table_inclusion, align_table_schema, construct_value_dict\nfrom falx.table.provenance_analysis import provenance_analysis\n\nabstract_combinators = {\n\t\"select\": lambda q: Select(q, cols=HOLE),\n\t\"unite\": lambda q: Unite(q, col1=HOLE, col2=HOLE),\n\t\"filter\": lambda q: Filter(q, col_index=HOLE, op=HOLE, const=HOLE),\n\t\"separate\": lambda q: Separate(q, col_index=HOLE),\n\t\"spread\": lambda q: Spread(q, key=HOLE, val=HOLE),\n\t\"gather\": lambda q: Gather(q, value_columns=HOLE),\n\t\"group_sum\": lambda q: GroupSummary(q, group_cols=HOLE, aggr_col=HOLE, aggr_func=HOLE),\n\t\"cumsum\": lambda q: CumSum(q, target=HOLE),\n\t\"mutate\": lambda q: Mutate(q, col1=HOLE, op=HOLE, col2=HOLE),\n\t\"mutate_custom\": lambda q: MutateCustom(q, col=HOLE, op=HOLE, const=HOLE), \n}\n\ndef update_tree_value(node, path, new_val):\n\t\"\"\"from a given ast node, locate the refence to the arg,\n\t and update the value\"\"\"\n\tfor k in path:\n\t\tnode = node[\"children\"][k]\n\tnode[\"value\"] = new_val\n\ndef get_node(node, path):\n\tfor k in path:\n\t\tnode = node[\"children\"][k]\n\treturn node\n\nclass Synthesizer(object):\n\n\tdef __init__(self, config=None):\n\t\tif config is None:\n\t\t\tself.config = {\n\t\t\t\t\"operators\": [\"select\", \"unite\", \"filter\", \"separate\", \"spread\", \n\t\t\t\t\t\"gather\", \"group_sum\", \"cumsum\", \"mutate\", \"mutate_custom\"],\n\t\t\t\t\"filer_op\": [\">\", \"<\", \"==\"],\n\t\t\t\t\"constants\": [],\n\t\t\t\t\"aggr_func\": [\"mean\", \"sum\", \"count\"],\n\t\t\t\t\"mutate_op\": [\"+\", \"-\"],\n\t\t\t\t\"gather_max_val_list_size\": 3,\n\t\t\t\t\"gather_max_key_list_size\": 3,\n\t\t\t\t\"consider_non_consecutive_gather_keys\": False,\n\t\t\t\t\"allow_comp_without_new_val\": False\n\t\t\t}\n\t\telse:\n\t\t\tself.config = config\n\n\tdef enum_sketches(self, inputs, output, size):\n\t\t\"\"\"enumerate program sketches up to the given size\"\"\"\n\n\t\t# check if output contains a new value \n\t\t# (this decides if we should use ops that generates new vals)\n\t\t\n\t\tinp_val_set = set([v for t in inputs for r in t for k, v in r.items()] + [k for t in inputs for k in t[0]])\n\t\tout_val_set = set([v for r in output for k, v in r.items()])\n\t\tnew_vals = out_val_set - inp_val_set\n\t\t\n\t\t#if any([len(t[0]) < 4 for t in inputs]):\n\t\t\t# always consider new value operators for small tables (#column < 4)\n\t\t#\tcontain_new_val = True\n\n\t\t# check if there are seperators in column names\n\t\tsep_in_col_names = [key for t in inputs for key in t[0] if ('-' in key or '_' in key or '/' in key)]\n\t\tsep_in_content = [v for t in inputs for r in t for k, v in r.items() if (isinstance(v, str) and ('-' in v or '_' in v or '/' in v))]\n\t\thas_sep = (len(sep_in_col_names) > 0) or (len(sep_in_content) > 0)\n\n\t\tcandidates = {}\n\t\tfor level in range(0, size + 1):\n\t\t\tcandidates[level] = []\n\t\t\tif level == 0:\n\t\t\t\tcandidates[level] += [Table(data_id=i) for i in range(len(inputs))]\n\t\t\telse:\n\t\t\t\tfor p in candidates[level - 1]:\n\t\t\t\t\tfor op in abstract_combinators:\n\t\t\t\t\t\t#ignore operators that are not set\n\t\t\t\t\t\tif op not in self.config[\"operators\"]:\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tq = abstract_combinators[op](copy.copy(p))\n\t\t\t\t\t\tcandidates[level].append(q)\n\n\t\tfor level in range(0, size + 1):\n\t\t\tcandidates[level] = [q for q in candidates[level] \n\t\t\t\t\t\t\t\tif not enum_strategies.disable_sketch(\n\t\t\t\t\t\t\t\t\tq, new_vals, has_sep, self.config[\"allow_comp_without_new_val\"])]\n\n\n\t\treturn candidates\n\n\tdef pick_vars(self, ast, inputs):\n\t\t\"\"\"list paths to all holes in the given ast\"\"\"\n\t\tdef get_paths_to_all_holes(node):\n\t\t\tresults = []\n\t\t\tfor i, child in enumerate(node[\"children\"]):\n\t\t\t\tif child[\"type\"] == \"node\":\n\t\t\t\t\t# try to find a variable to infer\n\t\t\t\t\tpaths = get_paths_to_all_holes(child)\n\t\t\t\t\tfor path in paths:\n\t\t\t\t\t\tresults.append([i] + path)\n\t\t\t\telif child[\"value\"] == HOLE:\n\t\t\t\t\t# we find a variable to infer\n\t\t\t\t\tresults.append([i])\n\t\t\treturn results\n\t\treturn get_paths_to_all_holes(ast)\n\n\tdef infer_domain(self, ast, var_path, inputs):\n\t\tnode = Node.load_from_dict(get_node(ast, var_path[:-1]))\n\t\treturn node.infer_domain(arg_id=var_path[-1], inputs=inputs, config=self.config)\n\n\tdef instantiate(self, ast, var_path, inputs):\n\t\t\"\"\"instantiate one hole in the program sketch\"\"\"\n\t\tdomain = self.infer_domain(ast, var_path, inputs)\n\t\tcandidates = []\n\t\tfor val in domain:\n\t\t\tnew_ast = copy.deepcopy(ast)\n\t\t\tupdate_tree_value(new_ast, var_path, val)\n\t\t\tcandidates.append(new_ast)\n\t\treturn candidates\n\n\tdef instantiate_one_level(self, ast, inputs):\n\t\t\"\"\"generate program instantitated from the most recent level\n\t\t\ti.e., given an abstract program, it will enumerate all possible abstract programs that concretize\n\t\t\"\"\"\n\t\tvar_paths = self.pick_vars(ast, inputs)\n\n\t\t# there is no variables to instantiate\n\t\tif var_paths == []:\n\t\t\treturn [], []\n\n\t\t# find all variables at the innermost level\n\t\tinnermost_level = max([len(p) for p in var_paths])\n\t\ttarget_vars = [p for p in var_paths if len(p) == innermost_level]\n\n\t\trecent_candidates = [ast]\n\t\tfor var_path in target_vars:\n\t\t\ttemp_candidates = []\n\t\t\tfor partial_prog in recent_candidates:\n\t\t\t\ttemp_candidates += self.instantiate(partial_prog, var_path, inputs)\n\t\t\trecent_candidates = temp_candidates\n\n\t\t# for c in recent_candidates:\n\t\t# \tnd = Node.load_from_dict(c)\n\t\t# \tprint(f\"{' | '}{nd.stmt_string()}\")\n\t\t\n\t\t# this show how do we trace to the most recent program level\n\t\tconcrete_program_level = innermost_level - 1\n\n\t\treturn recent_candidates, concrete_program_level\n\n\tdef iteratively_instantiate_and_print(self, p, inputs, level, print_programs=False):\n\t\t\"\"\"iteratively instantiate a program (for the purpose of debugging)\"\"\"\n\t\tif print_programs:\n\t\t\tprint(f\"{' '.join(['' for _ in range(level)])}{p.stmt_string()}\")\n\t\tresults = []\n\t\tif p.is_abstract():\n\t\t\tast = p.to_dict()\n\t\t\tvar_path = self.pick_vars(ast, inputs)[0]\n\t\t\t#domain = self.infer_domain(ast, path, inputs)\n\t\t\tcandidates = self.instantiate(ast, var_path, inputs)\n\t\t\tfor c in candidates:\n\t\t\t\tnd = Node.load_from_dict(c)\n\t\t\t\tresults += self.iteratively_instantiate_and_print(nd, inputs, level + 1, print_programs)\n\t\t\treturn results\n\t\telse:\n\t\t\treturn [p]\n\n\tdef iteratively_instantiate_with_premises_check(self, p, inputs, premise_chains, trimmed_inputs, time_limit_sec=None):\n\t\t\"\"\"iteratively instantiate abstract programs w/ promise check \n\t\tArgs:\n\t\t\tp: partial program\n\t\t\tinputs: input tables\n\t\t\tpremise_chains: backward analysis chains\n\t\t\ttrimmed inputs: input obtained from provenance analysis used to perform checks\n\t\t\ttime_limit_sec: remaining time limit\n\t\treturns:\n\t\t\ta list of candidate programs\n\t\t\"\"\"\n\n\t\tdef instantiate_with_premises_check(p, inputs, premise_chains, trimmed_inputs):\n\t\t\t\"\"\"instantiate programs and then check each one of them against the premise \"\"\"\n\t\t\tresults = []\n\t\t\tif p.is_abstract():\n\t\t\t\tprint(p.stmt_string())\n\t\t\t\tast = p.to_dict()\n\n\t\t\t\t\n\t\t\t\tnext_level_programs, level = self.instantiate_one_level(ast, inputs)\n\t\t\t\t#next_level_programs, level = self.instantiate_one_level(ast, trimmed_inputs)\n\n\t\t\t\tfor _ast in next_level_programs:\n\n\t\t\t\t\t# force terminate if the remaining time is running out\n\t\t\t\t\tif time_limit_sec is not None and time.time() - start_time > time_limit_sec:\n\t\t\t\t\t\treturn results\n\n\t\t\t\t\tpremises_at_level = [[pm for pm in premise_chain if len(pm[1]) == level][0] for premise_chain in premise_chains]\n\n\t\t\t\t\tsubquery_res = None # cache subquery result to avoid re-computation overhead\n\t\t\t\t\tfor premise, subquery_path in premises_at_level:\n\n\t\t\t\t\t\tif subquery_res is None:\n\t\t\t\t\t\t\t# check if the subquery result contains the premise\n\t\t\t\t\t\t\tsubquery_node = get_node(_ast, subquery_path)\n\t\t\t\t\t\t\tprint(\" {}\".format(Node.load_from_dict(subquery_node).stmt_string()))\n\n\t\t\t\t\t\t\t#subquery_res = Node.load_from_dict(subquery_node).eval(inputs)\n\t\t\t\t\t\t\tsubquery_res = Node.load_from_dict(subquery_node).eval(trimmed_inputs)\n\n\t\t\t\t\t\t# an optimization: compute the dictionary represented table here to reduce time spent later on to check table inclusion.\n\t\t\t\t\t\tsubquery_res_table = subquery_res.to_dict(orient=\"records\")\n\t\t\t\t\t\tsubquery_res_dict = {}\n\t\t\t\t\t\tfor k2 in subquery_res_table[0].keys():\n\t\t\t\t\t\t\tsubquery_res_dict[k2] = construct_value_dict([r[k2] for r in subquery_res_table if k2 in r])\n\n\t\t\t\t\t\t#print(subquery_res)\n\t\t\t\t\t\tif check_table_inclusion(premise.to_dict(orient=\"records\"), subquery_res_table, subquery_res_dict):\n\n\t\t\t\t\t\t\t# # debug\n\t\t\t\t\t\t\t# p = Node.load_from_dict(_ast)\n\t\t\t\t\t\t\t# if not p.is_abstract():\n\t\t\t\t\t\t\t# \tprint(f\"{' - '}{p.stmt_string()}\")\n\t\t\t\t\t\t\t# \tprint(subquery_res)\n\t\t\t\t\t\t\t# \tprint(premise)\n\t\t\t\t\t\t\t# \tprint( check_table_inclusion(premise.to_dict(orient=\"records\"), subquery_res.to_dict(orient=\"records\")))\n\n\t\t\t\t\t\t\tresults.append(Node.load_from_dict(_ast))\n\t\t\t\t\t\t\tbreak\n\n\t\t\t\treturn results\n\t\t\telse:\n\t\t\t\treturn []\n\n\t\tprint(\"time limit: {}\".format(time_limit_sec))\n\n\t\tresults = []\n\t\tif p.is_abstract():\n\t\t\t\n\t\t\tif time_limit_sec < 0:\n\t\t\t\treturn []\n\t\t\tstart_time = time.time()\n\n\t\t\tcandidates = instantiate_with_premises_check(p, inputs, premise_chains, trimmed_inputs)\n\t\t\tfor _p in candidates:\n\t\t\t\t# if time_limit_sec is not None and time.time() - start_time > time_limit_sec:\n\t\t\t\t# \treturn results\n\t\t\t\tremaining_time_limit = time_limit_sec - (time.time() - start_time) if time_limit_sec is not None else None\n\t\t\t\tresults += self.iteratively_instantiate_with_premises_check(_p, inputs, premise_chains, trimmed_inputs, remaining_time_limit)\n\t\t\treturn results\n\t\telse:\n\t\t\t# handling concrete programs won't take long, allow them to proceed\n\t\t\treturn [p]\n\n\tdef enumerative_all_programs(self, inputs, output, max_prog_size, print_progs=True):\n\t\t\"\"\"Given inputs and output, enumerate all programs in the search space until \n\t\t\tfind a solution p such that output ⊆ subseteq p(inputs) \"\"\"\n\t\tall_sketches = self.enum_sketches(inputs, output, size=max_prog_size)\n\t\tconcrete_programs = []\n\t\tfor level, sketches in all_sketches.items():\n\t\t\tfor s in sketches:\n\t\t\t\tconcrete_programs += self.iteratively_instantiate_and_print(s, inputs, 1, True)\n\t\t\n\t\tfor p in concrete_programs:\n\t\t\ttry:\n\t\t\t\tt = p.eval(inputs)\n\t\t\t\tif (print_progs):\n\t\t\t\t\tprint(p.stmt_string())\n\t\t\t\t\tprint(t)\n\t\t\texcept Exception as e:\n\t\t\t\tprint(f\"[error] {sys.exc_info()[0]} {e}\")\n\t\t\t\ttb = sys.exc_info()[2]\n\t\t\t\ttb_info = ''.join(traceback.format_tb(tb))\n\t\t\t\tprint(tb_info)\n\t\tprint(\"----\")\n\t\tprint(f\"number of programs: {len(concrete_programs)}\")\n\n\tdef enumerative_search(self, inputs, output, max_prog_size):\n\t\t\"\"\"Given inputs and output, enumerate all programs in the search space until \n\t\t\tfind a solution p such that output ⊆ subseteq p(inputs) \"\"\"\n\t\tall_sketches = self.enum_sketches(inputs, output, size=max_prog_size)\n\t\tcandidates = []\n\t\tfor level, sketches in all_sketches.items():\n\t\t\tfor s in sketches:\n\t\t\t\tconcrete_programs = self.iteratively_instantiate_and_print(s, inputs, 1)\n\t\t\t\tfor p in concrete_programs:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tt = p.eval(inputs)\n\t\t\t\t\t\tif align_table_schema(output, t.to_dict(orient=\"records\")) != None:\n\t\t\t\t\t\t\tprint(p.stmt_string())\n\t\t\t\t\t\t\tprint(t)\n\t\t\t\t\t\t\tcandidates.append(p)\n\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\tprint(f\"[error] {sys.exc_info()[0]} {e}\")\n\t\t\t\t\t\ttb = sys.exc_info()[2]\n\t\t\t\t\t\ttb_info = ''.join(traceback.format_tb(tb))\n\t\t\t\t\t\tprint(tb_info)\n\t\tprint(\"----\")\n\t\tprint(f\"number of programs: {len(candidates)}\")\n\t\treturn candidates\n\n\tdef enumerative_synthesis(self, \n\t\t\tinputs, output, max_prog_size, \n\t\t\ttime_limit_sec=None, \n\t\t\tsolution_sketch_limit=None, \n\t\t\tsolution_limit=None,\n\t\t\tdisable_provenance_analysis=False):\n\t\t\"\"\"Given inputs and output, enumerate all programs with premise check until \n\t\t\tfind a solution p such that output ⊆ subseteq p(inputs) \"\"\"\n\n\t\tstart_time = time.time()\n\n\t\tall_sketches = self.enum_sketches(inputs, output, size=max_prog_size)\n\t\t\n\t\tcandidates = []\n\t\tsolution_sketches = set() # records sketches of candidate programs\n\n\t\tfor level, sketches in all_sketches.items():\n\t\t\tfor s in sketches:\n\t\t\t\tast = s.to_dict()\n\t\t\t\tout_df = pd.DataFrame.from_dict(output)\n\n\t\t\t\tif disable_provenance_analysis:\n\t\t\t\t\t# disable provenance analysis\n\t\t\t\t\ttrimmed_inputs = inputs\n\t\t\t\telse:\n\t\t\t\t\tpred, trimmed_inputs = provenance_analysis(ast, out_df, inputs)\n\n\t\t\t\t\t# print(pred.print_str())\n\t\t\t\t\t# print(pd.DataFrame(trimmed_inputs[0]))\n\n\t\t\t\tif len(trimmed_inputs[0]) == 0:\n\t\t\t\t\tcontinue\n\n\t\t\t\tout_df = remove_duplicate_columns(out_df)\n\t\t\t\t# all premise chains for the given ast\n\t\t\t\tpremise_chains = abstract_eval.backward_eval(ast, out_df)\n\n\t\t\t\tremaining_time_limit = time_limit_sec - (time.time() - start_time) if time_limit_sec is not None else None\n\t\t\t\tprograms = self.iteratively_instantiate_with_premises_check(s, inputs, premise_chains, trimmed_inputs, remaining_time_limit)\n\t\t\t\t\n\t\t\t\tfor p in programs:\n\t\t\t\t\t# check table consistensy\n\t\t\t\t\tt = p.eval(inputs)\n\t\t\t\t\talignment_result = align_table_schema(output, t.to_dict(orient=\"records\"))\n\t\t\t\t\tif alignment_result != None:\n\t\t\t\t\t\tcandidates.append(p)\n\t\t\t\t\t\tsolution_sketches.add(s.stmt_string())\n\t\t\t\t\n\t\t\t\t\tif ((solution_sketch_limit is not None and len(solution_sketches) >= solution_sketch_limit) or \n\t\t\t\t\t\t(solution_limit is not None and len(candidates) >= solution_limit)):\n\t\t\t\t\t\treturn candidates\n\t\t\t\t\n\t\t\t\t# early return if the termination condition is met\n\t\t\t\t# TODO: time_limit may be exceeded if the synthesizer is stuck on iteratively instantiation\n\t\t\t\tif time_limit_sec is not None and time.time() - start_time > time_limit_sec:\n\t\t\t\t\treturn candidates\n\n\t\treturn candidates\n","repo_name":"Mestway/falx","sub_path":"falx/table/synthesizer.py","file_name":"synthesizer.py","file_ext":"py","file_size_in_byte":13499,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"21"} +{"seq_id":"35663350585","text":"def find(data, k, n, m):\n data.insert(0,0) #출발점 - 맨앞에 삽입\n data.append(n) #종점 - 맨뒤에 추가\n last = 0 #마지막 충전기\n cnt = 0 #충전횟수\n for i in range(1, m + 2):\n if data[i] - data[i-1] > k : #충전기 사이가 k보다 멀때\n return 0\n if data[i] > last + k: #i충전기까지 갈 수 없으면\n last = data[i-1]\n cnt += 1\n return cnt\n\nimport sys\nsys.stdin = open(\"전기버스_input.txt\")\n\nT = int(input())\nfor tc in range(T):\n # K : 한번 충전으로 이동할 수 있는 정류장 수\n # N : 정류장 수\n # M : 충전기 설치된 정류장 번호\n K, N, M = map(int, input().split()) #1 ≤ K, N, M ≤ 100\n data = list(map(int, input().split()))\n print(\"#{} {}\".format(tc+1, find(data, K, N, M)))","repo_name":"gogumasitda/TIL","sub_path":"algorithm/01.15/day2/전기버스.py","file_name":"전기버스.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"ko","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"13913573567","text":"import torch\nimport math\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom models import TextCNN\nfrom configs import get_args\nfrom utils import data_selfattention\nfrom torch.nn import CrossEntropyLoss\nfrom transformers import Trainer\n\n\ndef cl_cal_loss(vec1,vec2):\n loss_for_cl=CrossEntropyLoss(ignore_index=-100)\n labels=torch.arange(0,vec1.shape[0],device='cuda')\n vec1=F.normalize(vec1, p=2, dim=1)#归一化为单位向量[bs,hiden_len]\n vec2=F.normalize(vec2, p=2, dim=1)#[bs,hiden_len]\n sims=vec1.matmul(vec2.T)*20\n loss=loss_for_cl(sims,labels)#拉近二者距离\n return loss\n\n\ndef cos_similarity(p, z, version='simplified'): # negative cosine similarity\n if version == 'original':\n z = z.detach() # stop gradient\n p = F.normalize(p, dim=1) # l2-normalize \n z = F.normalize(z, dim=1) # l2-normalize \n return -(p*z).sum(dim=1).mean()\n\n elif version == 'simplified':# same thing, much faster. Scroll down, speed test in __main__\n return - F.cosine_similarity(p, z.detach(), dim=-1).mean()\n else:\n raise Exception\n\n\n\nclass projection_MLP(nn.Module):\n def __init__(self, in_dim, hidden_dim, out_dim=4096):\n super().__init__()\n self.layer1 = nn.Sequential(\n nn.Linear(in_dim, hidden_dim),\n nn.BatchNorm1d(hidden_dim),\n nn.ReLU(inplace=True)\n )\n self.layer2 = nn.Sequential(\n nn.Linear(hidden_dim, hidden_dim),\n nn.BatchNorm1d(hidden_dim),\n nn.ReLU(inplace=True)\n )\n self.layer3 = nn.Sequential(\n nn.Linear(hidden_dim, out_dim),\n nn.BatchNorm1d(out_dim)\n )\n self.num_layers = 3\n def set_layers(self, num_layers):\n self.num_layers = num_layers\n\n def forward(self, x):\n if self.num_layers == 3:\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n elif self.num_layers == 2:\n x = self.layer1(x)\n x = self.layer3(x)\n else:\n raise Exception\n return x \n\n\nclass prediction_MLP(nn.Module):\n def __init__(self, in_dim=4096, hidden_dim=1024, out_dim=4096): # bottleneck structure\n super().__init__()\n self.layer1 = nn.Sequential(\n nn.Linear(in_dim, hidden_dim),\n nn.BatchNorm1d(hidden_dim),\n nn.ReLU(inplace=True)\n )\n self.layer2 = nn.Linear(hidden_dim, out_dim)\n def forward(self, x):\n x = self.layer1(x)\n x = self.layer2(x)\n return x\n\nclass Plus_Proj_layer(nn.Module):# 继承类nn.Module\n def __init__(self, backbone):\n super().__init__()\n model_opt = TextCNN.ModelConfig()\n args=get_args()\n self.backbone = backbone #\n\n if args.backbone=='textcnn':\n self.projector = projection_MLP(model_opt.model_dim,4096)\n \n else:\n self.projector = projection_MLP(768)\n self.encoder = nn.Sequential( # f encoder\n self.backbone,\n self.projector\n )\n self.predictor = prediction_MLP()\n \n def forward(self, x1, x2, mask):\n x1=data_selfattention(x1,x1,x1,mask)#不加attention为42.69\n x2=data_selfattention(x2,x2,x2,mask)\n z1,z2=self.encoder(x1),self.encoder(x2)\n p1,p2=self.predictor(z1),self.predictor(z2)\n return p1,z2,p2,z1\n\n\n\n\n\n\nif __name__ == \"__main__\":\n\n\n\n model = Plus_Proj_layer()\n x1 = torch.randn((2, 3, 224, 224))\n x2 = torch.randn_like(x1)#创建像x1的大小的张量\n\n model.forward(x1, x2).backward()\n print(\"forward backwork check\")\n\n z1 = torch.randn((200, 2560))\n z2 = torch.randn_like(z1)\n import time\n tic = time.time()\n print(cos_similarity(z1, z2, version='original'))\n toc = time.time()\n print(toc - tic)\n tic = time.time()\n print(cos_similarity(z1, z2, version='simplified'))\n toc = time.time()\n print(toc - tic)\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"qianandfei/GCSRL-Grouped-Contrastive-Self-supervised-Representation-Learning-of-Sentence","sub_path":"models/plus_proj_layer.py","file_name":"plus_proj_layer.py","file_ext":"py","file_size_in_byte":3976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18596863472","text":"\"\"\"\nRoutines for working with Faraday spectra\n\nFunctions\n---------\ncreateFaraday(nu, polarization, phi)\n Converts a polarization spectrum into a Faraday spectrum.\n\"\"\"\n\nimport numpy as np\nfrom .units import c\n\ndef createFaraday(\n nu:np.ndarray,\n polarization:np.ndarray,\n phi:np.ndarray,\n) -> np.ndarray:\n \"\"\"\n Converts a polarization spectrum into a normalized Faraday spectrum.\n\n Parameters\n ----------\n nu : np.ndarray\n The frequency coverage\n\n polarization : np.ndarray\n The complex polarization array\n\n phi : np.ndarray\n The range of Faraday depths\n\n Returns\n -------\n faraday : np.ndarray\n The Faraday spectrum normalized to have a peak amplitude of 1. \n Aligned with the provided phi values.\n\n Examples\n -------- \n import matplotlib.pyplot as plt\n import numpy as np\n from possum.coverage import ASKAP12\n from possum.polarization import createPolarization, addPolarizationNoise\n from possum.faraday import createFaraday\n\n nu = ASKAP12()\n p = createPolarization(nu=nu, chi=0, depth=20, amplitude=1)\n p = addPolarizationNoise(polarization=p, sigma=0.1)\n\n phi = np.linspace(-50,50,100)\n f = createFaraday(nu=nu, polarization=p, phi=phi)\n\n fig, ax = plt.subplots()\n ax.plot(phi, abs(f), label='abs')\n ax.plot(phi, f.real, label='real')\n ax.plot(phi, f.imag, label='imag')\n ax.legend(loc='lower right', frameon=False)\n ax.set_xlabel(r'$\\phi$ (rad m$^{2}$)')\n ax.set_ylabel(r'$P_{\\nu}$ (Jy/beam)')\n fig.show()\n \"\"\"\n\n # ===========================================\n # Variables\n # ===========================================\n faraday = np.zeros(len(phi)).astype('complex')\n\n # ===========================================\n # Create Faraday spectrum\n # ===========================================\n lamSq = (c/nu)**2\n delta = lamSq - np.mean(lamSq)\n\n for i, p in enumerate(phi):\n far = np.exp(-2j * p * delta)\n far = np.sum(polarization * far)\n faraday[i] = far\n\n # ===========================================\n # Normalize spectrum and return\n # ===========================================\n return faraday / np.abs(faraday).max()","repo_name":"bbergerud/faraday_complexity","sub_path":"possum/faraday.py","file_name":"faraday.py","file_ext":"py","file_size_in_byte":2229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11944012053","text":"from __future__ import absolute_import, division, print_function\nimport torch\n\n\nclass CascorUtil:\n \"\"\"Class that holds the utilities for training and evaluating Cascor\"\"\"\n\n def __init__(self):\n pass\n\n @staticmethod\n def quickprop_update(weights, nunits, ncandidates, noutputs, deltas, slopes, prevs, epsilon, decay, mu,\n shrink_factor, is_input):\n \"\"\"Perform quickprop as indicated in the original paper by Fahlman\"\"\"\n n_columns = nunits + 1 if is_input else nunits\n n_rows = ncandidates if is_input else noutputs\n next_step = torch.zeros((n_rows, n_columns))\n w = weights[:n_rows, :n_columns]\n d = deltas[:n_rows, :n_columns]\n s = slopes[:n_rows, :n_columns] + (w * decay)\n p = prevs[:n_rows, :n_columns]\n t = torch.where(p == s, torch.ones(p.shape), p - s)\n next_step -= torch.where(d * s <= 0, epsilon * s, torch.zeros(next_step.shape))\n mask1 = (((d < 0) & (s >= shrink_factor * p)) | ((d > 0) & (s <= shrink_factor * p))).type(torch.FloatTensor)\n mask2 = (((d < 0) & (s < shrink_factor * p)) | ((d > 0) & (s > shrink_factor * p))).type(torch.FloatTensor)\n next_step += mu * d * mask1\n next_step += (d * s / t) * mask2\n\n deltas[:n_rows, :n_columns] = next_step\n weights[:n_rows, :n_columns] += next_step\n prevs[:n_rows, :n_columns] = slopes[:n_rows, :n_columns] + (w * decay)\n slopes[:n_rows, :n_columns] *= 0.0\n\n\nclass CascorStats:\n \"\"\"Class that stores data that is required to persist over multiple stages in the training and evaluation process\"\"\"\n def __init__(self, epoch=0):\n self.epoch = epoch\n\n\n","repo_name":"ianjchiu/Cascor","sub_path":"Cascor-PyTorch/CascorUtil.py","file_name":"CascorUtil.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"3981348258","text":"from django.contrib import admin\n\nfrom .models import Address, Coupon, Item, Order, OrderItem, Payment, Refund, UserProfile\n\n\"\"\"\n This function updates the order model in django custum admin just\n like custom select and delete row in django admin\n\"\"\"\n\n\ndef make_refund_accepted(modeladmin, request, queryset):\n queryset.update(refund_requested=False, refund_granted=True)\n\n\n# Default name is just the name of the function\nmake_refund_accepted.short_description = 'Update orders to refund granted'\n\n\n# Customizing admin panel\nclass OrderAdmin(admin.ModelAdmin):\n # Displays the list of all the fields mentioned in django admin panel row\n list_display = [\n 'user', 'ordered', 'being_delivered', 'received', 'refund_requested',\n 'refund_granted', 'shipping_address', 'billing_address',\n 'payment', 'coupon'\n ]\n\n # displays all the foreign key, on-to-one fields, ... with links\n list_display_links = [\n 'user', 'shipping_address', 'billing_address', 'payment', 'coupon'\n ]\n\n # all the list we can filter by. in the right corner in django admin panel\n list_filter = [\n 'ordered', 'being_delivered', 'received', 'refund_requested',\n 'refund_granted'\n ]\n\n # searchable fields in the admin panel on top\n search_fields = [\n 'user__username', 'ref_code'\n ]\n\n # allows to update order just like custom delete method in admin panel\n actions = [make_refund_accepted]\n\n\nclass AddressAdmin(admin.ModelAdmin):\n list_display = [\n 'user', 'street_address', 'apartment_address', 'country', 'zip',\n 'address_type', 'default'\n ]\n list_filter = ['default', 'address_type']\n\n # user__username looks for field username in user model\n search_fields = [\n 'user__username', 'street_address', 'apartment_address',\n 'zip', 'country'\n ]\n\n\nadmin.site.register(Item)\nadmin.site.register(OrderItem)\nadmin.site.register(Order, OrderAdmin)\nadmin.site.register(Address, AddressAdmin)\nadmin.site.register(Payment)\nadmin.site.register(Coupon)\nadmin.site.register(Refund)\nadmin.site.register(UserProfile)\n","repo_name":"afroz102/django_e-com","sub_path":"core/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10017250962","text":"from scipy.spatial.distance import cdist\nimport numpy as np\n\n\ndef mds(X, no_dims):\n \"\"\"\n This function performs MDS embedding.\n\n Parameters are:\n\n 'X' - N by D matrix. Each row in X represents an observation.\n 'no_dims' - A positive integer specifying the number of dimension of the representation Y.\n\n \"\"\"\n n = X.shape[0]\n D = cdist(X, X) ** 2\n sumd = np.mean(D, axis=1)\n sumD = np.mean(sumd)\n B = np.zeros((n, n))\n for i in range(n):\n for j in range(i+1, n):\n B[i][j] = -0.5 * (D[i][j] - sumd[i] - sumd[j] + sumD)\n B[j][i] = B[i][j]\n value, U = np.linalg.eig(B)\n embedX = U[:, :no_dims] @ np.diag(np.sqrt(np.abs(value[:no_dims])))\n return embedX\n","repo_name":"ZPGuiGroupWhu/scml","sub_path":"scml_py/mds.py","file_name":"mds.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"70818501172","text":"from numpy.core.fromnumeric import size\nimport pandas as pd\nimport numpy as np\nfrom pandas.core.frame import DataFrame\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom scipy import sparse\nimport sys, json\nimport traceback\n\n\nclass Recommendation_System(object):\n def __init__(self, data, userLimit):\n self.data = data\n self.userLimit = userLimit # number of user neighbours\n self.normalized_data = self.data.copy()\n\n def normalize_data(self):\n users = np.unique(self.data[:, 0]).astype(\n np.int32\n ) # take the unique users column\n items = np.unique(self.data[:, 1]).astype(np.int32)\n\n for user in users:\n this_user_index = np.where(\n self.data[:, 0] == user\n ) # get index of this user\n this_user_ratings = self.data[\n this_user_index, 2\n ] # take rating of this user\n mean_rating = np.mean(this_user_ratings)\n self.normalized_data[this_user_index, 2] -= mean_rating\n\n self.normalized_matrix = sparse.coo_matrix(\n (\n self.normalized_data[:, 2],\n (self.normalized_data[:, 1], self.normalized_data[:, 0]),\n ),\n (int(np.max(items)) + 1, int(np.max(users)) + 1),\n )\n self.normalized_matrix = self.normalized_matrix.tocsr()\n\n def generate_user_similarity_matrix(self):\n self.similar_user = cosine_similarity(\n self.normalized_matrix.T, self.normalized_matrix.T\n )\n\n def predict(self, user, item):\n index_user_rated_this_item = np.where(self.data[:, 1] == item)[\n 0\n ] # get rated user index to find users\n\n all_users_rated_this_item = (self.data[index_user_rated_this_item, 0]).astype(\n np.int32\n ) # get rated users\n\n if user >= len(self.similar_user):\n return np.NaN\n else:\n rated_user_similarity = self.similar_user[\n user, all_users_rated_this_item\n ] # get users similarity to this user\n\n index_of_nearest_limited_rated_user = np.argsort(rated_user_similarity)[\n -self.userLimit :\n ].astype(\n np.int32\n ) # get index of users which have the highest similarity\n\n rating_of_nearest_user = self.normalized_matrix[\n item, all_users_rated_this_item[index_of_nearest_limited_rated_user]\n ] # get rating of those nearest users\n\n all_nearest_user_similarity = rated_user_similarity[\n index_of_nearest_limited_rated_user\n ]\n\n return (rating_of_nearest_user * all_nearest_user_similarity)[0] / (\n np.abs(all_nearest_user_similarity).sum() + 1e-8\n )\n\n def generate_prerequisite(self):\n self.normalize_data()\n self.generate_user_similarity_matrix()\n\n def recommend(self, user):\n self.generate_prerequisite()\n\n recommended_items_dict = {}\n ids = np.where(self.data[:, 0] == user)[0]\n items_rated_by_this_user = self.data[ids, 1].astype(np.int32)\n all_items = np.unique(self.data[:, 1].astype(np.int32))\n\n for item in all_items:\n if item not in items_rated_by_this_user:\n rating = self.predict(user, item)\n if rating > 0:\n recommended_items_dict[item] = rating\n recommended_items_dict = sorted(\n recommended_items_dict.items(), key=lambda x: x[1], reverse=True\n )\n recommended_item = []\n if len(recommended_items_dict) > 6:\n for i in range(6):\n recommended_item.append(list(recommended_items_dict)[i][0])\n else:\n for i in range(len(recommended_items_dict)):\n recommended_item.append(list(recommended_items_dict)[i][0])\n\n return recommended_item\n\n\ntry:\n jsondata = json.loads(sys.argv[1])\n arrayOfReviews = np.asarray(jsondata, dtype=np.float)\n rs = Recommendation_System(arrayOfReviews, 4)\n data = rs.recommend(int(sys.argv[2]))\n print(data)\n sys.stdout.flush()\nexcept Exception as e:\n # print(traceback.format_exc())\n sys.stdout.flush()\n\n\n","repo_name":"ZNhatAnhZ/Bookstore","sub_path":"src/controllers/recommender.py","file_name":"recommender.py","file_ext":"py","file_size_in_byte":4204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8290868315","text":"from enum import Enum\nfrom typing import TypedDict\n\nfrom sqlalchemy import Table\nfrom sqlalchemy.orm import DeclarativeBase\n\n\nclass CheckResultType(str, Enum):\n \"\"\"This class contains the types of a check result.\"\"\"\n\n PASSED = \"PASSED\"\n FAILED = \"FAILED\"\n # A check is skipped from another check's result.\n SKIPPED = \"SKIPPED\"\n # A check is disabled from the user configuration.\n DISABLED = \"DISABLED\"\n # The result of the check is unknown or Macaron cannot resolve the\n # implementation of this check.\n UNKNOWN = \"UNKNOWN\"\n\n\nclass CheckResult(TypedDict):\n \"\"\"This class stores the result of a check in a dictionary.\"\"\"\n\n check_id: str\n check_description: str\n # The string representations of the slsa requirements and their\n # corresponding slsa level.\n slsa_requirements: list[str]\n # If an element in the justification is a string,\n # it will be displayed as a string, if it is a mapping,\n # the value will be rendered as a hyperlink in the html report.\n justification: list[str | dict[str, str]]\n # human_readable_justification: str\n # result_values: dict[str, str | float | int] | list[dict[str, str | float | int]]\n result_tables: list[DeclarativeBase | Table]\n # recommendation: str\n result_type: CheckResultType\n\n\nclass SkippedInfo(TypedDict):\n \"\"\"This class stores the information about a skipped check.\"\"\"\n\n check_id: str\n suppress_comment: str\n\n\ndef get_result_as_bool(check_result_type: CheckResultType) -> bool:\n \"\"\"Return the CheckResultType as bool.\n\n This method returns True only if the result type is PASSED else it returns False.\n\n Parameters\n ----------\n check_result_type : CheckResultType\n The check result type to return the bool value.\n\n Returns\n -------\n bool\n \"\"\"\n if check_result_type in (CheckResultType.FAILED, CheckResultType.UNKNOWN):\n return False\n\n return True\n","repo_name":"laurentsimon/macaron","sub_path":"src/macaron/slsa_analyzer/checks/check_result.py","file_name":"check_result.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"12257114601","text":"def findNumber(num):\n if not 1 <= num <= 2147483647:\n return [-1, -1]\n if num == 1:\n return [2, -1]\n if num == 2147483647:\n return [-1, -1]\n if num == 2147483646:\n return [-1, 1073741823]\n\n num1 = format(num, 'b').count(\"1\")\n maxans = num + 1\n minans = num - 1\n while bin(maxans).count(\"1\") != num1:\n if maxans < 2147483647:\n maxans += 1\n else:\n maxans = -1\n break\n while bin(minans).count(\"1\") != num1:\n if minans > 1:\n minans -= 1\n else:\n minans = -1\n break\n return [maxans, minans]\n","repo_name":"PlutoaCharon/CodeExercise_Python","sub_path":"笔试/顺丰/临近二进制.py","file_name":"临近二进制.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"15281347105","text":"# 타이핑 게임 제작 및 기본 완성\n\nimport random\nimport time\nimport winsound # 사운드 출력 필요 모듈\nimport sqlite3\nimport datetime\n\n#DB생성 & Auto Commit\n#본인 DB경로\nconn = sqlite3.connect('C:/python_basic/resource/records.db', isolation_level=None)\n\n#Cursor 연결\ncursor = conn.cursor()\n\ncursor.execute(\"CREATE TABLE IF NOT EXISTS records( id IMTEGER PRIMARY KEY AUTOINCREMEMT, cor_cnt INTEGER , record text, regdate text )\")\n\n\nwords =[] #영어 단어 리스트\nn = 1 #게임 시도 횟수\ncor_cnt = 0 # 정답 개수 \n\nwith open('./resource/word.txt', 'r') as f : # with 문은 알아서 close가 됨\n for c in f :\n words.append(c.strip())\n\nprint(words) # 단어 리스트 확인\n\ninput(\"Ready? Press Enter Key!\") #게임 스타트 // 무조건 String 형태로 들어온다.\n\nstart = time.time()\n\nwhile n <= 5 :\n random.shuffle(words)\n q = random.choice(words)\n \n print()\n\n print(\"*문제 # {}\".format(n)) # {}사이에 format 안 변수 대입\n\n print(q)\n\n x = input() #타이핑 입력\n\n print()\n\n if str(q).strip() == str(x).strip(): # 입력확인(공백제거)\n print(\"PASSS\")\n #정답 소리 재생\n winsound.PlaySound('./sound/good.wav', winsound.SND_FILENAME)\n cor_cnt += 1\n else :\n\n #오답 소리 재생\n winsound.PlaySound('./sound/bad.wav', winsound.SND_FILENAME)\n\n print (\"Wrong!\")\n n += 1 # 다음 문제 전환\n\nend = time.time() # End Time 기록\n\net = end - start # 총게임 시간\net = format(et,\".3f\") # et 를 3번째 소수점 까지 나타내라 라는 format\n\nif cor_cnt>= 3:\n print(\"합격\")\nelse:\n print (\"탈락\")\n\n\n# 기록 DB 삽입\n\ncursor.execute(\"INSERT INTO records('cor_cnt','records'.'regdate') VALUES(?,?,?)\",(cor_cnt, et, datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S')))\n# 수행 시간 출력\n\nprint(\"게임 시간 : \",et,\"초\", \"정답 개수:{}\".format(cor_cnt))\n\n#시작 지점 \n\nif __name__ == '__main__':\n pass\n\n\n\n","repo_name":"shinb-bong/python_basic_study","sub_path":"section_fin -2.py","file_name":"section_fin -2.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22408017900","text":"import datetime\n\nfrom ckan.logic import side_effect_free, check_access, get_or_bust\nfrom ckan.logic import NotFound, ValidationError\n\nfrom ckan.lib.navl.dictization_functions import validate\n\nfrom ckanext.activitiestracker.logic.schema import resource_tracker_create_schema\n\nfrom ckanext.activitiestracker.model import ResourceLog\nfrom ckan.model import User\n\n@side_effect_free\ndef resource_tracker_list(context, data_dict):\n '''Return the list of trackers for a particular resource\n :param resource_id: the id of the resource\n :param limit: the number of returning results\n :param offset: the offset to start returning results from\n '''\n check_access('resource_tracker_list', context, data_dict)\n \n resource_id = data_dict.get('resource_id')\n limit = data_dict.get('limit')\n offset = data_dict.get('offset')\n session = context['session']\n query = session.query(ResourceLog)\n\n if resource_id:\n query = query.filter(ResourceLog.resource_id == resource_id)\n if limit:\n query = query.limit(int(limit))\n if offset:\n query = query.offset(int(offset))\n\n trackers = query.all()\n\n return [tracker.as_dict() for tracker in trackers]\n\ndef resource_tracker_create(context, data_dict):\n '''Append a new resource tracker to the list of resource log\n :param resource_id: the id of the resource\n :param event: the action which the user take \n :param obj_type: object type which the user action is applied to.\n :param user_id: the username of the user\n '''\n check_access('resource_tracker_create', context, data_dict)\n \n data, errors = validate(data_dict, resource_tracker_create_schema(), context)\n\n if errors:\n raise ValidationError(errors)\n \n \n logger = User.get(context.get('user'))\n if logger:\n tracker = ResourceLog(\n resource_id=data.get('resource_id'),\n event=data.get('event'),\n obj_type=data.get('obj_type'),\n user_id=logger.name,\n )\n else:\n tracker = ResourceLog(\n resource_id=data.get('resource_id'),\n event=data.get('event'),\n obj_type=data.get('obj_type'),\n user_id=None,\n )\n\n tracker.save()\n\n return tracker.as_dict()","repo_name":"Jiaza492/ckanext-activitiestracker","sub_path":"ckanext/activitiestracker/logic/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35617620674","text":"###################################################################\n# Imported Files\nfrom cmu_112_graphics import *\nfrom helper import *\n###################################################################\n# this button class was modified for use in Hack112, but it was originally\n# written for use in the term project\n\n# Button is the superclass for every pressable object in the program\n# –> button must be rectangular\n\nclass Button():\n\n def __init__(self, dimension, location=None, action=None, \n fill='blue', outline=None, label=None, textFill='black', \n r=10, fontSize=12, textAnchor='center', font='Calbri', style='roman',\n overlay=None, overlayLocation=(0,0), overlayAlpha=254, overlayScale=1\n ):\n \n # tuples(x, y) of center of button or None \n self.location = location\n\n # tuples(width, height)\n self.width, self.height = dimension\n\n # functions that perform a given action when the button is pressed\n self.action = action\n\n # color name\n self.fill = fill\n self.outline = outline\n self.label = label\n self.textFill = textFill\n\n self.font = font\n self.style = style # bold underline italics roman\n self.fontAnchor = textAnchor # supports center and se\n\n # int\n self.r = r \n self.fontSize = fontSize \n\n self.overlay = overlay\n self.overlayLocation = overlayLocation\n self.overlayAlpha = overlayAlpha # transparency of image\n self.overlayScale = overlayScale # scale of the image\n if self.overlay != None:\n self.getOverlay(overlay)\n\n # process the overlay image\n def getOverlay(self, path):\n self.overlay = Image.open(path)\n self.overlay = self.scaleImage(self.overlay, self.overlayScale)\n if path[-3:] == 'png':\n # based on https://github.com/python-pillow/Pillow/issues/4687\n # makes the image translucent without displaying already transparent pixels\n overlayCopy = self.overlay.copy()\n overlayCopy.putalpha(self.overlayAlpha) # increases transparency\n self.overlay.paste(overlayCopy, self.overlay)\n else: # normal transparency for non-transparent images\n self.overlay.putalpha(self.overlayAlpha)\n if self.location != None:\n xButton, yButton = self.location\n width, height = self.overlay.size\n x, y = xButton + self.overlayLocation[0], yButton + self.overlayLocation[1]\n lowX, lowY, highX, highY = 0, 0, width, height # default values\n if x-width/2 <= xButton-self.width/2:\n lowX = (xButton-self.width//2) - (x-width//2) + self.overlayLocation[0]\n if x+width/2 >= xButton+self.width/2:\n highX = width-((x+width//2) - (xButton+self.width//2) - self.overlayLocation[0])\n if y-height/2 <= yButton-self.height/2:\n lowY = (yButton-self.height//2) - (y-height//2) + self.overlayLocation[1]\n if y+height/2 >= yButton+self.height/2:\n highY = height - ((y+height//2) - (yButton+self.height//2) - self.overlayLocation[1])\n self.overlay = self.overlay.crop((lowX, lowY, highX, highY))\n\n\n\n # copied directly from cmu_112_graphics\n def scaleImage(self, image, scale, antialias=False):\n # antialiasing is higher-quality but slower\n resample = Image.ANTIALIAS if antialias else Image.NEAREST\n return image.resize((round(image.width*scale), round(image.height*scale)), resample=resample)\n\n def __repr__(self):\n if self.label != None:\n return self.label\n elif self.action != None:\n return self.action.__name__\n else: return 'unknown button'\n\n\n def __eq__(self, other):\n if (isinstance(other, Button) and (self.action == None or other.action == None)):\n return False\n return self.action == other.action\n\n # returns True if the button isPressed\n # –> assumes that button is rectangular (doesn't account for rounded corners)\n def isPressed(self, x, y):\n # to prevent indexOutOfBounds error\n if self.location == None: \n return False\n return (abs(self.location[0] - x) < self.width/2 and\n abs(self.location[1] - y) < self.height/2)\n\n # draws a rounded square button\n def draw(self, canvas):\n if self.location == None: return # does not draw if location is None\n x, y = self.location\n create_roundedRectangles(canvas, \n x - self.width//2, y - self.height//2,\n x + self.width//2, y + self.height//2,\n r=self.r, fill=self.fill, outline=self.outline)\n \n \n if self.overlay != None:\n canvas.create_image(x, y, image=ImageTk.PhotoImage(self.overlay))\n\n\n if self.label != None:\n if self.fontAnchor == 'center':\n canvas.create_text(x, y, \n text=f'{self.label}', \n font = (self.font, self.fontSize, self.style),\n anchor='center', \n justify='center', \n fill=self.textFill)\n else:\n margin=10\n canvas.create_text(x+self.width//2-margin, y+self.height//2-margin, \n text=f'{self.label}', \n font = (self.font, self.fontSize, self.style),\n anchor='se', \n justify='right', \n fill=self.textFill)\n\n \n\n\n\n###################################################################\n# Test Functions\n\ndef testButtonClass():\n print('Testing Button...', end='')\n button1 = Button((5,10), (10,20), lambda: 'foo')\n assert(button1.action() == 'foo')\n assert(button1.location[0] == 10)\n assert(button1.location[1] == 20)\n assert(button1.isPressed(12, 21) == True)\n assert(button1.isPressed(9, 18) == True)\n assert(button1.isPressed(5, 27) == False)\n print('Passed!')\n\n\n# def appStarted(app):\n# app.button = Button((50,50), (100,100), lambda: print('foo'), fill='royalBlue')\n\n# def mousePressed(app, event):\n# if app.button.isPressed(event.x, event.y):\n# app.button.action()\n\n# def redrawAll(app, canvas):\n# app.button.draw(canvas)\n\n###################################################################\n# Code to run\n\ntestButtonClass()\n# runApp(width=200, height=200)\n\n\n","repo_name":"Wikignometry/bridge-buddy","sub_path":"button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":6616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2823333021","text":"import os\n\nINPUT_FILE = os.path.join(os.path.dirname(__file__), 'data', 'day01.txt')\n\ndef part_one():\n maxi = 0\n curr = 0\n\n with open(INPUT_FILE) as file:\n for line in file:\n curr = curr + int(line) if line.strip() else 0\n if curr > maxi:\n maxi = curr\n\n print(maxi)\n\ndef part_two():\n curr = 0\n per_elf = []\n\n with open(INPUT_FILE) as file:\n for line in file:\n if line.strip():\n curr += int(line)\n else:\n per_elf.append(curr)\n curr = 0\n\n print(sum(sorted(per_elf, reverse=True)[:3]))\n\nif __name__ == '__main__':\n part_one()\n part_two()\n","repo_name":"christospi/aoc-2022","sub_path":"day01.py","file_name":"day01.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27569775423","text":"import re\nfrom collections import defaultdict\n\nwith open('input_04.txt') as f:\n\tlines = f.read().splitlines()\n\nguards = defaultdict(lambda:[0]*59)\nid = 0\nfalls = 0\nfor line in sorted(lines):\t\n\tif 'Guard' in line:\n\t\tid = int(re.findall('#(\\d+)', line)[0])\n\t\tcontinue\n\tminute = int(re.findall(':(\\d+)\\]', line)[0])\n\tif 'falls asleep' in line: \n\t\tfalls = minute\n\telse:\n\t\tfor m in range(falls, minute):\n\t\t\tguards[id][m] += 1\n\ndef star1(guards):\n\t_, guard_id = max((sum(minutes), guard) for (guard, minutes) in guards.items())\n\t_, chosen_minute = max((m, idx) for (idx, m) in enumerate(guards[guard_id]))\n\treturn guard_id * chosen_minute\n\ndef star2(guards):\t\n\t_, chosen_minute, guard_id = max((minute, idx, guard) for (guard, minutes) in guards.items() for (idx, minute) in enumerate(minutes))\n\treturn guard_id * chosen_minute\n\nprint(\"Star 1:\", star1(guards))\nprint(\"Star 2:\", star2(guards))","repo_name":"lukaszroz/advent-of-code-2018","sub_path":"day04.py","file_name":"day04.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14483748566","text":"\"\"\"Import modules.\"\"\"\nimport math\nimport numpy\n\n\ndef vectorNorm(data, axis=None, out=None):\n \"\"\"Calculate norm of a vector.\"\"\"\n data = numpy.array(data, dtype=numpy.float64, copy=True)\n if out is None:\n if data.ndim == 1:\n return math.sqrt(numpy.dot(data, data))\n data *= data\n out = numpy.atleast_1d(numpy.sum(data, axis=axis))\n numpy.sqrt(out, out)\n return out\n else:\n data *= data\n numpy.sum(data, axis=axis, out=out)\n numpy.sqrt(out, out)\n\n\ndef rotationFromQuaternion(q):\n \"\"\"Convert quaternion to euler-axes-angle (vrml).\"\"\"\n v = [0.0, 0.0, 0.0, 0.0]\n v[3] = 2.0 * math.acos(q[0])\n if (v[3] < 0.0001):\n # if v[3] close to zero then direction of axis not important\n v[0] = 0.0\n v[1] = 0.0\n v[2] = 1.0\n else:\n # normalise axes\n n = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])\n v[0] = q[1] / n\n v[1] = q[2] / n\n v[2] = q[3] / n\n return v\n\n\ndef convertRPYtoQuaternions(rpy):\n \"\"\"Convert RPY to quaternions.\"\"\"\n cy = math.cos(rpy[2] * 0.5)\n sy = math.sin(rpy[2] * 0.5)\n cp = math.cos(rpy[1] * 0.5)\n sp = math.sin(rpy[1] * 0.5)\n cr = math.cos(rpy[0] * 0.5)\n sr = math.sin(rpy[0] * 0.5)\n\n q = [0, 0, 0, 0]\n q[0] = cy * cp * cr + sy * sp * sr\n q[1] = cy * cp * sr - sy * sp * cr\n q[2] = sy * cp * sr + cy * sp * cr\n q[3] = sy * cp * cr - cy * sp * sr\n return q\n\n\ndef convertRPYtoEulerAxis(rpy):\n \"\"\"Convert RPY angles to Euler angles.\"\"\"\n return rotationFromQuaternion(convertRPYtoQuaternions(rpy))\n\n\ndef multiplyMatrix(mat1, mat2):\n \"\"\"Multiply two matrices.\"\"\"\n matrix = []\n matrix.append(mat1[0] * mat2[0] + mat1[1] * mat2[3] + mat1[2] * mat2[6])\n matrix.append(mat1[0] * mat2[1] + mat1[1] * mat2[4] + mat1[2] * mat2[7])\n matrix.append(mat1[0] * mat2[2] + mat1[1] * mat2[5] + mat1[2] * mat2[8])\n matrix.append(mat1[3] * mat2[0] + mat1[4] * mat2[3] + mat1[5] * mat2[6])\n matrix.append(mat1[3] * mat2[1] + mat1[4] * mat2[4] + mat1[5] * mat2[7])\n matrix.append(mat1[3] * mat2[2] + mat1[4] * mat2[5] + mat1[5] * mat2[8])\n matrix.append(mat1[6] * mat2[0] + mat1[7] * mat2[3] + mat1[8] * mat2[6])\n matrix.append(mat1[6] * mat2[1] + mat1[7] * mat2[4] + mat1[8] * mat2[7])\n matrix.append(mat1[6] * mat2[2] + mat1[7] * mat2[5] + mat1[8] * mat2[8])\n return matrix\n\n\ndef matrixFromRotation(rotation):\n \"\"\"Get the 3x3 matrix associated to this VRML rotation.\"\"\"\n c = math.cos(rotation[3])\n s = math.sin(rotation[3])\n t1 = 1.0 - c\n t2 = rotation[0] * rotation[2] * t1\n t3 = rotation[0] * rotation[1] * t1\n t4 = rotation[1] * rotation[2] * t1\n matrix = []\n matrix.append(rotation[0] * rotation[0] * t1 + c)\n matrix.append(t3 - rotation[2] * s)\n matrix.append(t2 + rotation[1] * s)\n matrix.append(t3 + rotation[2] * s)\n matrix.append(rotation[1] * rotation[1] * t1 + c)\n matrix.append(t4 - rotation[0] * s)\n matrix.append(t2 - rotation[1] * s)\n matrix.append(t4 + rotation[0] * s)\n matrix.append(rotation[2] * rotation[2] * t1 + c)\n return matrix\n\n\ndef rotationFromMatrix(R):\n R = numpy.array(R).reshape(3, 3)\n # code from here (slightly modified):\n # https://rock-learning.github.io/pytransform3d/_modules/pytransform3d/rotations.html#axis_angle_from_matrix\n angle = numpy.arccos((numpy.trace(R) - 1.0) / 2.0)\n epsilon = 1e-4\n if angle < epsilon:\n return numpy.array([1.0, 0.0, 0.0, 0.0])\n a = numpy.empty(4)\n\n # We can usually determine the rotation axis by inverting Rodrigues'\n # formula. Subtracting opposing off-diagonal elements gives us\n # 2 * sin(angle) * e,\n # where e is the normalized rotation axis.\n axis_unnormalized = numpy.array(\n [R[2, 1] - R[1, 2], R[0, 2] - R[2, 0], R[1, 0] - R[0, 1]])\n\n if numpy.pi - angle < epsilon:\n # The threshold is a result from this discussion:\n # https://github.com/rock-learning/pytransform3d/issues/43\n # The standard formula becomes numerically unstable, however,\n # Rodrigues' formula reduces to R = I + 2 (ee^T - I), with the\n # rotation axis e, that is, ee^T = 0.5 * (R + I) and we can find the\n # squared values of the rotation axis on the diagonal of this matrix.\n # We can still use the original formula to reconstruct the signs of\n # the rotation axis correctly.\n sign = numpy.sign(axis_unnormalized)\n a[:3] = numpy.sqrt(0.5 * (numpy.diag(R) + 1.0)) * numpy.where(sign == 0, 1, sign)\n # print('test', abs(angle - numpy.pi), numpy.diag(R), numpy.sqrt(0.5 * (numpy.diag(R) + 1.0)), axis_unnormalized)\n else:\n a[:3] = axis_unnormalized\n # The norm of axis_unnormalized is 2.0 * numpy.sin(angle), that is, we\n # could normalize with a[:3] = a[:3] / (2.0 * numpy.sin(angle)),\n # but the following is much more precise for angles close to 0 or pi:\n a[:3] /= numpy.linalg.norm(a[:3])\n\n a[3] = angle\n return a\n\n\ndef rotateVector(vector, rotation):\n \"\"\"Rotate the vector by the VRML rotation.\"\"\"\n # multiply matrix by vector\n matrix = matrixFromRotation(rotation)\n v = []\n v.append(vector[0] * matrix[0] + vector[1] * matrix[1] + vector[2] * matrix[2])\n v.append(vector[0] * matrix[3] + vector[1] * matrix[4] + vector[2] * matrix[5])\n v.append(vector[0] * matrix[6] + vector[1] * matrix[7] + vector[2] * matrix[8])\n return v\n\n\ndef combineRotations(rotation1, rotation2):\n \"\"\"Combine two axis-angle rotations.\"\"\"\n matrix1 = matrixFromRotation(rotation1)\n matrix2 = matrixFromRotation(rotation2)\n matrixRes = multiplyMatrix(matrix1, matrix2)\n return rotationFromMatrix(matrixRes)\n\n\ndef combineTranslations(translation1, translation2):\n \"\"\"Combine two translations.\"\"\"\n result = []\n for (component1, component2) in zip(translation1, translation2):\n result.append(component1+component2)\n return result\n","repo_name":"cyberbotics/urdf2webots","sub_path":"urdf2webots/math_utils.py","file_name":"math_utils.py","file_ext":"py","file_size_in_byte":5960,"program_lang":"python","lang":"en","doc_type":"code","stars":111,"dataset":"github-code","pt":"21"} +{"seq_id":"22976092017","text":"n, m, v = map(int,input().split())\n# 1. 인접 행렬\n# 노드 번호가 1부터 n까지이므로 편리함을 위해 n+1로함\n# 1번과 2번 노드가 연결되어 있다면 a[1][2], a[2][1]에 1을 입력한다.\na1 = [[0]*(n+1) for _ in range(n+1)]\n\nfor _ in range(m):\n x, y = map(int,input().split())\n a1[x][y] = 1\n a1[y][x] = 1\n\nfor x in a1:\n print(x)\n\n# 2. 인접 리스트\n# n+1개의 리스트를 만들어 두고\n# 1번과 2번 노드가 연결되어 있다면 1번째 리스트에 2추가, 2번째 리스트에 1 추가\n# 정점 번호 작은 순이면 정렬 해주어야 함\na2 = [list() for _ in range(n+1)]\nfor _ in range(m):\n x, y = map(int,input().split())\n a2[x].append(y)\n a2[y].append(x)\nfor x in a2:\n x.sort()\n\n# 큐와 방문의 중복을 방지하기 위한 체크배열이 필요하다.\n# 체크는 큐에 처음 들어가는 시점에 해준다.\nimport queue\nchk = [False]*(n*1)\nq = queue.Queue()\nq.put(v)\nchk[v] = True","repo_name":"NewWisdom/Algorithm","sub_path":"파이썬으로 시작하는 삼성 SW역량테스트/5. DFS와 BFS/BFS.py","file_name":"BFS.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"41581541572","text":"import numpy as np\nimport gemx\nimport sys\nimport random\nimport argparse\nimport time\nfrom test import GemmTest\n\ndef test_multiInstrv1(int_range, m, k, n, add_bias=False):\n print (\"test_multiInstrv1: %d %d %d %d\" % (int_range, m, k, n)) \n A = np.random.randint(low=-int_range, high=int_range, size=(m, k), dtype=np.int16)\n B = np.random.randint(low=-int_range, high=int_range, size=(k, n), dtype=np.int16)\n C = np.zeros ((m, n), dtype=np.int16);\n D = np.random.randint(low=-int_range, high=int_range, size=(m, k), dtype=np.int16)\n E = np.zeros ((m, n), dtype=np.int16);\n b0 = np.zeros ((m, n), dtype=np.int32);\n \n b1 = np.zeros ((m, n), dtype=np.int32);\n \n if add_bias == True:\n b0 = np.random.randint(low=-int_range, high=int_range, size=(m, n), dtype=np.int32)\n b1 = np.random.randint(low=-int_range, high=int_range, size=(m, n), dtype=np.int32) \n gemx.sendMat(A)\n gemx.sendMat(B)\n gemx.sendMat(b0)\n gemx.sendMat(C)\n gemx.sendMat(D) \n gemx.sendMat(E)\n gemx.sendMat(b1) \n gemx.addGEMMOp(A, B, C, b0, 1, 0)\n gemx.addGEMMOp(D, C, E, b1, 1, 0)\n gemx.execute()\n gemx.getMat(C)\n gemx.getMat(E)\n print(\"test C\")\n test.multiply_and_cmp(C, A, B, b0, m, n, [1, 0])\n print(\"test E\")\n test.multiply_and_cmp(E, D, C, b1, m, n, [1, 0])\n\nif __name__ == '__main__':\n np.random.seed(123) # for reproducibility\n test=GemmTest()\n args, xclbin_opts = gemx.processCommandLine()\n gemx.createGEMMHandle(args, xclbin_opts)\n \n for PE in range(int(xclbin_opts[\"GEMX_numKernels\"])):\n test.test_basic_randint( PE, 512, 512, 128, [16,17])\n test.test_basic_randint( PE, 256, 512, 128, [2,18])\n test.test_basic_randint( PE, 2048, 512, 128, [4,18])\n test.test_basic_randint( PE, 2048, 512, 128, [128,17])\n\n # test.test_rand_basic (32764, 0, 5, [1,0]) # larger matrix size will lead to hw timeout error in regression test\n test_multiInstrv1(32764, 512, 512, 128, True) \n\n \n","repo_name":"ramcn/gemxx-2017","sub_path":"gemx/tests/test_gemm.py","file_name":"test_gemm.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42731527335","text":"def classifica_lista(lista):\n if len(lista)<2:\n print('nenhum')\n i=1\n a=0\n lista_c=[]\n lista_c=[lista[0]]\n while i lista_c[a]:\n lista_c.append(lista[i])\n a+=1\n i+=1\n lista_d=[]\n lista_d=[lista[0]] \n j=1\n p=0\n while j